Example #1
0
    private async void MatchJoin(IMatchmakerMatched matched)
    {
        var remote = matched.Users.FirstOrDefault(_1 => !_1.Presence.UserId.Equals(Composition.DataAccount.IdUser));

        Remote.Seed      = (float)remote.NumericProperties[KEY_SEED];
        Remote.NameUser  = remote.Presence.Username;
        Remote.BallColor = new Color(
            (float)remote.NumericProperties[KEY_BALL_COLOR_R],
            (float)remote.NumericProperties[KEY_BALL_COLOR_G],
            (float)remote.NumericProperties[KEY_BALL_COLOR_B]);
        Remote.BallRadius = (float)remote.NumericProperties[KEY_BALL_RADIUS];
        Remote.BallSpeedX = (float)remote.NumericProperties[KEY_BALL_SPEED_X];
        Remote.BallSpeedY = (float)remote.NumericProperties[KEY_BALL_SPEED_Y];

        if (Local.Seed == Remote.Seed)
        {
            throw new Exception("seeds are equals");
        }

        Debug.Log($">> match found for: {string.Join(", ", matched.Users.Select(_ => _.Presence.Username))}");

        _netMatch = await _netSocket.JoinMatchAsync(matched);

        lock (_users)
        {
            _users.AddRange(_netMatch.Presences);
        }

        Debug.Log($">> match state (joining): {string.Join(", ", _netMatch.Presences.Select(_ => _.Username))}");
    }
Example #2
0
    /**
     * private async void Awake()
     * {
     *  Debug.Log("NakamaTest: Awake");
     *  var authtoken = ""; // PlayerPrefs.GetString(PrefKeyName);
     *  Debug.Log("PlayerPrefsGetString: " + authtoken);
     *  if (!string.IsNullOrEmpty(authtoken))
     *  {
     *      //Debug.Log("Auth token was not null or open!");
     *      var session = Session.Restore(authtoken);
     *      //Debug.Log(new DateTime(session.ExpireTime));
     *      if (!session.IsExpired)
     *      {
     *          _session = session;
     *          Debug.Log(_session);
     *          Debug.Log("Hit this weird place.");
     *          return;
     *      }
     *  }
     *  //var deviceid = SystemInfo.deviceUniqueIdentifier;
     *  var email = "*****@*****.**";
     *  var password = "******";
     *  var username = "******";
     *  _session = await _client.AuthenticateEmailAsync(email, password, username, false);
     *  //PlayerPrefs.SetString(PrefKeyName, _session.AuthToken);
     *  _socket = _client.CreateWebSocket();
     *  _socket.OnConnect += (sender, args) =>
     *  {
     *      Debug.Log("Socket connected.");
     *  };
     *  _socket.OnDisconnect += (sender, args) =>
     *  {
     *      Debug.Log("Socket disconnected.");
     *  };
     *  await _socket.ConnectAsync(_session);
     *  Debug.Log(_session);
     *  Debug.Log(new DateTime(_session.ExpireTime));
     * }
     **/

    public async void AttemptMatchmake()
    {
        Debug.Log("Begin Attempted Matchmaking!");
        var query    = "*";
        var minCount = 2;
        var maxCount = 2;


        var matchmakerTicket = await _socket.AddMatchmakerAsync(
            query, minCount, maxCount);

        _socket.OnMatchmakerMatched += async(_, matched) =>
        {
            Debug.LogFormat("Received MatchmakerMatched message: {0}", matched);
            var opponents = string.Join(",", matched.Users); // printable list.
            Debug.LogFormat("Matched opponents: {0}", opponents);

            myMatch = await _socket.JoinMatchAsync(matched);

            if (myMatch != null)
            {
                Debug.Log("Match ID: " + myMatch.Id);
            }
            else
            {
                Debug.Log("NO MATCH!");
            }
            CreateMessageListener();
        };
    }
Example #3
0
        private async Task JoinMatch()
        {
            _match = await _socket.JoinMatchAsync(_matchId);

            Assert.NotNull(_match);
            Assert.NotNull(_match.Id);
        }
