Ejemplo n.º 1
0
    /// <summary>
    /// Handle the creation of a new Leaderboard entry
    /// </summary>
    /// <param name="_name"></param>
    /// <param name="_score"></param>
    private void HandleNewEntry(string _name, int _score)
    {
        LeaderboardEntry _newEntry = new LeaderboardEntry();

        _newEntry.position = 1;
        _newEntry.name     = _name;
        _newEntry.score    = _score;

        // if the leaderboard is empty
        if (leaderboard.Count == 0)
        {
            _newEntry.position = 1;
        }
        else
        {
            // the position increment by 1 every time ther's an higher score saved
            foreach (LeaderboardEntry _current in leaderboard)
            {
                if (_current.score >= _score)
                {
                    _newEntry.position++;
                }
            }

            // if the position is higher than the maxEntries it can't be saved
            if (_newEntry.position == maxEntries + 1)
            {
                return;
            }

            // Rearrange the list with the new positions and remove the last element if present
            List <LeaderboardEntry> _temp = new List <LeaderboardEntry>();
            foreach (LeaderboardEntry _current in leaderboard)
            {
                if (_current.position < _newEntry.position)
                {
                    _temp.Add(_current);
                }
                else
                {
                    _current.position++;
                    if (_current.position != maxEntries + 1)
                    {
                        _temp.Add(_current);
                    }
                }
            }

            leaderboard = _temp;
        }

        // add the new element to the leaderboard list
        leaderboard.Add(_newEntry);

        // save the list in playerprefs
        string _toSave = JsonUtility.ToJson(new LeaderboardData(leaderboard));

        PlayerPrefs.SetString("leaderboard", _toSave);
        PlayerPrefs.Save();
    }
Ejemplo n.º 2
0
    void CreateLeaderboardEntryField(LeaderboardEntry entry)
    {
        Transform     entryField = Instantiate(leaderboardEntry, leaderboardEntryContainer.transform);
        RectTransform entryRect  = entryField.transform.GetComponent <RectTransform>();

        entryRect.anchoredPosition = new Vector2(0, -(entryRect.rect.height / 2f) - entryRect.rect.height * leaderboardEntryFieldList.Count);

        if (leaderboardEntryFieldList.Count % 2 == 1)
        {
            entryField.transform.Find("LeaderboardEntryBG").GetComponent <Image>().color -= new Color(29f / 255f, 29f / 255f, 29f / 255f, 0); // Every other color is dark tinted version of the original color
        }

        entryField.transform.Find("RankNro").GetComponent <TextMeshProUGUI>().text    = (leaderboardEntryFieldList.Count + 1).ToString();
        entryField.transform.Find("PlayerName").GetComponent <TextMeshProUGUI>().text = entry.name;

        entryField.transform.Find("PlayerTime").GetComponent <TextMeshProUGUI>().text = Mathf.FloorToInt(entry.time / 60f).ToString() + "m:" + ((Mathf.RoundToInt(entry.time) % 60)).ToString() + "s";
        //entryField.transform.Find("PlayerScore").GetComponent<TextMeshProUGUI>().text = entry.score.ToString();
        entryField.transform.Find("PlayerKills").GetComponent <TextMeshProUGUI>().text = entry.kills.ToString();
        entryField.transform.Find("PlayerWave").GetComponent <TextMeshProUGUI>().text  = entry.wave.ToString();

        //entryField.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = (leaderboardEntryFieldList.Count + 1).ToString();
        //entryField.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = entry.name;
        //entryField.transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = entry.score.ToString();
        //entryField.transform.GetChild(3).GetComponent<TextMeshProUGUI>().text = entry.kills.ToString();
        //entryField.transform.GetChild(4).GetComponent<TextMeshProUGUI>().text = entry.wave.ToString();

        entryField.gameObject.SetActive(true);

        leaderboardEntryFieldList.Add(entryField);
    }
Ejemplo n.º 3
0
        private async Task <bool> RemoveAsync(string board, LeaderboardEntry entry)
        {
            _logger.LogInformation($"Check if {entry} already exists in the leaderboard {board}.");
            var db = _db;

            return(await db.SortedSetRemoveAsync(board, JsonConvert.SerializeObject(entry)));
        }
