Example #1
0
        public void SetInfo(GameInfoPacket gameInfo, GamesListView owner)
        {
            if (gameNameText)
            {
                gameNameText.text = gameInfo.IsPasswordProtected ? $"{gameInfo.Name} <color=yellow>[Password]</color>" : gameInfo.Name;
            }

            if (gameAddressText)
            {
                gameAddressText.text = gameInfo.Address;
            }

            if (gameRegionText)
            {
                string region = string.IsNullOrEmpty(gameInfo.Region) ? "International" : gameInfo.Region;
                gameRegionText.text = $"Region: <color=yellow>{region}</color>";
            }

            if (gamePlayersText)
            {
                string maxPleyers = gameInfo.MaxPlayers <= 0 ? "∞" : gameInfo.MaxPlayers.ToString();
                gamePlayersText.text = $"Players: <color=yellow>{gameInfo.OnlinePlayers} / {maxPleyers}</color>";
            }

            if (connectButton)
            {
                connectButton.AddOnClickListener(() => {
                    owner.StartGame(gameInfo);
                });
            }
        }
Example #2
0
        /// <summary>
        /// Test sign in callback
        /// </summary>
        /// <param name="accountInfo"></param>
        /// <param name="error"></param>
        private void SignInCallback(ClientAccountInfo accountInfo, string error)
        {
            if (accountInfo == null)
            {
                logger.Error(error);
                return;
            }

            logger.Debug($"Signed in successfully as {accountInfo.Username}");
            logger.Debug("Finding games...");

            Mst.Client.Matchmaker.FindGames((games) =>
            {
                if (games.Count == 0)
                {
                    logger.Error("No test game found");
                    return;
                }

                logger.Debug($"Found {games.Count} games");

                // Get first game fromlist
                GameInfoPacket firstGame = games.First();

                // Let's try to get access data for room we want to connect to
                GetRoomAccess(firstGame.Id);
            });
        }
Example #3
0
        protected virtual void OnJoinLobbyClick(GameInfoPacket packet)
        {
            //var loadingPromise = Msf.Events.FireWithPromise(Msf.EventNames.ShowLoading, "Joining lobby");
//
            //Msf.Client.Lobbies.JoinLobby(packet.Id, (lobby, error) => {
            //    loadingPromise.Finish();
//
            //    if (lobby == null) {
            //        Msf.Events.Fire(Msf.EventNames.ShowDialogBox, DialogBoxData.CreateError(error));
            //        return;
            //    }
//
            //    // Hide this window
            //    gameObject.SetActive(false);
//
            //    var lobbyUi = FindObjectOfType<LobbyUi>();
//
            //    if (lobbyUi == null && MsfUi.Instance != null) {
            //        // Try to get it through MsfUi
            //        lobbyUi = MsfUi.Instance.LobbyUi;
            //    }
//
            //    if (lobbyUi == null) {
            //        Logs.Error("Couldn't find appropriate UI element to display lobby data in the scene. " +
            //                   "Override OnJoinLobbyClick method, if you want to handle this differently");
            //        return;
            //    }
//
            //    lobbyUi.gameObject.SetActive(true);
            //    lobby.SetListener(lobbyUi);
            //});
        }