Example #4
0
        private async void Start()
        {
            var deviceId = SystemInfo.deviceUniqueIdentifier;
            var session  = await _client.AuthenticateDeviceAsync(deviceId);

            Debug.Log(session);

            _socket                = _client.NewSocket();
            _socket.Connected     += () => Debug.Log("Socket connected.");
            _socket.Closed        += () => Debug.Log("Socket closed.");
            _socket.ReceivedError += Debug.LogError;

            IUserPresence self = null;
            var           connectedOpponents = new List <IUserPresence>(2);

            _socket.ReceivedMatchmakerMatched += async matched =>
            {
                Debug.LogFormat("Matched result: {0}", matched);
                var match = await _socket.JoinMatchAsync(matched);

                self = match.Self;
                Debug.LogFormat("Self: {0}", self);
                connectedOpponents.AddRange(match.Presences);
            };
            _socket.ReceivedMatchPresence += presenceEvent =>
            {
                foreach (var presence in presenceEvent.Leaves)
                {
                    connectedOpponents.Remove(presence);
                }
                connectedOpponents.AddRange(presenceEvent.Joins);
                // Remove yourself from connected opponents.
                connectedOpponents.Remove(self);
                Debug.LogFormat("Connected opponents: [{0}]", string.Join(",\n  ", connectedOpponents));
            };
            await _socket.ConnectAsync(session);

            Debug.Log("After socket connected.");
            await _socket.AddMatchmakerAsync("*", 2, 2);


            // NOTE As an example create a second user and socket to matchmake against.
            var deviceId2 = Guid.NewGuid().ToString();
            var session2  = await _client.AuthenticateDeviceAsync(deviceId2);

            var socket2 = _client.NewSocket();

            socket2.ReceivedMatchmakerMatched += async matched => await socket2.JoinMatchAsync(matched);

            await socket2.ConnectAsync(session2);

            await socket2.AddMatchmakerAsync("*", 2, 2);

            await Task.Delay(TimeSpan.FromSeconds(10)); // disconnect after 10 seconds.

            Debug.Log("After delay socket2 closed.");
            await socket2.CloseAsync();
        }
Example #5
0
    async void Start()
    {
        var deviceid = SystemInfo.deviceUniqueIdentifier;
        // NOTE should cache a user session.
        var session = await _client.AuthenticateDeviceAsync(deviceid);

        Debug.LogFormat("Session '{0}'", session);

        _socket = _client.CreateWebSocket();

        IUserPresence self = null;
        var           connectedOpponents = new List <IUserPresence>(0);

        _socket.OnMatchmakerMatched += async(sender, matched) =>
        {
            Debug.LogFormat("Matched '{0}'", matched);
            var match = await _socket.JoinMatchAsync(matched);

            self = match.Self;
            Debug.LogFormat("Self '{0}'", self);
            connectedOpponents.AddRange(match.Presences);

            // NOTE shows how to send match state messages.
            var newState = new Dictionary <string, string> {
                { "hello", "world" }
            }.ToJson();
            _socket.SendMatchState(match.Id, 0, newState); // Send to all connected users.
        };
        _socket.OnMatchPresence += (sender, presenceChange) =>
        {
            connectedOpponents.AddRange(presenceChange.Joins);
            foreach (var leave in presenceChange.Leaves)
            {
                connectedOpponents.RemoveAll(item => item.SessionId.Equals(leave.SessionId));
            }
            ;
            // Remove yourself from connected opponents.
            connectedOpponents.RemoveAll(item => {
                return(self != null && item.SessionId.Equals(self.SessionId));
            });
        };
        _socket.OnMatchState += (sender, message) =>
        {
            var enc = System.Text.Encoding.UTF8;
            Debug.LogFormat("Match state '{0}'", enc.GetString(message.State));
        };
        _socket.OnConnect    += (sender, evt) => Debug.Log("Socket connected.");
        _socket.OnDisconnect += (sender, evt) => Debug.Log("Socket disconnected.");

        await _socket.ConnectAsync(session);

        int minCount         = 2;
        int maxCount         = 8;
        var matchmakerTicket = await _socket.AddMatchmakerAsync("*", minCount, maxCount);

        Debug.LogFormat("Matchmaker ticket '{0}'", matchmakerTicket);
    }
Example #6
0
    public async void JoinRoom()
    {
        matchId = matchIdField.text;
        match   = await socket.JoinMatchAsync(matchId);

        foreach (var presence in match.Presences)
        {
            Debug.LogFormat("User id '{0}' name '{1}'.", presence.UserId, presence.Username);
        }
    }