Ejemplo n.º 4
0
 public void SetEntry(LeaderboardEntry entry, int place)
 {
     _entry           = entry;
     _placeLabel.text = place.ToString();
     _nameLabel.text  = entry.Name;
     _scoreLabel.text = entry.Score.ToString("N0");
 }
Ejemplo n.º 5
0
    void CreateScoreEntry(int place, CSVScoreEntry entry)
    {
        GameObject       obj = (GameObject)Instantiate(_leaderboardEntryPrefab, _scrollParent);
        LeaderboardEntry leaderboardEntry = obj.GetComponent <LeaderboardEntry>();

        leaderboardEntry.SetupWithScoreEntry(place, entry);
    }
        // POST: api/ToDoItemList
        public void Post(LeaderboardEntry entry)
        {
            CheckCallerId();

            entry.ID = mockData.Count > 0 ? mockData.Keys.Max() + 1 : 1;
            mockData.Add(entry.ID, entry);
        }
Ejemplo n.º 7
0
    /// <summary>
    /// Updates the scoreboard online.
    /// </summary>
    private void UpdateScoreboard()
    {
        // Request data
        WWW bestTimes = new WWW(GET_SCORES_URL + "track=" + trackID);

        while (!bestTimes.isDone)
        {
            ;
        }

        // Parse data to array of JSON objects
        JsonData data = JsonMapper.ToObject(bestTimes.text);

        // Create array to pull results from
        LeaderboardEntry[] results = new LeaderboardEntry[data.Count];

        // Convert JSON data to C# objects
        for (int ii = 0; ii < data.Count; ++ii)
        {
            results[ii] = JsonMapper.ToObject <LeaderboardEntry>(data[ii].ToJson());
            Debug.Log(ii + ", " + data[ii].ToJson() + ", " + results[ii].Name);
        }

        // Display results
        leaderboardText.text = "Top Times:" + results[0].Name + "  " + results[0].Time;
    }
Ejemplo n.º 8
0
    // Adds an entry to the leaderboard
    private void AddEntry(LeaderboardEntry entryData, List <Transform> transformList)
    {
        // Instantiates an entry template at the entry container's location
        Transform entryTransform = Instantiate(entryTemplate, entryContainer);
        // Saves the entry's rect transform
        RectTransform entryRectTransform = entryTransform.GetComponent <RectTransform>();

        // Descends the anchored position based on the entry's index
        entryRectTransform.anchoredPosition = new Vector2(0, -templateHeight * transformList.Count);

        // Fills entry text using entry data
        entryTransform.Find("Entry Player Name").GetComponent <Text>().text = entryData.playerName;
        entryTransform.Find("Entry Wave").GetComponent <Text>().text        = entryData.wavesSurvived.ToString();
        entryTransform.Find("Entry Score").GetComponent <Text>().text       = entryData.playerScore.ToString();

        // Alternates background opacity
        if (transformList.Count % 2 != 0)
        {
            entryTransform.Find("Entry Background").GetComponent <Image>().color = Color.clear;
        }

        // Adds the entry to the transform list
        transformList.Add(entryTransform);

        // Enables the gameObject
        entryTransform.gameObject.SetActive(true);
    }
