Example #1
0
        private async Task <bool> SendLobbyRequest()
        {
            LobbyRequest request = new LobbyRequest
            {
                LobbyId   = lobbyId,
                PublicKey = App.Instance.CryptoHandler.SerializePublicKey(),
                Signature = App.Instance.CryptoHandler.CalculateSecuritySignature(),
                Latitude  = App.Instance.Locator.Position?.Latitude ?? 0.0,
                Longitude = App.Instance.Locator.Position?.Longitude ?? 0.0
            };

            var response = await App.Instance.Connector.SendRequest(request, 30000);

            if (response != null && response is LobbyResponse lobbyResp && lobbyResp.Success)
            {
                bool result = false;
                await semaphoreSlim.WaitAsync();

                try
                {
                    RefreshMemberList(lobbyResp.MemberPublicKeys);
                    lobbyId = lobbyResp.LobbyId;
                    result  = true;
                }
                finally
                {
                    semaphoreSlim.Release();
                }
                return(result);
            }

            return(false);
        }
Example #2
0
        public IActionResult Post([FromBody] LobbyRequest parameters, [FromRoute] int id)
        {
            if (parameters == null || parameters.token == null)
            {
                return(BadRequest(new Response("Wrong parameters", null)));
            }

            string token = parameters.token;
            string error = "";

            if (!TokenManager.CheckUser(token))
            {
                error = ErrorTypes.UNAUTH_USER_ERROR.ToString();
            }

            Response resp;

            if (error == "")
            {
                Lobby  curLobby = Lobbies.GetLobby(id);
                Player p        = TokenManager.GetPlayer(token);
                if (curLobby == null)
                {
                    error = ErrorTypes.NONEXIST_LOBBY_ERROR.ToString();
                    resp  = new Response(error, null);
                }
                else if (curLobby.GetPlayer(token) != null)
                {
                    error = ErrorTypes.ALREADY_CONNECT_TO_LOBBY_ERROR.ToString();
                    resp  = new Response(error, null);
                }
                else if (p.Status != PlayerStatus.Default)
                {
                    error = ErrorTypes.ALREADY_CONNECT_TO_DIFF_LOBBY_ERROR.ToString();
                    resp  = new Response(error, null);
                }
                else if (curLobby.Status != LobbyStatus.WaitingForPlayer)
                {
                    error = ErrorTypes.FULL_LOBBY_ERROR.ToString();
                    resp  = new Response(error, null);
                }
                else
                {
                    curLobby.ConnectPlayer(p);
                    resp = new Response(error, new LobbyResponse(curLobby));
                }
            }
            else
            {
                resp = new Response(error, null);
            }

            IActionResult res = Ok(resp);

            return(res);
        }