Example #7
0
    private async void OnUiJoinMatch(object eventArgs)
    {
        this.OnDebugMessage("Joining match...");
        string matchId = eventArgs.ToString();

        _match = await _socket.JoinMatchAsync(matchId);

        foreach (var p in _match.Presences)
        {
            AddActivePlayer(p);
        }
        List_Players(_presences);
        CheckPlayerLimitReached();
    }
    // +++ event handler ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    async void OnMatchmakerMatched(object sender, IMatchmakerMatched e)
    {
        Debug.Log("Match found");

        _match = await _socket.JoinMatchAsync(e);

        Debug.Log("match joined");

        // persisting own presence
        _self    = _match.Self;
        _matchId = _match.Id;

        _connectedUsers.AddRange(_match.Presences);
    }
        private void SubscribeSocketsEvents()
        {
            connectedOpponents = new List <IUserPresence>();

            _socket.ReceivedMatchmakerMatched += async matched =>
            {
                Debug.LogFormat("Matched result: {0}", matched);
                _currMatch = await _socket.JoinMatchAsync(matched);

                _self = _currMatch.Self;
                Debug.LogFormat("Self: {0}", _self);
                connectedOpponents.AddRange(_currMatch.Presences);

                OnMatchJoins(_currMatch.Presences);
            };
            //
            _socket.ReceivedMatchPresence += presenceEvent =>
            {
                OnMatchLeaves(presenceEvent.Leaves);

                connectedOpponents.Remove(_self);

                OnMatchJoins(presenceEvent.Joins);

                UnityMainThread.wkr.AddJob(() => _player.SetName(_self.Username));
                connectedOpponents.AddRange(presenceEvent.Joins);
            };
            //
            var enc = System.Text.Encoding.UTF8;

            _socket.ReceivedMatchState += newState =>
            {
                var content = enc.GetString(newState.State);
                var code    = newState.OpCode.ToDataCode();
                switch (newState.OpCode.ToDataCode())
                {
                case DataCode.POSITION:
                    Debug.Log("A custom opcode -- > NEW POSITION.");
                    break;

                default:
                    Debug.LogFormat("User '{0}'' sent '{1}'", newState.UserPresence.Username, content);
                    break;
                }

                UnityMainThread.wkr.AddJob(() => { OnNewDataState(newState.UserPresence.UserId, code, content); });
                BoxTextController.WriteText("Receive data--> " + content, Color.yellow);
            };
        }
Example #10
0
    public async Task <bool> JoinMatch()
    {
        try
        {
            _match = await _socket.JoinMatchAsync(_matchmakerMatched);

            _context.isAllPlayerJoined = true;
        }
        catch (Exception)
        {
            return(false);
        }

        return(true);
    }
Example #11
0
    public async Task JoinMatchAsync()
    {
        Debug.Log("awaiting match");
        // await joining match
        _match = await _socket.JoinMatchAsync(_matchMakerMatch);

        Debug.Log("match joined");

        // persisting own presence
        self     = _match.Self;
        _matchId = _match.Id;

        Debug.LogFormat("MatchId: {0}", _matchId);

        _connectedUsers.AddRange(_match.Presences);
    }
Example #12
0
    public async void JoinMatchIdAsync(string matchId)
    {
        if (matchSocket == null)
        {
            matchSocket = client.NewSocket();
            await matchSocket.ConnectAsync(session);
        }
        activeSceneMatchId = matchId;
        match = await matchSocket.JoinMatchAsync(matchId);

        EventManager.onRoomJoin.Invoke();

        //foreach (var presence in match.Presences)
        //{
        //    Debug.LogFormat("User id '{0}' name '{1}'.", presence.UserId, presence.Username);
        //}
    }
    // Start is called before the first frame update
    async void Start()
    {
        deviceId = SystemInfo.deviceUniqueIdentifier;
        Dictionary <string, string> authParams = new Dictionary <string, string>();

        authParams.Add("skillz_match_token", "1234567890");

        var session = await client.AuthenticateCustomAsync(deviceId, "test-client-2", false, authParams);

        //var session = await client.AuthenticateDeviceAsync(deviceId, "test-client-2", false);

        Debug.Log("Device authenticated with token:");
        Debug.Log(session.AuthToken); // raw JWT token
        Debug.LogFormat("Session user id: '{0}'", session.UserId);
        Debug.LogFormat("Session user username: '******'", session.Username);
        Debug.LogFormat("Session has expired: {0}", session.IsExpired);
        Debug.LogFormat("Session expires at: {0}", session.ExpireTime); // in seconds.

        socket = client.NewSocket();

        socket.Connected          += () => Debug.Log("Socket Connected");
        socket.Closed             += () => Debug.Log("Socket Closed");
        socket.ReceivedMatchState += ReceiveMatchStateMessage;

        await socket.ConnectAsync(session);



        //var match = await socket.CreateMatchAsync();
        //Debug.LogFormat("New match with id '{0}'.", match.Id);
        //var matchId = "01234567890123456789.nakama";

        var resp = await socket.RpcAsync("create_skillz_match", "{\"match_id\": \"01234567890123456789.nakama\"}");

        GameMsg gMsg = JsonUtility.FromJson <GameMsg>(resp.Payload);

        Debug.LogFormat("New Match ID: {0}", gMsg.match_id);

        serverMatchId = gMsg.match_id;
        var match = await socket.JoinMatchAsync(serverMatchId);
    }
    public async Task <bool> joinMatch(string matchId)
    {
        if (_socket == null)
        {
            await createSocket();
        }

        if (_socket != null)
        {
            if (_socket.IsConnected)
            {
                _match = await _socket.JoinMatchAsync(matchId);

                return(true);
            }
            else
            {
                await _socket.ConnectAsync(_session);

                joinMatch(matchId);
            }
        }
        return(false);
    }