Example #4
0
    public void HandleFindAppropriateGame(IIncommingMessage message)
    {
        var            list     = new List <GameInfoPacket>();
        GameInfoPacket toreturn = null;
        var            filters  = new Dictionary <string, string>().FromBytes(message.AsBytes());

        foreach (var provider in GameProviders)
        {
            list.AddRange(provider.GetPublicGames(message.Peer, filters));
        }
        foreach (var actualGame in list)
        {
            if (actualGame.OnlinePlayers < 2)//si il n'y a pas deux joueurs
            {
                toreturn = actualGame;
                break;
            }
        }
        if (toreturn != null)
        {
            message.Respond(toreturn.ToBytes(), ResponseStatus.Success);
        }
        else
        {
            message.Respond("", ResponseStatus.Failed);
        }

        // Convert to generic list and serialize to bytes
    }
        public void StartGame(GameInfoPacket gameInfo)
        {
            Msf.Options.Set(MsfDictKeys.autoStartRoomClient, true);
            Msf.Options.Set(MsfDictKeys.roomId, gameInfo.Id);

            ScenesLoader.LoadSceneByName("Room", (progressValue) =>
            {
                Msf.Events.Invoke(EventKeys.showLoadingInfo, $"Loading scene {Mathf.RoundToInt(progressValue * 100f)}% ... Please wait!");
            }, null);
        }
        public void StartGame(GameInfoPacket gameInfo)
        {
            Msf.Options.Set(MsfDictKeys.roomId, gameInfo.Id);

            if (gameInfo.IsPasswordProtected)
            {
                Msf.Events.Invoke(MsfEventKeys.showPasswordDialogBox,
                                  new PasswordInputDialoxBoxEventMessage("Room is required the password. Please enter room password below",
                                                                         () =>
                {
                    OnStartGameEvent?.Invoke();
                }));
            }
            else
            {
                OnStartGameEvent?.Invoke();
            }
        }
        public void Setup(GameInfoPacket data)
        {
            RawData = data;
            IsLobby = data.infoType == GameInfoType.Lobby;
            SetIsSelected(false);
            Name.text = data.Name;
            GameId    = data.Id;
            LockImage.SetActive(data.IsPasswordProtected);

            isPreGame = bool.Parse(data.Properties [MsfDictKeys.IsPreGame]);

            /*
             *          if (data.MaxPlayers > 0)
             *                  Online.text = string.Format("{0}/{1}", data.OnlinePlayers, data.MaxPlayers);
             *          else
             *                  Online.text = data.OnlinePlayers.ToString();
             */
            MapName.text = "Snake";//data.Properties.ContainsKey(MsfDictKeys.MapName) ? data.Properties[MsfDictKeys.MapName] : UnknownMapName;
        }
    public void SetData(GameInfoPacket data)
    {
        _data = data;
        if (textRoomName != null)
        {
            textRoomName.text = data.Name;
        }
        if (textSceneName != null)
        {
            textSceneName.text = data.Properties.ContainsKey(MsfDictKeys.MapName)
                ? data.Properties[MsfDictKeys.MapName] : defaultMapName;
        }
        if (textPlayerCount != null)
        {
            if (data.MaxPlayers > 0)
            {
                textPlayerCount.text = data.OnlinePlayers + "/" + data.MaxPlayers;
            }
            else
            {
                textPlayerCount.text = data.OnlinePlayers.ToString();
            }
        }
        var rate = (float)data.OnlinePlayers / (float)data.MaxPlayers;

        if (rate >= 1)
        {
            SetPlayerMeasure(playerMeasureMax);
        }
        else if (rate >= 0.6f)
        {
            SetPlayerMeasure(playerMeasureHigh);
        }
        else if (rate >= 0.4f)
        {
            SetPlayerMeasure(playerMeasureMedium);
        }
        else
        {
            SetPlayerMeasure(playerMeasureLow);
        }
    }
Example #9
0
        /// <summary>
        /// Starts given match
        /// </summary>
        /// <param name="gameInfo"></param>
        public virtual void StartMatch(GameInfoPacket gameInfo)
        {
            // Save room Id in buffer, may be very helpful
            Mst.Options.Set(MstDictKeys.ROOM_ID, gameInfo.Id);
            // Save max players to buffer, may be very helpful
            Mst.Options.Set(MstDictKeys.ROOM_MAX_PLAYERS, gameInfo.MaxPlayers);

            if (gameInfo.IsPasswordProtected)
            {
                Mst.Events.Invoke(MstEventKeys.showPasswordDialogBox,
                                  new PasswordInputDialoxBoxEventMessage("Room is required the password. Please enter room password below",
                                                                         () =>
                {
                    StartLoadingGameScene();
                }));
            }
            else
            {
                StartLoadingGameScene();
            }
        }
