Пример #1
0
        TransactionResult playGameTransaction(MutableData mutableData)
        {
            Dictionary <string, object> leaders = mutableData.Value as Dictionary <string, object>;
            string _color = settingplayer.Instances.Color;

            //inicializo un tablero de juegos, si no existe;
            if (leaders == null)
            {
                UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("no se ha creado la sala de juego " + tableroNAme));
                return(TransactionResult.Abort());
            }
            Debug.Log(leaders[_color].ToString());
            if (leaders[_color].ToString() == UIHandler.instance.usuario.CurrentUser.UserId)//accedo a el valor de color de este usuario y verifico si este color no esta ocupado en el tablero de juego
            {
                mutableData.Value = leaders;
                return(TransactionResult.Success(mutableData));
            }
            else if (leaders[Otrocolor(_color)].ToString() == UIHandler.instance.usuario.CurrentUser.UserId)
            {
                UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("no ha actualizado el color de jugador a " + _color));
                return(TransactionResult.Abort());
            }
            else
            {
                UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("sala de juego: " + tableroNAme + " llena"));
                return(TransactionResult.Abort());
            }
            // You must set the Value to indicate data at that location has changed.
        }
Пример #2
0
    public void OnClickMaxScores()
    {
        const int MaxScoreRecordCount = 10;

        DatabaseReference mDatabaseRef = FirebaseDatabase.DefaultInstance.RootReference;

        mDatabaseRef.Child("top10").RunTransaction(mutableData =>
        {
            List <object> leaders = mutableData.Value as List <object>;


            if (leaders == null)
            {
                leaders = new List <object>();
            }
            else if (mutableData.ChildrenCount >= MaxScoreRecordCount)
            {
                long minScore = long.MaxValue;
                object minVal = null;
                foreach (var child in leaders)
                {
                    if (!(child is Dictionary <string, object>))
                    {
                        continue;
                    }
                    long childScore = (long)((Dictionary <string, object>)child)["score"];
                    if (childScore < minScore)
                    {
                        minScore = childScore;
                        minVal   = child;
                    }
                }
                if (minScore > score)
                {
                    // The new score is lower than the existing 5 scores, abort.
                    return(TransactionResult.Abort());
                }


                // Remove the lowest score.
                leaders.Remove(minVal);
            }


            Dictionary <string, object> entryValues = new Dictionary <string, object>();
            entryValues.Add("score", score);
            entryValues.Add("name", userName);
            entryValues.Add("email", userEmail);

            leaders.Add(entryValues);

            mutableData.Value = leaders;
            return(TransactionResult.Success(mutableData));
        }).ContinueWith(
            task =>
        {
            Debug.Log(string.Format("OnClickMaxScores::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
        }
            );
    }
Пример #3
0
    // A realtime database transaction receives MutableData which can be modified
    // and returns a TransactionResult which is either TransactionResult.Success(data) with
    // modified data or TransactionResult.Abort() which stops the transaction with no changes.
    TransactionResult AddScoreTransaction(MutableData mutableData)
    {
        List <object> leaders = mutableData.Value as List <object>;

        if (leaders == null)
        {
            leaders = new List <object>();
        }
        // If the current list of scores is greater or equal to our maximum allowed number,
        // we see if the new score should be added and remove the lowest existing score.
        long   childScore = long.MaxValue;
        object overlap    = null;

        foreach (var child in leaders)
        {
            if (!(child is Dictionary <string, object>))
            {
                continue;
            }
            //loop to see if the leaderboard contains the same Email
            //If a matching Email was found, then set the overlap variable to the found record
            Dictionary <string, object> dict = (Dictionary <string, object>)child;
            childScore = (long)((Dictionary <string, object>)child)["score"];

            //If the database has this user's email already
            if (dict.ContainsValue(email))
            {
                //If the score in the database is greater than the new score, then abort
                if (childScore >= score)
                {
                    // If the new score is less than the highscore, we abort
                    return(TransactionResult.Abort());
                }
                else
                {
                    // Otherwise, we remove the current lowest to be replaced with the new score.
                    overlap = child;
                    leaders.Remove(overlap);
                    break;
                }
            }
        }


        // Now we add the new score as a new entry that contains the name, score and address.
        Dictionary <string, object> newScoreMap = new Dictionary <string, object>();

        newScoreMap["score"] = score;
        newScoreMap["name"]  = firstName;
        newScoreMap["email"] = email;
        leaders.Add(newScoreMap);

        // You must set the Value to indicate data at that location has changed.
        mutableData.Value = leaders;
        LeaderboardList   = leaders;
        return(TransactionResult.Success(mutableData));
    }
    // A realtime database transaction receives MutableData which can be modified
    // and returns a TransactionResult which is either TransactionResult.Success(data) with
    // modified data or TransactionResult.Abort() which stops the transaction with no changes.
    TransactionResult AddScoreTransaction(MutableData mutableData)
    {
        List <object> leaders = mutableData.Value as List <object>;

        if (leaders == null)
        {
            leaders = new List <object>();
        }

        else if (mutableData.ChildrenCount < MaxScores)
        {
            foreach (var child in leaders)
            {
                scoreRet = (string)((Dictionary <string, object>)child)["score"];
                Debug.Log(scoreRet);
            }
        }
        else if (mutableData.ChildrenCount >= MaxScores)
        {
            // If the current list of scores is greater or equal to our maximum allowed number,
            // we see if the new score should be added and remove the lowest existing score.
            long   minScore = long.MaxValue;
            object minVal   = null;
            foreach (var child in leaders)
            {
                if (!(child is Dictionary <string, object>))
                {
                    continue;
                }
                long childScore = (long)((Dictionary <string, object>)child)["score"];
                if (childScore < minScore)
                {
                    minScore = childScore;
                    minVal   = child;
                }
            }
            // If the new score is lower than the current minimum, we abort.
            if (minScore > score)
            {
                return(TransactionResult.Abort());
            }
            // Otherwise, we remove the current lowest to be replaced with the new score.
            leaders.Remove(minVal);
        }

        // Now we add the new score as a new entry that contains the email address and score.
        Dictionary <string, object> newScoreMap = new Dictionary <string, object>();

        newScoreMap["score"] = score;
        newScoreMap["email"] = email;
        leaders.Add(newScoreMap);

        // You must set the Value to indicate data at that location has changed.
        mutableData.Value = leaders;
        return(TransactionResult.Success(mutableData));
    }
Пример #5
0
    private void UpdateRankingRecord(GameMode type, long inputScore, string inputEmail)
    {
        string gameType;

        switch (type)
        {
        default:
            gameType = "easy";
            break;

        case GameMode.Hard:
            gameType = "hard";
            break;
        }
        _leaderboardRef.Child(gameType).RunTransaction(nodeData =>
        {
            List <object> recordList = nodeData.Value as List <object>;
            if (recordList == null)
            {
                recordList = new List <object>();
            }
            else if (nodeData.ChildrenCount >= MaxScoreDisplayCount)     //기록이 꽉차면
            {
                long minScore   = long.MaxValue;
                object minValue = null;
                foreach (var record in recordList.Where(x => x is Dictionary <string, object>))
                {
                    long score = (long)(record as Dictionary <string, object>)["score"];
                    if (score < minScore)
                    {
                        minScore = score;
                        minValue = record;
                    }
                }
                if (inputScore < minScore)
                {
                    return(TransactionResult.Abort()); //순위 안에 최소값 보다 못하면 중단
                }
                recordList.Remove(minValue);           //기존 최소값 정보 제거
            }
            Dictionary <string, object> newScoreMap = new Dictionary <string, object>();
            newScoreMap["email"] = inputEmail; //식별자
            newScoreMap["score"] = inputScore; //점수
            recordList.Add(newScoreMap);       // 새로운 점수 기록
            nodeData.Value = recordList;
            return(TransactionResult.Success(nodeData));
        });
    }
Пример #6
0
    public void InsertDataRoom()    //MACHTMAKING
    {
        Message.Instance.NewMessage("Buscando oponente");

        Dictionary <string, object> info = new Dictionary <string, object>();

        ReferenceRoom().RunTransaction(data =>
        {
            info = data.Value as Dictionary <string, object>;

            if ((string)info["owner"] == GameManager.Instance.GetUserID())
            {
                return(TransactionResult.Abort());
            }

            if ((string)info["owner"] == "")
            {
                info["owner"]  = GameManager.Instance.GetUserID().ToString();
                buscando_match = false;
            }
            else if ((string)info["guest"] == "")
            {
                info["guest"]  = GameManager.Instance.GetUserID().ToString();
                buscando_match = false;
            }
            else
            {
                return(TransactionResult.Abort());
            }

            data.Value = info;

            return(TransactionResult.Success(data));
        }).ContinueWith(task => {
            if (task.Exception.Message != string.Empty && (string)info["owner"] != GameManager.Instance.GetUserID())
            {
                print("Hay alguien en guest atascado");
                ExtraFunction((string)info["guest"]);
            }
            else
            {
                print("Todo va bien");
            }
        });
    }
Пример #7
0
 TransactionResult UpdateScore(MutableData nd)
 {
     if (nd.Value != null)
     {
         Dictionary <string, object> updatedScore = nd.Value as Dictionary <string, object>;
         topScore = (long)updatedScore["topScore"];
     }
     if (currScore > topScore)
     {
         topScore = currScore;
         nd.Value = new Dictionary <string, object>()
         {
             { "topScore", currScore }
         };
         return(TransactionResult.Success(nd));
     }
     return(TransactionResult.Abort());
 }
    TransactionResult AddScoreTransaction(MutableData mutableData)
    {
        List <object> leaders = mutableData.Value as List <object>;

        if (leaders == null)
        {
            leaders = new List <object>();
        }
        else if (mutableData.ChildrenCount >= MaxScores)
        {
            long   maxTime = 0;
            object maxVal  = null;
            foreach (var child in leaders)
            {
                if (!(child is Dictionary <string, object>))
                {
                    continue;
                }
                long childTime = (long)((Dictionary <string, object>)child)["time"];
                if (childTime > maxTime)
                {
                    maxTime = childTime;
                    maxVal  = child;
                }
            }
            // Not fast enough
            if (maxTime < finishTime)
            {
                return(TransactionResult.Abort());
            }
            // Kick lowest score
            leaders.Remove(maxVal);
        }

        // Insert new player record time
        Dictionary <string, object> newScoreMap = new Dictionary <string, object>();

        newScoreMap["time"]       = finishTime;
        newScoreMap["playerName"] = playerName;
        leaders.Add(newScoreMap);

        mutableData.Value = leaders;
        return(TransactionResult.Success(mutableData));
    }
Пример #9
0
    TransactionResult AddTransaction(MutableData mutableData)
    {
        int  theValue    = -1;
        bool parseResult = int.TryParse(mutableData.Value.ToString(), out theValue);

        Debug.Log("------ Mutable Data : " + theValue);

        if (parseResult)
        {
            mutableData.Value = theValue + 1;
            Debug.Log("The Value : " + mutableData.Value);
            return(TransactionResult.Success(mutableData));
        }
        else
        {
            Debug.Log("Failed : " + mutableData.Value.ToString());
            return(TransactionResult.Abort());
        }
    }
Пример #10
0
    private TransactionResult UpdateTopScore(MutableData md)
    {
        if (md.Value != null)
        {
            Dictionary <string, object> updatedScore = md.Value as Dictionary <string, object>;
            topScore = (long)updatedScore ["topScore"];
        }

        // Compare the cur score to the top score.
        if (curScore > topScore)           // Update topScore, triggers other UpdateTopScores to retry
        {
            topScore = curScore;
            md.Value = new Dictionary <string, object>()
            {
                { "topScore", curScore }
            };
            return(TransactionResult.Success(md));
        }
        return(TransactionResult.Abort());         // Aborts the transaction
    }
Пример #11
0
    private IEnumerator SalaOcupada(string last_guest_user)
    {
        print("Tocaría esperar");
        yield return(new WaitForSeconds(1f)); //Esperar a que los usuarios hagan match.

        buscando_match = true;
        ReferenceRoom().RunTransaction(data => {
            Dictionary <string, object> info = data.Value as Dictionary <string, object>;

            if ((string)info["guest"] == last_guest_user)           //Si sigue la misma persona, se ha quedado bugeada. Limpiarla.
            {
                info["guest"] = "";
                data.Value    = info;
                return(TransactionResult.Success(data));
            }
            else
            {
                return(TransactionResult.Abort());
            }
        });
    }
Пример #12
0
        TransactionResult moveTransaction(MutableData mutableData)
        {
            Dictionary <string, object> leaders = mutableData.Value as Dictionary <string, object>;

            //inicializo un tablero de juegos, si no existe;
            if (leaders == null)
            {
                Debug.Log("no existe " + settingplayer.Instances.TableroName);
                return(TransactionResult.Abort());
            }
            if (leaders[settingplayer.Instances.Color].ToString() == UIHandler.instance.usuario.CurrentUser.UserId)
            {
                leaders["posxOld"] = posxOld;
                leaders["posyOld"] = posyOld;
                leaders["posxNew"] = posxNew;
                leaders["posyNew"] = posyNew;
            }


            mutableData.Value = leaders;
            return(TransactionResult.Success(mutableData));
            // You must set the Value to indicate data at that location has changed.
        }
Пример #13
0
        TransactionResult AddTableroTransaction(MutableData mutableData)
        {
            Dictionary <string, object> leaders = mutableData.Value as Dictionary <string, object>;
            string _color = color;
            string _playerName;

            //inicializo un tablero de juegos, si no existe;
            if (leaders == null)
            {
                leaders            = new Dictionary <string, object>();
                leaders["blanco"]  = "";
                leaders["negro"]   = "";
                leaders["posxOld"] = 0;
                leaders["posyOld"] = 0;
                leaders["posxNew"] = 0;
                leaders["posyNew"] = 0;
            }

            /*DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("bartolo");
             * IDebugLog("Running Transaction...");
             * // Use a transaction to ensure that we do not encounter issues with
             * // simultaneous updates that otherwise might create more than MaxScores top scores.
             * reference.RunTransaction(ReadPlayerNameTransaction)
             * .ContinueWith(task =>
             * {
             *  if (task.Exception != null)
             *  {
             *      Debug.Log(/*task.Exception.ToString()+///"El error se presento cuando voy a leer los datos del jugador");
             *      _color = "";
             *  }
             *  else if (task.IsCompleted) //accedo a leer los datos del jugador en la nube
             *  {
             *      Debug.Log("Transaction complete. " + "leer datos del jugador");
             *      _color = task.Result.Child("color").Value.ToString();//leo el color que tiene asignado este usuario en la nube
             *      Debug.Log("color: " + _color + " " + string.IsNullOrEmpty(_color).ToString());
             *  }
             * });
             * reference.GetValueAsync().ContinueWith(task => {
             *  if (task.IsFaulted)
             *  {
             *      // Handle the error...
             *  }
             *  else if (task.IsCompleted)
             *  {
             *      _color = task.Result.Child("color").Value.ToString();
             *      // Do something with snapshot...
             *  }
             * });*/
            Debug.Log("busqueda: " + leaders[color] + "blanco" + _color);
            if (string.IsNullOrEmpty(leaders[_color].ToString()))     //accedo a el valor de color de este usuario y verifico si este color no esta ocupado en el tablero de juego
            {
                if ((string)leaders[Otrocolor(_color)] != playerName) //rectifico que la sala, el otro color no esta ocupado por este jugador
                {
                    leaders[_color] = UIHandler.instance.usuario.CurrentUser.UserId;
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("Configurado Sala de Juego"));
                    Debug.Log(_color + " : " + leaders[_color]);
                }
                else
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("El usuario ya tiene asignado el color " + Otrocolor(_color) + " en la sala de juego " + tableroNAme + " así que se procede a cambiar de color"));
                    leaders[Otrocolor(_color)] = "";
                    leaders[_color]            = playerName;
                    //return TransactionResult.Abort();
                }
            }
            else
            {
                if (leaders[_color].ToString() == playerName)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("Ud ya eligio el color: " + _color + " en esta sala de juego"));
                }
                else if ((string)leaders[Otrocolor(_color)] == playerName)
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("Ud ya eligio el color: " + Otrocolor(_color)));
                }
                else if (string.IsNullOrEmpty((string)leaders[Otrocolor(_color)]))
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("Esta sala solo tiene libre el color " + Otrocolor(_color)));
                }
                else
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(IDebugLog("no hay espacio para más jugadores" + " En la sala " + tableroNAme));
                    return(TransactionResult.Abort());
                }
            }
            // You must set the Value to indicate data at that location has changed.
            mutableData.Value = leaders;
            return(TransactionResult.Success(mutableData));
        }