Ejemplo n.º 9
0
        public bool GetDownloadedLeaderboardEntry(LeaderboardEntriesHandle entries, int index,
                                                  out LeaderboardEntry entry, int[] details)
        {
            CheckIfUsable();
            int numberOfDetails = details == null ? 0 : details.Length;

            using (NativeBuffer entryBuffer = new NativeBuffer(Marshal.SizeOf(typeof(LeaderboardEntry))))
            {
                using (NativeBuffer detailsBuffer = new NativeBuffer(numberOfDetails * sizeof(int)))
                {
                    bool result = NativeMethods.Stats_GetDownloadedLeaderboardEntry(entries.AsUInt64, index,
                                                                                    entryBuffer.UnmanagedMemory, detailsBuffer.UnmanagedMemory, numberOfDetails);

                    // Read the entry directly from the unmanaged buffer
                    entry = LeaderboardEntry.Create(entryBuffer.UnmanagedMemory, entryBuffer.UnmanagedSize);

                    for (int i = 0; i < numberOfDetails; i++)
                    {
                        // Read all the detail values from the unmanaged buffer
                        details[i] = Marshal.ReadInt32(detailsBuffer.UnmanagedMemory, sizeof(int) * i);
                    }

                    return(result);
                }
            }
        }
    public void AddEntry(LeaderboardEntry entry, bool isMine, int index)
    {
        rank.text = $"#{index}";
        if (isMine)
        {
            rank.color = mineColour;
        }

        name.text = $"{entry.name}";
        if (isMine)
        {
            name.color = mineColour;
        }

        score.text = entry.score.ToString();
        if (isMine)
        {
            score.color = mineColour;
        }

        date.text = entry.date.ToString("dd MMM yyyy");
        if (isMine)
        {
            date.color = mineColour;
        }
    }
        public async Task<IHttpActionResult> PutLeaderboardEntry(int id, LeaderboardEntry leaderboardEntry)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != leaderboardEntry.Id)
            {
                return BadRequest();
            }

            db.Entry(leaderboardEntry).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LeaderboardEntryExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Ejemplo n.º 12
0
    public void MakeGood(string userName, Color userColor)
    {
        LeaderboardEntry entry = GetEntry(userName, userColor);

        entry.Team       = OtherModes.Team.Good;
        entry.LastAction = DateTime.Now;
    }
Ejemplo n.º 13
0
    private void CheckAndSort()
    {
        if (!_sorted)
        {
            _entryList.Sort(CompareScores);
            _entryListSolo.Sort(CompareSoloTimes);
            _sorted = true;

            int i = 1;
            LeaderboardEntry previous = null;
            foreach (LeaderboardEntry entry in _entryList)
            {
                if (previous == null)
                {
                    entry.Rank = 1;
                }
                else
                {
                    entry.Rank = (CompareScores(entry, previous) == 0) ? previous.Rank : i;
                }
                previous = entry;
                i++;
            }

            i = 1;
            foreach (LeaderboardEntry entry in _entryListSolo)
            {
                entry.SoloRank = i++;
            }
        }
    }
Ejemplo n.º 14
0
    private void FillLeaderboard()
    {
        if (globalLeaderboard.data == null)
        {
            return;
        }

        currentValues = new List <LeaderboardEntry>();

        foreach (GlobalstatsIO_LeaderboardValue v in globalLeaderboard.data)
        {
            LeaderboardEntry entry = new LeaderboardEntry(v);
            //if (entry.Graph.Equals(currGraphName))
            //{
            currentValues.Add(entry);
            //}
        }

        for (int i = 0; i < leaderboardCells.Count; i++)
        {
            if (pageIndex * leaderboardCells.Count + i < currentValues.Count)
            {
                LeaderboardEntry entry = currentValues[pageIndex * leaderboardCells.Count + i];
                entry.Rank = pageIndex * leaderboardCells.Count + i + 1;
                SetLeaderboardEntryToUi(leaderboardCells[i], entry);
            }
            else
            {
                leaderboardCells [i].SetActive(false);
            }
        }
    }
Ejemplo n.º 15
0
    // Inserts new object if its in highscore list
    public bool InsertEntry(LeaderboardEntry entry)
    {
        bool inserted = false;

        if (board.Count == 0)
        {
            board.Add(entry);
            inserted = true;
        }
        // If entry needs to be added last in a not full list
        else if (board.Count < listSize && board.Last().GetScore() > entry.GetScore())
        {
            board.Insert(board.Count, entry);
            inserted = true;
        }
        else
        {
            int minimum = Mathf.Min(board.Count, listSize);
            for (int i = 0; i < minimum; i++)
            {
                LeaderboardEntry entryAtIndex = board.ElementAt(i);
                if (entryAtIndex.GetScore() < entry.GetScore())
                {
                    board.Insert(i, entry);
                    return(true);
                }
            }
        }
        return(inserted);
    }