Example #10
0
        /// <summary>
        /// Initializes serverobject with IP
        /// </summary>
        /// <param name="useLocalhost">Whether the server should use 127.0.0.1 ip or use its actual outgoing one</param>
        public Server(bool useLocalhost = false)
        {
            WorldManager.OnServer = true;

            isDisposed     = false;
            isDoingCleanup = false;

            IPAddress ip;

            if (useLocalhost)
            {
                ip = IPAddress.Parse("127.0.0.1");
            }
            else
            {
                ip = GetIP();
            }
            IPEndPoint iep = new IPEndPoint(ip, PORT);

            listener = new CustomUdpClient(PORT);
            listener.PacketRecieved += PacketReceived;

            pending   = new Connection[PENDING_SLOTS];
            connected = new Connection[CONNECTED_SLOTS];
            games     = new Game[GAME_SLOTS];

            packetCallbacks = new Dictionary <Type, Action <Packet> >()
            {
                {
                    typeof(StringPacket), (Packet p) =>
                    {
                        StringPacket sp = (StringPacket)p;
                        Console.WriteLine(sp.Content);
                    }
                },
                { typeof(ConnectPacket), (Packet p) =>
                  {
                      int             connectionIndex = GetConnectionIndexFromIEP(pending, p.Sender);
                      ChallengePacket challenge;
                      ConnectPacket   cp = (ConnectPacket)p;
                      if (connectionIndex == -1)
                      {
                          int i = GetFirstFreeIndex(pending);
                          if (i == -1)
                          {
                              listener.Send(new DeclineConnectPacket(), p.Sender);
                              return;
                          }

                          challenge  = new ChallengePacket(cp.ClientSalt);
                          pending[i] = new Connection(cp.Sender, cp.ClientSalt, challenge.ServerSalt);
                          pending[i].RefreshRecievedPacketTimestamp();
                      }
                      else
                      {
                          Connection c = pending[connectionIndex];
                          c.ClientSalt = cp.ClientSalt;
                          challenge    = new ChallengePacket(c.ClientSalt, c.ServerSalt);
                          c.RefreshRecievedPacketTimestamp();
                      }
                      listener.Send(challenge, p.Sender);
                  } },
                {
                    typeof(ChallengeResponsePacket), (Packet p) =>
                    {
                        int connectionIndex = GetConnectionIndexFromIEP(pending, p.Sender);
                        if (connectionIndex == -1)
                        {
                            return;
                        }
                        Connection c = pending[connectionIndex];
                        ChallengeResponsePacket crp = (ChallengeResponsePacket)p;
                        if (crp.Xored == c.Xored) // response packet was correct
                        {
                            pending[connectionIndex] = null;
                            connectionIndex          = GetFirstFreeIndex(connected);
                            if (connectionIndex == -1)
                            {
                                listener.Send(new DeclineConnectPacket(), p.Sender);
                                return;
                            }
                            connected[connectionIndex] = c;
                            c.RefreshRecievedPacketTimestamp();
                            KeepClientAlivePacket kcap = new KeepClientAlivePacket();
                            listener.Send(kcap, p.Sender);
                            return;
                        }
                        listener.Send(new DeclineConnectPacket(), p.Sender);
                    }
                }
            };

            connectedPacketCallbacks = new Dictionary <Type, Action <SaltedPacket, Connection> >()
            {
                {
                    typeof(KeepAlivePacket), (SaltedPacket p, Connection c) =>
                    {
                        c.RefreshRecievedPacketTimestamp();
                    }
                },
                {
                    typeof(QueuePacket), (SaltedPacket p, Connection c) =>
                    {
                        int gameIndex = GetGameIndexFromIep(p.Sender);
                        int gameId    = -1;
                        if (gameIndex != -1)
                        {
                            gameId = games[gameIndex].Id;
                        }
                        else
                        {
                            lock (games)
                            {
                                foreach (Game g in games)
                                {
                                    if (g != null && g.AddConnection(c))
                                    {
                                        gameId = g.Id;
                                        break;
                                    }
                                }


                                if (gameId == -1)
                                {
                                    int newGameIndex = GetFirstFreeIndex(games);
                                    if (newGameIndex != -1)
                                    {
                                        Game g = new Game();
                                        games[newGameIndex] = g;
                                        g.AddConnection(c);
                                        gameId = g.Id;
                                        g.StartHandle(SendPacket);
                                        g.GameEnded += (object sender, EventArgs e) =>
                                        {
                                            lock (games)
                                                games[newGameIndex] = null;
                                        };
                                    }
                                }
                            }
                        }

                        QueueResponsePacket qrp = new QueueResponsePacket(gameId);
                        listener.Send(qrp, p.Sender);
                        c.RefreshSentPacketTimestamp();
                    }
                },
                {
                    typeof(GetGameInfoPacket), (SaltedPacket p, Connection c) =>
                    {
                        int gameIndex = GetGameIndexFromIep(c.Client);
                        if (gameIndex == -1)
                        {
                            return;
                        }

                        Game           g    = games[gameIndex];
                        GameInfoPacket ggip = new GameInfoPacket(g);
                        listener.Send(ggip, p.Sender);
                        c.RefreshSentPacketTimestamp();
                    }
                },
                {
                    typeof(InputPacket), (SaltedPacket p, Connection c) =>
                    {
                        int gameIndex = GetGameIndexFromIep(c.Client);
                        if (gameIndex == -1)
                        {
                            SendPacket(new QueueResponsePacket(-1), c.Client);
                            return;
                        }

                        Game        g    = games[gameIndex];
                        InputPacket inpt = (InputPacket)p;
                        g.HandleInputPacket(inpt, c);
                    }
                }
            };
        }