Пример #14
0
 private void AddScoreToLeaders(int score, string nickname, string timestamp)
 {
     ScoresReference.RunTransaction(mutableData =>
     {
         // 서버에 있는 점수 리스트
         var leaders = mutableData.Value as List <object>;
         // 점수 리스트가 없으면, 생성
         if (leaders == null)
         {
             leaders = new List <object>();
         }
         // 점수 리스트가 최대 개수를 넘었으면, 가장 작은 점수를 제거
         else if (mutableData.ChildrenCount >= rankingList.Count)
         {
             var minScore  = long.MaxValue;
             object minVal = null;
             foreach (var child in leaders)
             {
                 var childDic = child as Dictionary <string, object>;
                 if (childDic == null)
                 {
                     continue;
                 }
                 var rankingEntry = new RankingInfo(childDic);
                 if (rankingEntry == null)
                 {
                     continue;
                 }
                 if (rankingEntry.score < minScore)
                 {
                     minScore = rankingEntry.score;
                     minVal   = child;
                 }
             }
             // 새 점수가 순위에 들지못했으면, 실패했다고 처리
             if (minScore > score)
             {
                 return(TransactionResult.Abort());
             }
             leaders.Remove(minVal);
         }
         // 리스트에 새 점수를 추가
         var newEntry = new RankingInfo(score, nickname, timestamp);
         leaders.Add(newEntry.ToDictionary());
         // 내림차순으로 정렬
         leaders.Sort((a, b) =>
         {
             var rankingA = new RankingInfo(a as Dictionary <string, object>);
             var rankingB = new RankingInfo(b as Dictionary <string, object>);
             return(rankingB.score.CompareTo(rankingA.score));
         });
         mutableData.Value = leaders;
         // Ranking UI에 반영
         rankingInfoList.Clear();
         foreach (var v in leaders)
         {
             rankingInfoList.Add(new RankingInfo(v as Dictionary <string, object>));
         }
         // 성공했다고 처리
         return(TransactionResult.Success(mutableData));
     });
 }