Ejemplo n.º 16
0
    private void PositionLeaderboard(LeaderboardEntry target)
    {
        if (target == null)
        {
            return;
        }
        Transform transform = null;

        for (int i = 0; i < this.top50Grid.transform.childCount; i++)
        {
            Transform child = this.top50Grid.transform.GetChild(i);
            if (child.gameObject.activeSelf)
            {
                transform = child;
            }
        }
        if (transform == null)
        {
            return;
        }
        float     num        = this.leaderboardListScroller.UpperBound;
        Transform transform2 = target.transform;

        num -= transform2.localPosition.y;
        num -= (Mathf.Abs(this.leaderboardListScroller.UpperBound) + Mathf.Abs(this.leaderboardListScroller.LowerBound)) / 2f;
        this.singleRanksGrid.transform.position = transform.transform.position + Vector3.down * this.singleRanksGrid.VerticalGap;
        if (transform2.parent == this.singleRanksGrid.transform)
        {
            num -= transform.transform.localPosition.y + this.singleRanksGrid.VerticalGap;
        }
        num = Mathf.Clamp(num, this.leaderboardListScroller.UpperBound, this.leaderboardListScroller.LowerBound + this.leaderboardListScroller.TotalHeight);
        this.top50Grid.transform.localPosition  = new Vector3(0f, num);
        this.singleRanksGrid.transform.position = transform.transform.position + Vector3.down * this.singleRanksGrid.VerticalGap;
    }
Ejemplo n.º 17
0
    public void SyncronizeToSteamLeaderBoardIfNeeded()
    {
        // try fetch the players leaderboard score one time
        if (fetchSteamLeaderboardEntry && steamLeaderboard.foundLeaderboard && steamLeaderboard.downloadedLeaderboard && !steamLeaderboard.downLoadingUserEntry)
        {
            int fetchedMMR = steamLeaderboard.ReadDownloadedUserLeaderboardEntry(); // read user mmr
            intro_playerMMR.text       = fetchedMMR.ToString();                     // syncronize the ui with the fetched value
            playerController.playerMMR = fetchedMMR;
            fetchSteamLeaderboardEntry = false;
        }

        // try fetch the top 10 leaderboard scores one time
        if (fetchSteamLeaderboardTop100Entries && steamLeaderboard.foundLeaderboard && steamLeaderboard.downloadedLeaderboard && !steamLeaderboard.downLoadingTop100Entries)
        {
            steamLeaderboard.top100Entries = steamLeaderboard.ReadDownloadedTop100Entries(); // read top 10 entries
            for (int i = 0; i < steamLeaderboard.top100Entries.Length; i++)
            {
                LeaderboardEntry leaderboardEntryPrefab = steamLeaderBoardTop100EntriesUIPrefabsList.ToArray()[i]; // syncronize the ui with the fetched values
                LeaderEntry      top100Entry            = steamLeaderboard.top100Entries[i];
                leaderboardEntryPrefab.rank               = top100Entry.globalRank;
                leaderboardEntryPrefab.mmrText.text       = top100Entry.score.ToString();
                leaderboardEntryPrefab.nameText.text      = SteamFriends.GetFriendPersonaName(top100Entry.id);
                leaderboardEntryPrefab.rankText.text      = top100Entry.globalRank.ToString() + ")";
                leaderboardEntryPrefab.steamAvatar.sprite = top100Entry.avatar;
                if (top100Entry.globalRank == 1 || top100Entry.globalRank == 2 || top100Entry.globalRank == 3)
                {
                    leaderboardEntryPrefab.trophyIcon.gameObject.SetActive(true);
                    leaderboardEntryPrefab.trophyIcon.sprite = top100Entry.trophyIcon;
                }
            }
            fetchSteamLeaderboardTop100Entries = false;
        }
    }