Example #3
0
        public LobbyResponse Lobby(ClientSession session, LobbyRequest request)
        {
            session.PublicKey = request.PublicKey;
            var response = new LobbyResponse();

            response.Token = request.Token;
            try
            {
                if (session.HasLobby)
                {
                    var chatLobby = ChatLobbyManager.GetLobby(session.ChatLobbyId);
                    response.Latitude         = chatLobby.Latitude;
                    response.Longitude        = chatLobby.Longitude;
                    response.LobbyId          = chatLobby.LobbyId;
                    response.MemberPublicKeys = chatLobby.GetMemberKeys();
                    response.Range            = chatLobby.Range;
                    response.Success          = true;
                    return(response);
                }
                if (ChatLobbyManager.IsLobbyAvailable())
                {
                    var chatLobbyId = ChatLobbyManager.GetIdForNextOpenLobby();
                    var chatLobby   = ChatLobbyManager.GetLobby(chatLobbyId);
                    chatLobby.JoinLobby(session);
                    response.Latitude         = chatLobby.Latitude;
                    response.Longitude        = chatLobby.Longitude;
                    response.LobbyId          = chatLobby.LobbyId;
                    response.MemberPublicKeys = chatLobby.GetMemberKeys();
                    response.Range            = chatLobby.Range;
                    response.Success          = true;
                    return(response);
                }
                else
                {
                    var chatLobbyId = ChatLobbyManager.CreateLobby(session, request.Longitude, request.Latitude);
                    var chatLobby   = ChatLobbyManager.GetLobby(chatLobbyId);
                    response.Latitude         = chatLobby.Latitude;
                    response.Longitude        = chatLobby.Longitude;
                    response.LobbyId          = chatLobby.LobbyId;
                    response.MemberPublicKeys = chatLobby.GetMemberKeys();
                    response.Range            = chatLobby.Range;
                    response.Success          = true;
                    return(response);
                }
            }
            catch (Exception exc)
            {
                log.Error("Error on LobbyRequest", exc);
                response.Success = false;
                return(response);
            }
        }
        private void DoAdminRequest(LobbyRequest request, string message, Admin chatAdmin)
        {
            message = message.Remove(0, message.IndexOf(":") + 1);
            StreamWriter sw = new StreamWriter(chatAdmin.ClientSocket.GetStream());

            switch (request)
            {
            case LobbyRequest.Connect:
            {
                DoRequestConnect(sw, message, chatAdmin);
                chatAdmin.IsInRoom = true;
                break;
            }

            case LobbyRequest.Exit:
            {
                var roomExit = GetByName(message);
                int ind      = roomExit.GetAdminIndex();
                roomExit.messageCounter[ind] = roomExit.messages;
                chatAdmin.IsInRoom           = false;
                break;
            }

            case LobbyRequest.Message:
            {
                DoRequestMessage(sw, message, chatAdmin);
                break;
            }

            case LobbyRequest.Refresh:
            {
                sw.WriteLine(GetMissedMessageCount(chatAdmin));
                sw.Flush();
                Thread.Sleep(100);
                break;
            }

            case LobbyRequest.Admin:
            {
                DoRequestAdmin(sw, message, chatAdmin);
                break;
            }

            default:
                break;
            }
        }
        public static LobbyRequest GetRequest(string cmd)
        {
            cmd = cmd.Remove(cmd.IndexOf(":"));
            LobbyRequest req = LobbyRequest.Create;

            switch (cmd)
            {
            case "create":
                req = LobbyRequest.Create;
                break;

            case "connect":
                req = LobbyRequest.Connect;
                break;

            case "exit":
                req = LobbyRequest.Exit;
                break;

            case "message":
                req = LobbyRequest.Message;
                break;

            case "refresh":
                req = LobbyRequest.Refresh;
                break;

            case "admin":
                req = LobbyRequest.Admin;
                break;

            case "logout":
                req = LobbyRequest.Logout;
                break;

            case "private":
                req = LobbyRequest.Private;
                break;

            default:
                break;
            }

            return(req);
        }
Example #6
0
        /// <summary>
        /// Method that processes lobby retrieval request.
        /// </summary>
        /// <param name="request">The <see cref="LobbyRequest"/>.</param>
        /// <returns>The <see cref="LobbyResult"/>.</returns>
        LobbyResult IRequestHandler <LobbyRequest, LobbyResult> .ProcessRequest(LobbyRequest request)
        {
            if (!this.Lobbies.TryGetValue(request.Id, out Game.Lobby lobby))
            {
                return(new LobbyResult()
                {
                    Success = false,
                    Details = "Could not find lobby with id: " + request.Id.ToString(),
                });
            }

            return(new LobbyResult()
            {
                Lobby = new Communication.API.Schemas.Lobby()
                {
                    Id = lobby.Id,
                    Name = lobby.Name,
                    PlayerCount = lobby.PlayerCount,
                },
            });
        }
Example #7
0
    public void HostGame(bool isPublic, int map, int playerAmount, int dimensionAmount)
    {
        LobbyRequest request = new LobbyRequest();

        request.packetType = (int)GameClientPackets.CreateLobby;
        request.username   = info.username;
        if (isPublic)
        {
            request.isPublic = 1;
        }
        else
        {
            request.isPublic = 0;
        }
        request.map             = map;
        request.playerAmount    = playerAmount;
        request.dimensionAmount = dimensionAmount;
        string json = JsonUtility.ToJson(request);

        ws.Send(json);
    }