Пример #15
0
        // A realtime database transaction receives MutableData which can be modified
        // and returns a TransactionResult which is either TransactionResult.Success(data) with
        // modified data or TransactionResult.Abort() which stops the transaction with no changes.
        TransactionResult AddScoreTransaction(MutableData mutableData)
        {
            List <object> Faculties = mutableData.Value as List <object>;

            if (Faculties == null)
            {
                Faculties = new List <object>();
            }
            else if (mutableData.ChildrenCount >= MaxScores)
            {
                // If the current list of scores is greater or equal to our maximum allowed number,
                // we see if the new score should be added and remove the lowest existing score.
                long   minScore = long.MaxValue;
                object minVal   = null;
                foreach (var child in Faculties)
                {
                    if (!(child is Dictionary <string, object>))
                    {
                        continue;
                    }
                    long   childScore = (long)((Dictionary <string, object>)child)["score"];
                    string extension  = (string)((Dictionary <string, object>)child)["extension"];

                    Debug.Log("extension url get working **************************************** " + extension);
                    if (childScore < minScore)
                    {
                        minScore = childScore;
                        minVal   = child;
                    }
                }
                // If the new score is lower than the current minimum, we abort.
                if (minScore > score)
                {
                    return(TransactionResult.Abort());
                }
                // Otherwise, we remove the current lowest to be replaced with the new score.
                Faculties.Remove(minVal);
            }

            // Now we add the new score as a new entry that contains the email address and score.
            Dictionary <string, object> newScoreMap = new Dictionary <string, object>();

            //newScoreMap["score"] = score;
            //newScoreMap["email"] = email;
            //***********************************************************************************************************************************************
            newScoreMap["year"]        = Global.year;
            newScoreMap["facultyname"] = Global.faculty_name;
            newScoreMap["subject"]     = Global.subject;

            newScoreMap["section"] = Global.section;

            newScoreMap["category_name"] = Global.category_name;

            newScoreMap["filename"]  = Global.destination_filename_with_extension_for_uploading;
            newScoreMap["extension"] = Global.extension;

            //newScoreMap["filename_url"] = Global.faculty_name + "/" + Global.year + "/" + Global.subject + "/" + Global.section + "/" + Global.category_name + "/" + Global.destination_filename_with_extension_for_uploading;

            //***********************************************************************************************************************************************
            Faculties.Add(newScoreMap);
            //Faculties.Add("Faculties/" + Global.faculty_name + "/" + Global.year + "/" + Global.subject + "/" + Global.section + "/" + Global.category_name + "/" + Global.destination_filename_with_extension_for_uploading );

            // You must set the Value to indicate data at that location has changed.
            mutableData.Value = Faculties;
            return(TransactionResult.Success(mutableData));
        }