Ejemplo n.º 18
0
        // We have to convert the acPlugins4net-Leaderboard to a minoRating one. This is pretty stupid mapping
        LeaderboardEntry[] ConvertLB(List <MsgLapCompletedLeaderboardEnty> leaderboard)
        {
            var array = new LeaderboardEntry[leaderboard.Count];

            for (int i = 0; i < leaderboard.Count; i++)
            {
                string     steamId;
                DriverInfo driver;
                if (this.PluginManager.TryGetDriverInfo(leaderboard[i].CarId, out driver))
                {
                    steamId = driver.DriverGuid;
                }
                else
                {
                    // should not happen
                    steamId = string.Empty;
                }

                array[i] = new LeaderboardEntry()
                {
                    CarId       = leaderboard[i].CarId,
                    DriverId    = steamId,
                    LapsDriven  = leaderboard[i].Laps,
                    Time        = leaderboard[i].Laptime,
                    HasFinished = leaderboard[i].HasFinished,
                };
            }
            ;

            return(array);
        }
Ejemplo n.º 19
0
    public static void GetScore(Action <List <LeaderboardEntry> > callback, int EntryCount = 100)
    {
        new LeaderboardDataRequest().SetLeaderboardShortCode("TIME").SetEntryCount(EntryCount).Send((response) =>
        {
            Debug.Log(response.JSONString);
            if (!response.HasErrors)
            {
                var list = new List <LeaderboardEntry>();
                Debug.Log("Found Leaderboard Data...");
                foreach (GameSparks.Api.Responses.LeaderboardDataResponse._LeaderboardData entry in response.Data)
                {
                    var resultentry = new LeaderboardEntry();

                    resultentry.Rank       = (int)entry.Rank;
                    resultentry.PlayerName = entry.UserName;
                    resultentry.Time       = Convert.ToInt32(entry.JSONData["TIME"]);

                    list.Add(resultentry);
                }

                callback(list);
            }
            else
            {
                Debug.LogError("Error Retrieving Leaderboard Data...");
            }
        });
    }
Ejemplo n.º 20
0
 public void UpdateInfo(LeaderboardEntry entry)
 {
     _playerName.text  = entry.player_name;
     _comboPoints.text = entry.combo_points.ToString();
     _maxCombo.text    = entry.max_combo.ToString();
     _totalScore.text  = entry.total_score.ToString();
 }
Ejemplo n.º 21
0
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);

            //This area serves to prepare the connections with the database and fetch from it.
            //Loads up your last sent entry
            string save = PlayerPrefs.GetString("LeaderboardSave");
            if (save != "")
            {
                string[] saveArr = save.Split(':');
                playerEntry = new LeaderboardEntry(saveArr[0], saveArr[1], float.Parse(saveArr[2]));
            }

            for (int i = 0; i < Leaderboards.Count; i++)
            {
                Leaderboards[i].Init();
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }
Ejemplo n.º 22
0
    static public void AddLeaderboardScoreEntry(float score, string name)
    {
        //create leaderboardEntry
        LeaderboardEntry leaderboardEntry = new LeaderboardEntry {
            score = score, name = name
        };

        //Load saved leaderboardScores
        string jsonString = PlayerPrefs.GetString("leaderboardTable");

        if (jsonString == "")
        {
            SetNootLeaderBoard();
            jsonString = PlayerPrefs.GetString("leaderboardTable");
            //JsonUtility.ToJson()
        }
        LeaderboardScores leaderboardScores = JsonUtility.FromJson <LeaderboardScores>(jsonString);

        //Add new entry to leaderboardScores
        leaderboardScores.leaderboardEntryList.Add(leaderboardEntry);
        SortScores(leaderboardScores.leaderboardEntryList);

        while (leaderboardScores.leaderboardEntryList.Count > 15)
        {
            leaderboardScores.leaderboardEntryList.RemoveAt(15);
        }

        //save updated leaderboardScores
        string json = JsonUtility.ToJson(leaderboardScores);

        PlayerPrefs.SetString("leaderboardTable", json);
        PlayerPrefs.Save();
    }