Example #8
0
        public override async Task HandleLobbyAsync(string roomId, string playerId, WebSocket playerConn, string receivedData)
        {
            Room         lobby            = null;
            GameRoom     gameRoom         = null;
            Task         find_matchmaking = null;
            LobbyRequest request          = JsonConvert.DeserializeObject <LobbyRequest>(receivedData);

            switch (request.eventType)
            {
            case "chat-message":
                if (!String.IsNullOrWhiteSpace(request.data))
                {
                    await base.SendToAllInLobbyAsync(roomId, JsonConvert.SerializeObject(
                                                         new LobbyChatResponse(playerId, request.data, DateTime.Now.ToShortTimeString())));
                }
                break;

            case "cancel-matchmaking":
                await CancelMatchmaking(roomId);

                break;

            case "start-matchmaking":
                lobby = base._lobby_rooms.GetRoomById(roomId);
                if (lobby.Players.hostID != playerId)
                {
                    throw new LobbyWarningException("Only the room's host can start matchmaking");
                }
                else if (!lobby.Players.matchmakingRoom)
                {
                    throw new LobbyWarningException("Invalid room for matchmaking. 1-2 players are allowed.");
                }
                else
                {
                    if (find_matchmaking != null)
                    {
                        throw new LobbyWarningException("Room already started matchmaking");
                    }
                    else
                    {
                        _matchmaking.AddRoomToQueue(lobby);
                        // notify other players in the lobby
                        await base.SendToAllInLobbyAsync(roomId, JsonConvert.SerializeObject(
                                                             new LobbyAlertResponse("finding-match", "true")));

                        find_matchmaking = Task.Run(
                            async() =>
                        {
                            Console.WriteLine("Start search");
                            await Task.Run(() => gameRoom = _matchmaking.GetGameRoom(lobby));
                            if (gameRoom != null)
                            {
                                Console.WriteLine("Found");

                                base._ingame_rooms.AddMatchMakingGameRoom(gameRoom);
                                await base.SendToAllInLobbyAsync(roomId, JsonConvert.SerializeObject(
                                                                     new LobbyAlertResponse("game-started", gameRoom.roomId)));

                                _matchmaking.DeleteGameRoom(lobby.roomId, gameRoom.roomId);
                                await gameRoom.GameInstance.loadGameInfo();
                            }
                        });
                    }
                }
                break;

            case "start-game":
                lobby = base._lobby_rooms.GetRoomById(roomId);
                if (lobby.Players.hostID != playerId)
                {
                    throw new LobbyWarningException("Only the room's host can start the game");
                }
                else if (lobby.Players.PlayerCount < 4)
                {
                    throw new LobbyWarningException("Room should be full before starting the game");
                }
                else
                {
                    GameRoom room = base._ingame_rooms.CreateRoom(lobby.Players.PlayerList);

                    await base.SendToAllInLobbyAsync(roomId, JsonConvert.SerializeObject(
                                                         new LobbyAlertResponse("game-started", room.roomId)));

                    await room.GameInstance.loadGameInfo();
                }
                break;

            default:
                throw new LobbyWarningException("Invalid Request Type");
            }
        }
        private void DoRequest(LobbyRequest request, string message, Client client)
        {
            message = message.Remove(0, message.IndexOf(":") + 1);
            StreamWriter sw = new StreamWriter(client.ClientSocket.GetStream());

            switch (request)
            {
            case LobbyRequest.Create:
            {
                if (!client.IsBanned)
                {
                    DoRequestCreate(message, client);
                    sw.WriteLine("create:yes");
                    sw.Flush();
                    Thread.Sleep(100);
                }
                break;
            }

            case LobbyRequest.Connect:
            {
                DoRequestConnect(sw, message, client);
                client.IsInRoom = true;
                break;
            }

            case LobbyRequest.Exit:
            {
                var roomExit = GetByName(message);
                int ind      = roomExit.GetClientIndex(client);
                roomExit.messageCounter[ind] = roomExit.messages;
                client.IsInRoom = false;
                break;
            }

            case LobbyRequest.Message:
            {
                if (!client.IsBanned)
                {
                    DoRequestMessage(sw, message, client);
                }
                break;
            }

            case LobbyRequest.Refresh:
            {
                sw.WriteLine(GetMissedMessageCount(client));
                sw.Flush();
                Thread.Sleep(100);
                break;
            }

            case LobbyRequest.Logout:
            {
                var room = GetByName(message);
                room.RemoveClient(client);
                break;
            }

            case LobbyRequest.Private:
            {
                DoRequestPrivate(sw, message, client.Name);
                break;
            }

            default:
                break;
            }
        }