Пример #16
0
    private static void AddScoreToLeaders(string uid, string timestamp, long score, int num)
    {
        ScoresReference[num].RunTransaction(mutableData =>
        {
            var leaders = mutableData.Value as List <object>;

            if (leaders == null)
            {
                leaders = new List <object>();
            }
            else if (mutableData.ChildrenCount >= MaxScores)
            {
                var minScore  = long.MaxValue;
                object minVal = null;
                foreach (var child in leaders)
                {
                    var childDic = child as Dictionary <string, object>;
                    if (childDic == null)
                    {
                        continue;
                    }

                    var scoreEntry = new ScoreEntry(childDic);
                    if (scoreEntry == null)
                    {
                        continue;
                    }

                    if (scoreEntry.score < minScore)
                    {
                        minScore = scoreEntry.score;
                        minVal   = child;
                    }
                }
                if (minScore > score)
                {
                    return(TransactionResult.Abort());
                }

                leaders.Remove(minVal);
            }

            object val = null;
            foreach (var child in leaders)
            {
                var childDic = child as Dictionary <string, object>;
                if (childDic == null)
                {
                    continue;
                }

                var scoreEntry = new ScoreEntry(childDic);
                if (scoreEntry == null)
                {
                    continue;
                }

                if (scoreEntry.uid == "")
                {
                    val = child;
                }
            }
            leaders.Remove(val);

            var newEntry = new ScoreEntry(uid, timestamp, score);
            leaders.Add(newEntry.ToDictionary());
            leaders.Sort((a, b) =>
            {
                var scoreA = new ScoreEntry(a as Dictionary <string, object>).score;
                var scoreB = new ScoreEntry(b as Dictionary <string, object>).score;

                if (scoreA == scoreB)
                {
                    return(0);
                }
                else if (scoreA > scoreB)
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            });

            mutableData.Value = leaders;
            return(TransactionResult.Success(mutableData));
        });
    }