Ejemplo n.º 23
0
    private void HandleEntrySubmitted(bool success)
    {
        if (success)
        {
            LeaderboardEntry topEntry = myEntries.OrderByDescending(e => e.score).First();
            int index = entries.IndexOf(topEntry) + 1;
            if (myEntries.Count == 1)
            {
                infoMessage.text = $"You've placed #{index} out of " + entries.Count + " entries";
            }
            else
            {
                LeaderboardEntry newestEntry = myEntries.OrderByDescending(e => e.date).First();
                int newestEntryIndex         = entries.IndexOf(newestEntry) + 1;
                infoMessage.text = $"You've placed #{newestEntryIndex} out of " + entries.Count + $" entries. Your highest placement is #{index}";
            }
        }

        nameInput.gameObject.SetActive(false);
        secretInput.gameObject.SetActive(false);
        refreshButton.gameObject.SetActive(true);

        submitButton.GetComponentInChildren <TextMeshProUGUI>().text = "play again";
        submitButton.onClick.RemoveAllListeners();
        submitButton.onClick.AddListener(() => SceneManager.LoadScene("Game"));
    }
Ejemplo n.º 24
0
    private void initValues(int num, LeaderboardEntry entry, bool isNewRecord)
    {
        newRecord = isNewRecord;
        Color textColor = Color.white;

        if (newRecord)
        {
            textColor = ColorPalette.getColor(4, 1);
        }
        else if (num == 1)
        {
            textColor = ColorPalette.getColor(3, 1);
        }
        else if (num == 2)
        {
            textColor = ColorPalette.getColor(2, 2);
        }
        else if (num == 3)
        {
            textColor = ColorPalette.getColor(12, 3);
        }
        numText.color = nameText.color = floorText.color = timeText.color = textColor;
        numText.text  = num + ".";

        if (entry == null)
        {
            return;
        }
        nameText.text  = entry.name.ToLower();
        floorText.text = entry.floor.ToString();
        timeText.text  = TimeSpan.FromSeconds(entry.time).ToString(@"hh\:mm\:ss");
    }
Ejemplo n.º 25
0
    // Download from Cloud Storage into a byte array.
    protected IEnumerator DownloadBytesWithEmail(Dictionary <string, object> scoreEntry)
    {
        var storageReference = GetStorageReference();
        var imageReference   = storageReference.Child("images/" + scoreEntry["email"].ToString());
        //Texture
        Texture2D tex = new Texture2D(128, 128, TextureFormat.PVRTC_RGBA4, false);

        DebugLog(String.Format("Downloading {0} ...", imageReference.Path));
        var task = imageReference.GetBytesAsync(
            0, new StorageProgress <DownloadState>(DisplayDownloadState),
            cancellationTokenSource.Token);

        yield return(new WaitForTaskCompletion(this, task));

        if (!(task.IsFaulted || task.IsCanceled))
        {
            DebugLog("Finished downloading bytes");
            //Add sprite
            fileContents = System.Text.Encoding.Default.GetString(task.Result);
            tex.LoadImage(task.Result);
            Sprite profilePic = Sprite.Create(tex, new Rect(0, 0, 128, 128), new Vector2());
            scoreEntry["sprite"] = profilePic;
            LeaderboardEntry e = (LeaderboardEntry)scoreEntry["entry"];
            e.AddSprite(profilePic);
            DebugLog(String.Format("File Size {0} bytes\n", fileContents.Length));
        }
    }
Ejemplo n.º 26
0
    private void UpdateData(LeaderboardResult data)
    {
        if (Stat != null &&
            (data.NextQuery == null ||
             (data.NextQuery != null && data.NextQuery.StatName == Stat.Name)))
        {
            this.leaderboardData = data;

            if (this.totalPages == 0)
            {
                this.totalPages = (this.leaderboardData.TotalRowCount - 1) / this.entryCount + 1;
            }

            this.pageText.text = string.Format("Page: {0} / {1}", this.currentPage + 1, this.totalPages);

            while (this.contentPanel.childCount > 0)
            {
                var entry = this.contentPanel.GetChild(0).gameObject;
                this.entryObjectPool.ReturnObject(entry);
            }

            foreach (LeaderboardRow row in this.leaderboardData.Rows)
            {
                GameObject       entryObject = this.entryObjectPool.GetObject();
                LeaderboardEntry entry       = entryObject.GetComponent <LeaderboardEntry>();

                entry.Data = row;

                entryObject.transform.SetParent(this.contentPanel);
            }
            this.UpdateButtons();
        }
    }