Example #11
0
    private IEnumerator JoinGame()
    {
        // Checks to see if client is connected to master server
        if (!Msf.Connection.IsConnected)
        {
            Debug.Log("You must be connected to master server");
            status = "ERROR: No connection to master server, please try again";
            yield break;
        }

        // Login as guest
        var  promise         = Msf.Events.FireWithPromise(Msf.EventNames.ShowLoading, "Logging in");
        bool loggedInAsGuest = false;

        status = "Logging in as guest";
        Msf.Client.Auth.LogInAsGuest((accInfo, error) =>
        {
            promise.Finish();

            loggedInAsGuest = true;

            if (accInfo == null)
            {
                Msf.Events.Fire(Msf.EventNames.ShowDialogBox, DialogBoxData.CreateError(error));
                Logs.Error(error);
                status = "ERROR: Unable to login as guest, please try again";
                return;
            }
        });

        while (loggedInAsGuest == false)
        {
            yield return(null);
        }

        // Gets list of active games from master server
        Debug.Log("Retrieving gamelist");
        List <GameInfoPacket> gamesList = null;
        bool gotGamesList = false;

        status = "Retrieving game list";
        Msf.Client.Matchmaker.FindGames(games =>
        {
            gotGamesList = true;
            gamesList    = games;
        });

        while (gotGamesList == false)
        {
            yield return(null);
        }

        Debug.Log("Game list retrieved");
        status = "Game list retrieved";
        // Tries to find an avaliable game.
        // If none are found, make a new game.
        if (gamesList.Count == 0)
        {
            Debug.Log("Game not found, creating a game");
            status = "No avaliable games found, creating a game";
            CreateGame();
        }
        else
        {
            // Trys to find an open game
            Debug.Log("There seems to be avaliable games, hold on a sec");
            status = "Possible avaliable game, please hold";
            GameInfoPacket gameToJoin = null;
            foreach (GameInfoPacket i in gamesList)
            {
                if (i.OnlinePlayers < i.MaxPlayers)
                {
                    gameToJoin = i;
                    break;
                }
            }

            // If there is a game to join, connect to the game
            // Else, create a new game
            if (gameToJoin != null)
            {
                status = "Game found! Joining!";
                Msf.Client.Rooms.GetAccess(gameToJoin.Id, OnPassReceived);
            }
            else
            {
                Debug.Log("Game not found, creating a game");
                status = "No avaliable games found, creating a game";
                CreateGame();
            }
        }
    }