Пример #17
0
 TransactionResult FoundCoinTransaction(MutableData mutableData)
 {
     return(TransactionResult.Abort());
 }
Пример #18
0
    async private void AddScoreToLeaders(string userName, float score, DatabaseReference leaderBoardRef)
    {
        //Passing DataSnapshot to generic task type, you get the results as a DataSnapshot:
        Task <DataSnapshot> leaderBoardTransactionTask = leaderBoardRef.RunTransaction(mutableData =>
        {
            List <object> leaders = mutableData.Value as List <object>;
            if (leaders == null)
            {
                leaders = new List <object>();
            }
            else if (mutableData.ChildrenCount >= MaxAmountOfHighScores)
            {
                float maxScore = float.MinValue;
                object maxVal  = null;
                foreach (var child in leaders)
                {
                    if (!(child is Dictionary <string, object>))
                    {
                        continue;
                    }
                    object testScore = ((Dictionary <string, object>)child)["score"];
                    Debug.Log(testScore);
                    float childScore = Convert.ToSingle(testScore);
                    if (childScore > maxScore)
                    {
                        maxScore = childScore;
                        maxVal   = child;
                    }
                }
                if (maxScore < score)
                {
                    Debug.Log(maxScore + " " + score);
                    // The new score is higher than the existing scores, abort.
                    Debug.Log("Higher than existing scores, don't add!");
                    return(TransactionResult.Abort());
                }
                // Remove the highest score.
                leaders.Remove(maxVal);
                Debug.Log("Score removed");
            }
            Debug.Log(mutableData.ChildrenCount);
            // Add the new high score.
            Debug.Log("Added new high score!");
            Dictionary <string, object> newScoreMap = new Dictionary <string, object>();
            newScoreMap["score"] = score;
            newScoreMap["user"]  = userName;
            leaders.Add(newScoreMap);
            mutableData.Value = leaders;
            return(TransactionResult.Success(mutableData));
        });

        try
        {
            //Await for asynchronous task to complete (or to throw error e.g. if user doesn't exist...
            await leaderBoardTransactionTask;
        }
        catch (AggregateException ae)
        {
            Debug.Log(ae.Message);
            return;
        }
        //Get DataSnapshot from transaction Result:
        DataSnapshot transactionResult = leaderBoardTransactionTask.Result;
        //Get JSON from DataSnapshot:
        string resultingJSON = transactionResult.GetRawJsonValue();

        //Format JSON properly so that JsonUtility can instantiate objects:
        resultingJSON = "{\"leaderboards\":" + resultingJSON + "}";
        Debug.Log("JSON Result:\n" + resultingJSON);
        //Instantiate Leaderboard that then holds list of LeaderboardEntry instances:
        Leaderboard leaderboard = JsonUtility.FromJson <Leaderboard>(resultingJSON);

        //Now that we have instances of objects it's trivial to show leaderboards in UI:
        leaderboard.leaderboards = leaderboard.leaderboards.OrderBy(entry => entry.score).ToList();

        // Empty the leadeboardContainer from entries

        /*
         * foreach (Transform child in leaderboardEntryContainer.transform)
         *  Destroy(child.gameObject);
         */
        string scoreString = "";

        leaderboard.leaderboards.ToList().ForEach(lbEntry => {
            scoreString += lbEntry.user + " | " + HelperFunctions.TimeConvertToString(lbEntry.score) + "\n";
        });

        leaderBoardString.text = scoreString;

        // SetLeaderBoardString(scoreString);
        Debug.Log(scoreString);
    }