Ejemplo n.º 27
0
	IEnumerator OnLeaderboardHttpRequest (WWW httpRequest)
	{
		// Wait until the HTTP request has received a response
		yield return httpRequest;

		// Deserialize the response into a list of objects
		List<object> list = Facebook.MiniJSON.Json.Deserialize (httpRequest.text) as List<object>;

		int rank = 1;

		foreach (object dict in list) {
			Dictionary<string, object> d = dict as Dictionary<string, object>;

			LeaderboardEntry entry = new LeaderboardEntry ();

			entry.Rank = rank;
			entry.Name = d ["userName"] as string;

			if (entry.Name == "") {
				entry.Name = "Guest";
			}
            
			try {
				entry.Score = int.Parse (d ["score"].ToString ());
			} catch (Exception e) {
				Debug.Log(e);
				entry.Score = 0;
			}

			Leaderboard.Instance.LeaderboardEntries.Add (entry);

			rank++;
		}
	}
Ejemplo n.º 28
0
    private IEnumerator Download()
    {
        StartCoroutine(Global.DownloadFromLeaderboard("scores", top));

        message.text = Global.leaderboardDownloadMessage;

        while (Global.downloadingScore)
        {
            yield return(null);
        }

        message.text = Global.leaderboardDownloadMessage;

        string[] rows = Global.latestLeaderboards.Split('\n');

        int rank = 1;

        foreach (string r in rows)
        {
            if (string.IsNullOrEmpty(r))
            {
                continue;
            }

            string[] cols = r.Split('/');

            LeaderboardEntry lbe = Instantiate(lbPrefab, content).GetComponent <LeaderboardEntry>();

            string name  = cols[0];
            string comp  = cols[1];
            string auc   = cols[2];
            string score = cols[3];
            string dt    = cols[4].Substring(0, 10);
            string file  = cols[5];
            if (!int.TryParse(cols[6], out int version))
            {
                version = 1;
            }

            lbe.SetValues(file, version, rank.ToString(), name, comp, auc, score, dt);

            // colors and borders for top ranks
            if (rank <= topColors.Length)
            {
                lbe.SetTextColor(topColors[rank - 1]);
            }

            if (rank <= backColors.Length)
            {
                Border border = Instantiate(borderPrefab, scroll).GetComponent <Border>();
                border.target = lbe.GetComponent <RectTransform>();
                border.transform.SetAsFirstSibling();
                border.GetComponent <Image>().color = backColors[rank - 1];
            }

            rank += 1;

            yield return(null);
        }
    }
Ejemplo n.º 29
0
    private void UpdateClosePlayers(int rank)
    {
        List <LeaderboardEntry> value = Singleton <LeaderboardRunner> .Instance.TournamentLeaderboard.Value;

        if (value == null || value.Count < 3)
        {
            return;
        }
        if (m_closePlayers[0] != null)
        {
            m_closePlayers[2] = CopyLeaderboardEntryToStaticOne(m_closePlayers[0]);
        }
        if (m_closePlayers[1] != null)
        {
            m_closePlayers[3] = CopyLeaderboardEntryToStaticOne(m_closePlayers[1]);
        }
        if (rank <= value.Count)
        {
            if (rank > 1)
            {
                m_closePlayers[0] = value[rank - 2];
            }
            if (rank < value.Count)
            {
                m_closePlayers[1] = value[rank];
            }
            if (rank < value.Count - 1)
            {
                m_closePlayers[4] = CopyLeaderboardEntryToStaticOne(value[rank + 1]);
            }
            m_playerEntry = value[rank - 1];
        }
    }