Пример #19
0
    public void JoinGame(GameInfo _gameInfo)
    {
        if (AuthenticationManager.m_Instance.m_User == null)
        {
            Toast.m_Instance.ShowMessage("You have to login or create account first...", 5);
            return;
        }

        Toast.m_Instance.ShowMessageUntilinterrupt("Joining at creator uid : " + _gameInfo.m_CreatorUID);
        DatabaseReference _joinedPlayersDatabaseRef = FirebaseDatabase.DefaultInstance.GetReference(GetJoinedPlayerPath(_gameInfo.m_CreatorUID));

        _joinedPlayersDatabaseRef.RunTransaction(mutableData =>
        {
            Dictionary <string, object> _joinedPlayers = mutableData.Value as Dictionary <string, object>;
            long count = mutableData.ChildrenCount;

            string _userUID     = AuthenticationManager.m_Instance.m_User.UserId;
            string _displayName = AuthenticationManager.m_Instance.m_User.DisplayName;

            bool _isPlayerAlreadyJoined = false;

            if (_joinedPlayers == null)
            {
                _joinedPlayers = new Dictionary <string, object>();
            }
            else if (_joinedPlayers.Count < 4)
            {
                foreach (var _joinedPlayer in _joinedPlayers)
                {
                    if (_joinedPlayer.Key == _userUID)
                    {
                        _isPlayerAlreadyJoined = true;
                    }
                }
            }
            else if (mutableData.ChildrenCount >= 4)
            {
                Toast.m_Instance.ShowMessage("Joined aborted at " + _gameInfo + ", child count " + count, 10);
                return(TransactionResult.Abort());
            }

            if (_isPlayerAlreadyJoined == false)
            {
                Dictionary <string, object> _newJoinedPlayer = new Dictionary <string, object>();
                _newJoinedPlayer.Add(r_displayName, _displayName);
                _newJoinedPlayer.Add(r_gameCreatorUID, _gameInfo.m_CreatorUID);
                _joinedPlayers.Add(_userUID, _newJoinedPlayer);
                mutableData.Value = _joinedPlayers;
                Toast.m_Instance.ShowMessage("Joined at " + _gameInfo + ", child count " + count, 10);
            }
            else
            {
                Toast.m_Instance.ShowMessage("Joined aborted because of already joined at " + _gameInfo + ", child count " + count, 10);
            }

            GameManager.m_Instance.m_GameInfo    = _gameInfo;
            GameManager.m_Instance.m_MyGameState = GameState.Joining;
            SubscribeJoinOrRemovePlayerEventHandler(GameManager.m_Instance.m_GameInfo);
            SubscribeOnGameStateChangedEventHandler(GameManager.m_Instance.m_GameInfo);
            MenuController.m_Instance.ShowMenuPage(MenuPage.StartGameMenuPage);

            return(TransactionResult.Success(mutableData));
        });
    }