Ejemplo n.º 30
0
        /// <summary>
        /// Compare two leaderboard entries to check which belongs on higher position
        /// </summary>
        /// <param name="x">First entry for comparison</param>
        /// <param name="y">Second entry for comparison</param>
        /// <returns>Negative if first entry must be first. 0 if both should be at same location. Positive if second item should be on higher position</returns>
        protected int CompareLeaderboardEntries(LeaderboardEntry x, LeaderboardEntry y)
        {
            int ret = x.Points.CompareTo(y.Points);

            if (ret == 0)
            {
                ret = x.GoalScore.CompareTo(y.GoalScore);
            }

            if (ret == 0)
            {
                ret = x.GoalsScored.CompareTo(y.GoalsScored);
            }

            if (ret == 0)
            {
                ret = x.GoalsAgainst.CompareTo(y.GoalsAgainst);
            }

            if (ret == 0)
            {
                ret = CompareLeaderboardEntriesWithMatchesCriteria(x, y);
            }

            return(ret);
        }
Ejemplo n.º 31
0
 public async Task Update(LeaderboardEntry entry)
 {
     using (var connection = _connectionFactory.Open())
     {
         await connection.UpdateAsync(entry);
     }
 }
Ejemplo n.º 32
0
    private IEnumerator ChangeSetPlayerValues(LeaderboardEntry next, LeaderboardEntry prev, int rank)
    {
        yield return(new WaitForSeconds(1.5f));

        SetNextPlayersValues(next, rank - 1);
        SetPreviousPlayersValues(prev, rank + 1);
    }
        public async Task<IHttpActionResult> PostLeaderboardEntry(LeaderboardEntry leaderboardEntry)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.LeaderboardEntries.Add(leaderboardEntry);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = leaderboardEntry.Id }, leaderboardEntry);
        }
Ejemplo n.º 34
0
        public override void Deserialize(KnetikJSONNode json)
        {
            base.Deserialize (json);

            MetricID = json ["metric_id"].AsInt;
            SortStyle = json ["sort_style"].Value;
            QualifyingValue = json["qualifying_value"].AsInt;
            Size = json["size"].AsInt;
            PlayerCount = json["player_count"].AsInt;
            Level = json["level"].Value;
            MetricName = json["metric_name"].Value;
            Entries = new List<LeaderboardEntry>();

            foreach (KnetikJSONNode node in json["leaderboard_data"].Children)
            {
                LeaderboardEntry entry = new LeaderboardEntry();
                entry.Deserialize(node);
                Entries.Add(entry);
            }
        }
Ejemplo n.º 35
0
 List<LeaderboardEntry> DeserializeScores(string json)
 {
     List<LeaderboardEntry> leaderboard = new List<LeaderboardEntry>();
     JSONNode root = JSON.Parse(json);
     JSONNode data = root["data"];
     for (int i = 0; i < data.Count; i++)
     {
         LeaderboardEntry entry = new LeaderboardEntry();
         entry.Id = data[i]["user"]["id"];
         entry.Name = data[i]["user"]["name"];
         entry.Score = data[i]["score"].AsInt;
         leaderboard.Add(entry);
         if (entry.Id == FB.UserId)
             entry.Id = "me";
     }
     return leaderboard;
 }
Ejemplo n.º 36
0
        // We have to convert the acPlugins4net-Leaderboard to a minoRating one. This is pretty stupid mapping
        LeaderboardEntry[] ConvertLB(List<MsgLapCompletedLeaderboardEnty> leaderboard)
        {
            var array = new LeaderboardEntry[leaderboard.Count];
            for (int i = 0; i < leaderboard.Count; i++)
            {
                string steamId;
                DriverInfo driver;
                if (this.PluginManager.TryGetDriverInfo(leaderboard[i].CarId, out driver))
                {
                    steamId = driver.DriverGuid;
                }
                else
                {
                    // should not happen
                    steamId = string.Empty;
                }

                array[i] = new LeaderboardEntry()
                {
                    CarId = leaderboard[i].CarId,
                    DriverId = steamId,
                    LapsDriven = leaderboard[i].Laps,
                    Time = leaderboard[i].Laptime
                };
            };

            return array;
        }