public void SetWrongHighScoreName()
        {
            var highScore = new Highscore();
            var name = "1";

            highScore.Name = name;
        }
	//Make temporary copy of highscore leaderboards and store in highScoreDict
	public void makeHighScoreList() {
		highScoreDict = new Dictionary<string,Highscore> ();

		if (PlayerPrefs.GetString ("LoadedLevel") == "scn_endless") {
			currentKey = endlessKey;
		} else {
			currentKey = highScoreKey;
		}

		for (int i = 1; i <= 5; i++) {
			string tempKey = currentKey + i;
			bool hasKey = PlayerPrefs.HasKey(tempKey);
			//If the key exists, get it from persistence
			if(hasKey) {
				string tempName = PlayerPrefs.GetString (tempKey);
				int tempScore = PlayerPrefs.GetInt (tempName);
				Highscore tempHighScore = new Highscore(tempScore, tempName);
				highScoreDict.Add (tempKey, tempHighScore);
			//Else assign a new value to the key
			}else{
				Highscore temp = new Highscore(0 , "N/A" + i);
				highScoreDict.Add (tempKey, temp); 
			}
		}
	}
        public void HighScoreToStringTest()
        {
            var highScore = new Highscore("Veli", 10);
            var outputValue = "Veli-10";

            Assert.AreEqual(highScore.ToString(), outputValue);
        }
Exemple #4
0
        public void Start()
        {
            animator = GetComponent<Animator>();

            highscore = ProgressManager.GetProgress().highscores.Find(x => x.levelId == id);
            if (highscore != null && highscore.starCount > 0)
            {
                starScore = highscore.starCount;
            }
            else
            {
                starScore = 0;
            }

            Main.onSceneChange.AddListener(SceneChanged);

            Highscore.onStarChange.AddListener(HighscoreStarChanged);

            UpdateUILevel();

            if (createdByLevelswitch)
                animator.SetTrigger("levelswitch");
            else
                animator.SetTrigger("fadein");
        }
Exemple #5
0
    public void OnDeath()
    {
        var score = gameObject.GetComponent<Character>().PowerLevel;
        Highscore hs;
        if (JsonStorage.TryLoad("highscore.json", out hs))
        {
            if (score > hs.Score) {
                hs.Score = score;
                JsonStorage.Save("highscore.json", hs);
            }
        }
        else
        {
            hs = new Highscore();
            hs.Score = score;
            JsonStorage.Save("highscore.json", hs);
        }

        var go = GameObject.FindGameObjectsWithTag("MainUIRoot").FirstOrDefault();
        var master = go.GetComponent<SubUIMaster>();
        master.ShowEndScreenSubUI();

        AudioSystem.Get().PlayPlayerDeath();

        Destroy(gameObject);
    }
        public void SetWrongHighScorePoints()
        {
            var highScore = new Highscore();
            var value = -1;

            highScore.Value = value;
        }
        public void SetProperHighScorePoints()
        {
            var highScore = new Highscore();
            var value = 10;

            highScore.Value = value;

            Assert.AreEqual(highScore.Value, value);
        }
        public void SetProperHighScoreName()
        {
            var highScore = new Highscore();
            var name = "Veli";

            highScore.Name = name;

            Assert.AreEqual(highScore.Name, name);
        }
 /// Update is called once per frame
 //void Update () {}
 private void InitializeDemoUI()
 {
     _score = new Highscore()
     {
         score = 0,
         username = "******",
         id = ""
     };
 }
 public void OnHighscoresDownloaded(Highscore[] highscoreList)
 {
     for (int i = 0; i < highscoreFields.Length; i++)
     {
         highscoreFields[i].text = i + 1 + ". ";
         if (i < highscoreList.Length) {
            highscoreFields[i].text += highscoreList[i].username + " - " + highscoreList[i].score;
         }
     }
 }
 public void onHighscoresDownloaded(Highscore[] highscoreList)
 {
     for (int i = 0; i < highscoreText.Length; i++)
     {
         highscoreText[i].text = i + 1 + ". ";
         if (highscoreList.Length > i)
         {
             highscoreText[i].text += highscoreList[i].username + " - " + highscoreList[i].score;
         }
     }
 }
    public void OnHighscoresDownloaded(Highscore[] highscoreArray)
    {
        for (int i = 0; i < textHighscores.Length; i++)
        {
            textHighscores[i].text = (i+1) + ". ";

            if (highscoreArray.Length > i)
            {
                textHighscores[i].text += string.Format("({0:d}) player: <color=yellow>{1}</color> | score: <color=yellow>{2}</color>", highscoreArray[i].date, highscoreArray[i].username, highscoreArray[i].score);
            }
        }
    }
 private bool isValid(Highscore highscore)
 {
     if ( highscore.score > 0 )
     {
         return true;
     }
     else
     {
         Debug.Log("Score needs to be > 0");
         return false;
     }
 }
    void FormatHighscores(string textStream)
    {
        string[] entries = textStream.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
        highscoresList = new Highscore[entries.Length];

        for (int i = 0; i < entries.Length; i++)
        {
            string[] entryInfo = entries[i].Split(new char[] { '|' });
            string username = entryInfo[0];
            int score = int.Parse(entryInfo[1]);
            highscoresList[i] = new Highscore(username, score);
        }
    }
Exemple #15
0
 public void SetNewScore(int players, Highscore score)
 {
     players -= 1;
     if (players == 0)
     {
         onePlayerScores.Add(score);
     }
     else
     {
         twoPlayerScores.Add(score);
     }
     SortListsAscending(players);
 }
 public void Initialize(bool on, Highscore highscore)
 {
     Toggle(on);
     highScoreLabel.text = highscore.score.ToString("N0");
     bestTimeLabel.text = highscore.TimeString;
     if (highscore.rank > 0)
     {
         medalSprite.spriteName = medalNames[highscore.rank];
     }
     else
     {
         medalSprite.enabled = false;
     }
 }
	/**
	 * 
	 */
	public static bool GetScoreEqualOrMoreThan(ref Highscore.ScoreEntry result, float distance)
	{
		if (distance < mMinDistance || distance > mMaxDistance) return false;
		
		foreach(Highscore.ScoreEntry entry in mScoreEntries)
		{
			if (entry.Score >= distance)
			{
				result = entry;
				return true;
			}
		}

		return false;
	}
Exemple #18
0
 public string FormatToBeDisplayer(string someText)
 {
     string[] entries = someText.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
     highscoresList = new Highscore[entries.Length];
     string test = string.Empty; 
     for (int i = 0; i < entries.Length; i++)
     {
         string[] entryInfo = entries[i].Split(new char[] { '|' });
         string username = entryInfo[0];
         int score = int.Parse(entryInfo[1]);
         highscoresList[i] = new Highscore(username, score, entryInfo[2]);
         someText = highscoresList[i].level + "/ " + highscoresList[i].username + ": " + highscoresList[i].score + "\n";
         test += someText;
     }
     return test;
 }
    void FormatHighscores(string textStream)
    {
        string tempScore = " ";
        string[] entries = textStream.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
        highscoresList = new Highscore[entries.Length];

        for (int i = 0; i < SCORE_MAX; i++)
        {
            string[] entryInfo = entries[i].Split(new char[] { '|' });
            string username = entryInfo[0];
            int score = int.Parse(entryInfo[1]);
            highscoresList[i] = new Highscore(username, score);

            tempScore+= highscoresList[i].username + ": " + highscoresList[i].score +"\n" ;

        }
        scoreText.text = tempScore;
    }
	//Updates highScoreDict by adding the player score and see if it is in the top 5 
	public void updateHighScoreList(string name) {
		//Construct a new temporary dictionary which is an exact copy of highScoreDict
		Dictionary<string,Highscore> newDict = new Dictionary<string,Highscore>(highScoreDict);

		string duplicateName = name;
		int dupIndex = 1;
		while(PlayerPrefs.HasKey(duplicateName)) { 
			duplicateName = name + " (" + dupIndex + ")";
			dupIndex++;
		}

		Highscore temp = new Highscore (this.score.getScore (), duplicateName);

		//Add a temporary key called "HighScoreNew" with the score of the last game played
		newDict.Add (currentKey + "New", temp);
		int x = 1;

		//Loops through newDict in descending order of the highscores
		foreach (var item in newDict.OrderByDescending(i => newDict[i.Key].getHighscore ())) {

			//This switch statement assigns the top 5 scores
			switch(x)
			{
				case 1:
					highScoreDict[currentKey + "1"] = newDict[item.Key];
					break;
				case 2:
					highScoreDict[currentKey + "2"] = newDict[item.Key];
					break;
				case 3:
					highScoreDict[currentKey + "3"] = newDict[item.Key];
					break;
				case 4:
					highScoreDict[currentKey + "4"] = newDict[item.Key];
					break;
				case 5:
					highScoreDict[currentKey + "5"] = newDict[item.Key];
					break;
			}

			x++;
		}

	}				
        /// <summary>
        /// takes the current user points, sorts them with the top 5 user points form before and writes only the best 5 back in the file
        /// </summary>
        /// <param name="spentMoves">takes int value of how many moves the user has made before wining</param>
        public static void SortAndPrintChartFive(int spentMoves)
        {
            var consoleInut = new Reader().ReadUserInput();
            var userName = new Reader().ReadUsername();
            var currentScore = new Highscore(userName, spentMoves); // get current score
            var scores = GetHighScoresFromFile(); // read from file
            var results = new List<Highscore>();
            foreach (var item in scores)
            {
                results.Add(ScoreParser(item));
            } // add old highscores
            results.Add(currentScore); // add current score to highscores
            results.Sort((x1, x2) => x1.Value.CompareTo(x2.Value)); // sort score

            if (results.Count == Common.Constants.GlobalGameLogicDependencesValues.TopChartLength + 1)
            {
                results.RemoveAt(Common.Constants.GlobalGameLogicDependencesValues.TopChartLength);
            } // remove the last score from the sorted highscore list
            SaveToFile(results); // save to file
        }
Exemple #22
0
        }         // ReadHighscoresFromSettings()

        #endregion

        #region Generate hash from file for sending value to online server

        /*obs
         * /// <summary>
         * /// Generate hash from file
         * /// </summary>
         * /// <param name="filename">Filename</param>
         * private static byte[] GenerateHashFromFile(string filename)
         * {
         *      FileStream file = File.OpenRead(filename);
         *      byte[] readData = new byte[file.Length];
         *      file.Read(readData, 0, (int)file.Length);
         *      file.Close();
         *
         *      SHA1Managed shaHash = new SHA1Managed();
         *      return shaHash.ComputeHash(readData);
         * } // GenerateHashFromFile(filename)
         *
         * /// <summary>
         * /// Precalculated game file hash of "Rocket Commander.exe"
         * /// </summary>
         * static byte[] gameFileHash = null;
         */
        #endregion

        #region Static constructor
        /// <summary>
        /// Create Highscores class, will basically try to load highscore list,
        /// if that fails we generate a standard highscore list!
        /// </summary>
        static Highscores()
        {
            //obs: gameFileHash = GenerateHashFromFile("Rocket Commander.exe");

            if (ReadHighscoresFromSettings() == false)
            {
                // Generate default list
                highscores[9] = new Highscore("Newbie", "Easy Flight", 0);
                highscores[8] = new Highscore("Desert-Fox", "Easy Flight", 5000);
                highscores[7] = new Highscore("Waii", "Easy Flight", 10000);
                highscores[6] = new Highscore("ViperDK", "Easy Flight", 15000);
                highscores[5] = new Highscore("Netfreak", "Easy Flight", 20000);
                highscores[4] = new Highscore("Judge", "Easy Flight", 25000);
                highscores[3] = new Highscore("exDreamBoy", "Easy Flight", 30000);
                highscores[2] = new Highscore("Master_L", "Easy Flight", 35000);
                highscores[1] = new Highscore("Freshman", "Easy Flight", 40000);
                highscores[0] = new Highscore("abi", "Easy Flight", 45000);

                WriteHighscoresToSettings();
            }     // if
        }         // Highscores()
    private void SaveName()
    {
        if (m_inputField.text.Length > 0)
        {
            Highscore.AddHighscore(m_inputField.text, (int)MoneyManager.highscorePoints, (int)DAS.TimeSystem.TimePassedSeconds);
        }
        else
        {
            Highscore.AddHighscore("Noname", (int)MoneyManager.highscorePoints, (int)DAS.TimeSystem.TimePassedSeconds);
        }

        Highscore.SortHighscore();
        Highscore.SaveHighscore();
        m_lists.GetComponent <DisplayScoreList>().AnimateHighscoreList();
        m_inputField.readOnly = true;

        foreach (var item in m_buttons)
        {
            item.gameObject.SetActive(true);
        }
    }
Exemple #24
0
        /// <summary>
        /// Create Highscores class, will basically try to load highscore list,
        /// if that fails we generate a standard highscore list!
        /// </summary>
        static Highscores()
        {
            //obs: gameFileHash = GenerateHashFromFile("Rocket Commander.exe");

            if (ReadHighscoresFromSettings() == false)
            {
                // Generate default list
                highscores[9] = new Highscore("Newbie", DefaultLevelName, 0);
                highscores[8] = new Highscore("Master_L", DefaultLevelName, 50);
                highscores[7] = new Highscore("Freshman", DefaultLevelName, 100);
                highscores[6] = new Highscore("Desert-Fox", DefaultLevelName, 150);
                highscores[5] = new Highscore("Judge", DefaultLevelName, 200);
                highscores[4] = new Highscore("ViperDK", DefaultLevelName, 250);
                highscores[3] = new Highscore("Netfreak", DefaultLevelName, 300);
                highscores[2] = new Highscore("exDreamBoy", DefaultLevelName, 350);
                highscores[1] = new Highscore("Waii", DefaultLevelName, 400);
                highscores[0] = new Highscore("abi", DefaultLevelName, 450);

                WriteHighscoresToSettings();
            } // if (ReadHighscoresFromSettings)
        }
    public void Start()
    {
        Highscore highscore = new Highscore();

        highscore.player = PlayerPrefs.GetString("player");
        highscore.score  = PlayerPrefs.GetFloat("time");

        XmlSerializer    serializer = new XmlSerializer(typeof(List <Highscore>));
        List <Highscore> highscores = new List <Highscore> ();

        using (XmlTextReader reader = new XmlTextReader("highscores.xml")) {
            highscores = (List <Highscore>)serializer.Deserialize(reader);
        }

        highscores.Add(highscore);
        using (StreamWriter open = new StreamWriter("highscores.xml")) {
            serializer.Serialize(open, highscores);
        }

        PlayerPrefs.DeleteAll();
    }
        public async void AddScoresThenNewHighscore()
        {
            Highscore highscore;

            for (var i = 1; i < 15; i++)
            {
                highscore       = new Highscore();
                highscore.User  = "******" + i;
                highscore.Score = 100 + i;
                await _controller.PostHighscore(highscore);
            }
            highscore       = new Highscore();
            highscore.Score = 10000;
            highscore.User  = "******";
            await _controller.PostHighscore(highscore);

            Assert.Equal(highscore, _controller.GetHighscores().ElementAt(0));

            _context.HighScores.RemoveRange(_controller.GetHighscores());
            await _context.SaveChangesAsync();
        }
        public void Initialize()
        {
            _currentHighscore = CreateCurrentHighscore();

            var highscores = new List <Highscore>
            {
                CreateHighscore("Frank", _testDictionary, 80),
                CreateHighscore("Myself", _testDictionary, 50),
                CreateHighscore("Sandra", _testDictionary, 40),
                CreateHighscore("Sandra", _testDictionary, 70),
                CreateHighscore("Myself", new Dictionary("dict2", null), 20),
                _currentHighscore,
                CreateHighscore("Frank", _testDictionary, 30),
                CreateHighscore("Frank", _testDictionary, 60)
            };

            _repositoryMock = new Mock <IRepository>();
            _repositoryMock.Setup(p => p.GetAllHighscores(_testDictionary.Id)).Returns(highscores);

            _objectUnderTest = new HighscoreVM(_repositoryMock.Object, new ScoreCalculator());
        }
Exemple #28
0
    /// <summary>
    /// Fixeds the update.
    /// </summary>
    void FixedUpdate()
    {
        if ((locatedScrap) || (timer > 0f))
        {
            timer += Time.fixedDeltaTime;
            if (timer > animationSpeed)
            {
                timer = 0f;
            }

            if (locatedScrap)
            {
                line.SetPosition(1, locatedScrap.transform.position);
                line.SetPosition(0, transform.position);

                Highscore.AddScore(scrap.TakeScrap(transferSpeed * Time.fixedDeltaTime, timer == 0f));
            }

            material.mainTextureOffset = new Vector2(-1f + (2f * timer / animationSpeed), 0f);
        }
    }
Exemple #29
0
    private void LoadHighscores()
    {
        for (int i = 0; i < _highscoreListLength; i++)
        {
            string key = _highscore_key + i;

            var hs = new Highscore();
            if (PlayerPrefs.HasKey(key))
            {
                JsonUtility.FromJsonOverwrite(PlayerPrefs.GetString(key), hs);
            }
            else
            {
                PlayerPrefs.SetString(key, JsonUtility.ToJson(hs));
            }

            _highscores.Add(hs);
        }

        PlayerPrefs.Save();
    }
        /// <summary>
        /// Initializes the <see cref="Gamestate"/>.
        /// </summary>
        public override void Initialize()
        {
            _TextFont  = Manager.Game.Content.LoadBitmapFont("Font");
            _TitleFont = Manager.Game.Content.LoadBitmapFont("TitleFont");
            _Batch     = Manager.Game.Batch;

            // New highscore?
            for (int i = 0; i < Gamedata.MaxHighscoreCount; i++)
            {
                Highscore highscore = Manager.Game.Data.Highscores[i];
                if (Score > highscore.Score)
                {
                    highscore.Name  = "AAA";
                    highscore.Score = Score;
                    highscore.Level = Level;
                    highscore.Date  = DateTime.Now;
                    _NewHighscore   = i;
                    break;
                }
            }
        }
Exemple #31
0
    void FormatHighscores(string textStream)
    {
        string[] entries = textStream.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
        highscoresList = new Highscore[entries.Length];
        for (int i = 0; i < entries.Length; i++)
        {
            string[] entryInfo = entries[i].Split(new char[] { '|' });
            string   username  = entryInfo[0];
            int      score     = int.Parse(entryInfo[1]);
            highscoresList[i] = new Highscore(username, score);
            if (highscoresList[i].username == MainMenu.username)
            {
                playerPlace = i + 1;
            }
//			Debug.Log(highscoresList[i].username + ": " + highscoresList[i].score);
        }
        if (playerPlace == -1)
        {
            playerPlace = highscoresList.Length + 1;
        }
    }
    public void LoadHighscore()
    {
        if (File.Exists(Application.persistentDataPath + "/highscore.dat"))
        {
            print("Loading highscore.dat from: " + Application.persistentDataPath);
            BinaryFormatter bf   = new BinaryFormatter();
            FileStream      file = File.Open(Application.persistentDataPath + "/highscore.dat", FileMode.Open);

            Highscore hs = (Highscore)bf.Deserialize(file);

            file.Close();

            highscore = hs.highscore;
            print("Current Highscore: " + highscore);
        }
        else
        {
            print("highscore.dat not found...");
            SaveHighscore();
        }
    }
    //------------------------------------ Add new Highscore -----------------------------------

    public void addHighscore(string na, string dif, int str, int sco)
    {
        string name       = na;
        string difficulty = dif;
        int    winStreak  = str;
        int    score      = sco;

        if (HighscoreList.Exists(x => x.name == name) == true)                         // if the name already exists in the Highscore List:
        {
            Highscore oldScore = HighscoreList.Find(x => x.name.Contains(name));
            if (oldScore.score < score)                                                // and the old score is less than the new score
            {
                HighscoreList.Remove(oldScore);                                        // delete old Highscore
                HighscoreList.Add(new Highscore(name, difficulty, winStreak, score));  // and add a new one
            }
        }
        else                                                                           // if the name does not already exist:
        {
            HighscoreList.Add(new Highscore(name, difficulty, winStreak, score));      // add a new Highscore
        }
    }
 public void UpdateSingle()
 {
     AzureUnityServices.Instance.SelectByID <Highscore>("bbd01bc4-52db-407d-83a4-d8b5422e300f", selectResponse =>
     {
         if (selectResponse.Status == CallBackResult.Success)
         {
             Highscore hs = selectResponse.Result;
             hs.score    += 1;
             AzureUnityServices.Instance.UpdateObject(hs, updateResponse =>
             {
                 if (updateResponse.Status == CallBackResult.Success)
                 {
                     string msg = "object with id " + updateResponse.Result.id + " was updated";
                     Debug.Log(msg);
                     StatusText.text = msg;
                 }
             });
         }
     });
     StatusText.text = "Loading...";
 }
 public void DeleteByID()
 {
     AzureUnityServices.Instance.SelectByID <Highscore>("bbd01bc4-52db-407d-83a4-d8b5422e300f", selectResponse =>
     {
         if (selectResponse.Status == CallBackResult.Success)
         {
             Highscore hs = selectResponse.Result;
             AzureUnityServices.Instance.DeleteByID <Highscore>(hs.id, deleteResponse =>
             {
                 if (deleteResponse.Status == CallBackResult.Success)
                 {
                     string msg = "successfully deleted ID = " + hs.id;
                     Debug.Log(msg);
                     StatusText.text = msg;
                 }
             }
                                                                );
         }
     });
     StatusText.text = "Loading...";
 }
    // Gets executed by the respective button in the menu bar UI.
    public void OnHighscoreButtonPressed()
    {
        highscoreCanvas.SetActive(!highscoreCanvas.activeSelf);

        if (highscoreCanvas.activeSelf)
        {
            if (!highscoresAreLoaded)
            {
                Load();
            }

            for (int i = 0; i < highscores.Count; i++)
            {
                Highscore highscore = highscores[i];
                if (highscore != null)
                {
                    highscoreDisplays[i].Fill(highscore);
                }
            }
        }
    }
Exemple #37
0
        public static void Update()
        {
            Collision.Update();
            Pause.Update();

            // Start Menu
            if (GAME_SETTINGS.Status == GAME_SETTINGS.Scene.Start)
            {
                Objects.menu.Update();
            }

            // Settings menu
            if (GAME_SETTINGS.Status == GAME_SETTINGS.Scene.Settings)
            {
                Objects.settings.Update();
            }


            // Map select
            else if (GAME_SETTINGS.Status == GAME_SETTINGS.Scene.Maps)
            {
                Objects.maps.Update();
            }

            // In Game
            else if (GAME_SETTINGS.Status == GAME_SETTINGS.Scene.InGame)
            {
                // statics
                Shoot.Update();
                Zombie_manager.Update();
                Shops.Update();
                Highscore.Update();

                // Objects
                Objects.bullets.Update();
                Objects.player.Update();
                Objects.weapon.Update();
            }
            Objects.camera.UpdateCamera(Objects.View);
        }
Exemple #38
0
    private void Awake()
    {
        entryContainer = GameObject.Find("HighscoresEntrysContainer").transform;

        entryTemplate = entryContainer.Find("HighscoresEntryTemplate");

        entryTemplate.gameObject.SetActive(false);

        if (PlayerPrefs.HasKey("highscores"))
        {
            string     jsonString = PlayerPrefs.GetString("highscores");
            Highscores highscores = JsonUtility.FromJson <Highscores>(jsonString);

            //Sortiert die Liste
            for (int i = 0; i < highscores.highscoreList.Count; i++)
            {
                for (int j = i + 1; j < highscores.highscoreList.Count; j++)
                {
                    if (highscores.highscoreList[j].score > highscores.highscoreList[i].score)
                    {
                        //Tauschen
                        Highscore temp = highscores.highscoreList[i];
                        highscores.highscoreList[i] = highscores.highscoreList[j];
                        highscores.highscoreList[j] = temp;
                    }
                }
            }

            highscoreTransformList = new List <Transform>();
            int anzEntrys = 10;
            if (highscores.highscoreList.Count < anzEntrys)
            {
                anzEntrys = highscores.highscoreList.Count;
            }
            for (int i = 0; i < anzEntrys; i++)
            {
                CreateHighscoreEntryTransform(highscores.highscoreList[i], entryContainer, highscoreTransformList);
            }
        }
    }
Exemple #39
0
    public void OnSingleScoreDownloaded(Highscore singleHighscore, bool isPrevious)
    {
        ResetColors();
        if (isPrevious)
        {
            previousHighscore      = singleHighscore;
            previousHighscoreScore = previousHighscore.score;
        }
        else
        {
            newHighscore      = singleHighscore;
            newHighscoreScore = newHighscore.score;

            if (!usernameExists)
            {
                ShowNewBest();
            }
            else // if username DOES exist
            {
                if (newHighscore.score > previousHighscore.score)
                {
                    ShowNewBest();
                }
                else if (scoreThisRun == previousHighscore.score)
                {
                    ShowTiedBest();
                }
                else if (scoreThisRun < previousHighscore.score)
                {
                    ShowOldBest();
                }
                else
                {
                    Debug.LogWarning("Invalid score comparrison state reached!");
                    Debug.LogWarning("newHighscore: " + newHighscore.score + "\n" + "previousHighscore: " + previousHighscore.score + "\n" + "scoreThisRun: " + scoreThisRun);;
                }
            }
        }
    }
Exemple #40
0
        public async Task <ActionResult <Highscore> > PostHighscore(Highscore highscore)
        {
            // if list is full, check if the score is bigger than one already in the highscore list
            // add directly if list has less than 10 entries
            if (_context.HighScores.Count() >= 10)
            {
                var lastHighscore = _context.HighScores.OrderByDescending(h => h.Score).Last();
                if (lastHighscore.Score < highscore.Score)
                {
                    _context.HighScores.Remove(lastHighscore);
                }
                else
                {
                    return(BadRequest("This score is not a highscore"));
                }
            }

            _context.HighScores.Add(highscore);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetHighScore", new { id = highscore.HighScoreId }, highscore));
        }
Exemple #41
0
    public static async void EndGame()
    {
        SceneManager.LoadScene(mainMenu);

        int score = DataController.GetCurrentScore();

        if (PlayerPrefs.GetInt("highScore") < score)
        {
            PlayerPrefs.SetInt("highScore", score);
            string id = PlayerPrefs.GetString("_id");
            if (id != null && id.Length > 0)
            {
                Highscore highscore = await Highscores.Update(id, score);

                if (highscore != null)
                {
                    PlayerPrefs.SetInt("rank", highscore.rank);
                }
            }
        }
        DataController.Init();
    }
        public void EndGame()
        {
            // Stop the game timer
            timer.Stop();

            // Get previous highscores
            Highscore highscore = Highscore.ReadHighScores();

            // Update highscores
            foreach (ClientHandler client in clients)
            {
                highscore.AddHighScore(GetSnake(client.Id).Body.Count, client.Name);
            }
            highscore.WriteHighScores();

            // Send Endpacket and highscores
            Broadcast(TcpProtocol.EndSend());
            foreach (ClientHandler client in clients)
            {
                client.Write(TcpProtocol.HighscoreSend(highscore));
            }
        }
Exemple #43
0
    void renderHighscores()
    {
        if (GUI.needLoadHighscores)
        {
            switch (GUI.highscoreType)
            {
            case HighscoreType.LOCAL:
                highscores = Highscore.getLocalHighscores();

                localHighscoresButtonText.color  = GUI.black;
                onlineHighscoresButtonText.color = GUI.inactiveColor;

                break;

            case HighscoreType.ONLINE:
                highscores = Highscore.getOnlineHighscores();

                onlineHighscoresButtonText.color = GUI.black;
                localHighscoresButtonText.color  = GUI.inactiveColor;

                break;
            }

            highscoreContent.DetachChildren();

            foreach (KeyValuePair <float, string> kvp in highscores)
            {
                GameObject _highscoreEntry = (GameObject)Instantiate(highscoreEntry);

                _highscoreEntry.transform.SetParent(highscoreContent);

                Text[] texts = _highscoreEntry.GetComponentsInChildren <Text>();
                texts[0].text = kvp.Value;
                texts[1].text = kvp.Key.ToString("0.00");
            }

            GUI.needLoadHighscores = false;
        }
    }
Exemple #44
0
    /// <summary>
    /// Sorting the highscores for display
    /// </summary>
    private void SortingHighScore()
    {
        for (int i = 0; i < tempIntList.Count; i++)
        {
            for (int j = i + 1; j < tempIntList.Count; j++)
            {
                if (tempIntList[j] > tempIntList[i])
                {
                    int tempscore = tempIntList[i];
                    tempIntList[i] = tempIntList[j];
                    tempIntList[j] = tempscore;
                }
            }
        }

        for (int i = 0; i < tempIntList.Count; i++)
        {
            Highscore hscore = new Highscore();
            hscore.score = tempIntList[i];
            highscoreList.Add(hscore);
        }
    }
    private IEnumerator UpdateHighscoresRoutine()
    {
        Debug.Log("Loading Scores");

        WWW highscoreGet = new WWW(m_GetHighscoreURL);

        yield return(highscoreGet);

        if (highscoreGet.error != null)
        {
            Debug.Log("There was an error getting the highscores: " + highscoreGet.error);
        }
        else
        {
            //Split the string (comma separated)
            char[]   delimiterChars = { ',' };
            string[] words          = highscoreGet.text.Split(delimiterChars);

            m_Highscores.Clear();
            for (int i = 0; i < words.Length; i += 2)
            {
                if (String.IsNullOrEmpty(words[i]))
                {
                    continue;
                }

                Highscore highscore = new Highscore();
                highscore.name = words[i];
                bool success = int.TryParse(words[i + 1], out highscore.score);

                m_Highscores.Add(highscore);
            }

            if (m_HighscoreUpdatedEvent != null)
            {
                m_HighscoreUpdatedEvent();
            }
        }
    }
Exemple #46
0
    /// <summary>
    /// Save highscore. Will overwrite previous if it exists.
    /// </summary>
    /// <param name="level">Level identifier (<c>size.seed</c>).</param>
    /// <param name="seconds">Highscore time</param>
    public void Save(string level, int seconds)
    {
        Highscore highscore = new Highscore(level, seconds);

        List <Highscore> list = LoadAll();
        int index             = list.FindIndex((hs) => hs.Level == level);

        if (index > -1)
        {
            list[index] = highscore;
        }
        else
        {
            list.Add(highscore);
        }

        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Open(filePath, FileMode.OpenOrCreate);

        bf.Serialize(file, list);
        file.Close();
    }
Exemple #47
0
        public static void insert(Highscore hs)
        {
            MySqlConnection con = DBConnection.getConnection();

            if (con == null)
            {
                throw new Exception("Conexiunea la baza de date nu s-a realizat.");
            }

            MySqlCommand cmd = con.CreateCommand();

            cmd.CommandText = "INSERT INTO highscores(gamer, highscore) VALUES(@gamer, @hscore)";
            cmd.Parameters.AddWithValue("@gamer", hs.Gamer);
            cmd.Parameters.AddWithValue("@hscore", hs.Hscore);

            if (cmd.ExecuteNonQuery() != 1)
            {
                throw new Exception("Inserarea nu s-a putut face.");
            }

            con.Close();
        }
        public async void AddToMuchScores()
        {
            Highscore highscore;

            for (var i = 1; i < 15; i++)
            {
                highscore       = new Highscore();
                highscore.User  = "******" + i;
                highscore.Score = 100 + i;

                Captcha captcha = new Captcha();
                captcha.captcha   = "6Lej2OUUAAAAAKWBrOTPfgy_2Y_5GfICOJ_WEOsE";
                captcha.Highscore = highscore;

                await _controller.PostHighscore(captcha);
            }

            Assert.Equal(10, _controller.Get().Count());

            _context.HighscoreLists.RemoveRange(_controller.Get());
            await _context.SaveChangesAsync();
        }
Exemple #49
0
    public void UpdateHighscoresFile(string user, string levelname, int scr)
    {
        HighscoreList hsList = Load <HighscoreList> (HighscoresPath);
        Highscore     temp   = new Highscore();

        hsList.highscores.Add(new Highscore()
        {
            User      = user,
            levelName = levelname,
            score     = scr
        });


        hsList.highscores.OrderByDescending(u => u.score);

        Highscores = hsList;
        using (StreamWriter sw = new StreamWriter(HighscoresPath))
        {
            string json = JsonUtility.ToJson(Highscores, true);
            sw.Write(json);
        }
    }
Exemple #50
0
    void Start()
    {
        //Creating our loader object
        loader = new HighscoreLoader();

        //Getting list of high scores
        highScores = loader.LoadHighScores();

        Scene currentScene = SceneManager.GetActiveScene();

        //Depending on scene, call appropriate function
        if (currentScene.name == "High Scores")
        {
            DisplayHighScores();
        }
        else if (currentScene.name == "New High Score")
        {
            newHighScorePrefab = GameObject.FindGameObjectWithTag("New High Score");
            newHighScore       = new Highscore();
            newHighScore.score = newHighScorePrefab.GetComponent <NewHighScore>().newHighScore;
        }
    }
 public void CallUpdateForAndroid()
 {
     EasyAPIs.Instance.CallAPIMultiple <Highscore, Highscore>("UpdateHighScore", HttpMethod.Post, response =>
     {
         if (response.Status == CallBackResult.Success)
         {
             Highscore obj = response.Result[0];
             string result = string.Format("new highscore is {0} and name is {1}", obj.score, obj.playername);
             Debug.Log(result);
             StatusText.text = result;
         }
         else
         {
             ShowError(response.Exception.Message);
         }
     },
                                                              new Highscore()
     {
         id = "ecca86cb-8e35-47ac-8eef-74dc2ef87faa", playername = "Dimitris", score = 33
     });
     StatusText.text = "Loading...";
 }
    public void showHighscoreFromGameover()
    {
        // Disable enter
        _enabledEnterRestart = false;

        // Enable ui
        UiGameover.SetActive(false);
        UiHighscoreFromGameover.SetActive(true);

        // Update highscore
        List <NameScoreData> data = new List <NameScoreData>();

        StartCoroutine(Database.GetHighscoreData(data));

        // Pass to highscore to wait for coroutine finishing
        Highscore highscore = UiHighscoreFromGameover.GetComponent <Highscore>();

        if (highscore && highscore.isActiveAndEnabled)
        {
            highscore.StartCoroutine(highscore.UpdateScores(data));
        }
    }
 private void pictureBox1_Click(object sender, EventArgs e)
 {
     Highscore form4 = new Highscore();
     form4.Show();
     this.Hide();
     MenuSound.Stop();
 }
 /// <summary>
 /// Handler to get selected row item
 /// </summary>
 public void OnSelectedRow(Button button)
 {
     int index = Convert.ToInt32 (button.name);
     //Debug.Log("Selected index:" + index);
     if (index >= _scores.Count) {
         return;
     }
     Highscore score = _scores [index];
     Debug.Log ("Selected:" + score.ToString());
     _score = score; // update editor with selected item
 }
 /// <summary>
 /// Update UI with data model 
 /// </summary>
 private void DisplayScore(Highscore highscore)
 {
     InputField name = GameObject.Find("InputName").GetComponent<InputField> ();
     InputField score = GameObject.Find("InputScore").GetComponent<InputField> ();
     Text id = GameObject.Find("Id").GetComponent<Text> ();
     name.text = highscore.username;
     score.text = highscore.score.ToString ();
     id.text = highscore.id;
     UpdateUI ();
 }
 /// <summary>
 /// Create data model from UI
 /// </summary>
 private Highscore GetScore()
 {
     string name = GameObject.Find("InputName").GetComponent<InputField> ().text;
     string score = GameObject.Find("InputScore").GetComponent<InputField> ().text;
     string id = GameObject.Find("Id").GetComponent<Text> ().text;
     Highscore highscore = new Highscore();
     highscore.username = name;
     if (!String.IsNullOrEmpty (score)) {
         highscore.score = Convert.ToInt32 (score);
     }
     if (!String.IsNullOrEmpty (id)) {
         highscore.id = id;
         Debug.Log ("Existing Id:" + id);
     }
     return highscore;
 }
 /// <summary>
 /// Validate data before sending
 /// </summary>
 private bool Validate(Highscore highscore)
 {
     bool isUsernameValid=true, isScoreValid=true;
     // Validate username
     if (String.IsNullOrEmpty (highscore.username)) {
         isUsernameValid = false;
         Debug.Log ("Error, player username required");
     }
     // Validate score
     if ( !(highscore.score > 0) )
     {
         isScoreValid = false;
         Debug.Log ("Error, player score should be greater than 0");
     }
     UpdateText ("Player", isUsernameValid);
     UpdateText ("Score", isScoreValid);
     return (isUsernameValid && isScoreValid);
 }
 // Update is called once per frame
 void Update()
 {
     // Only update table when there is new data
     if (HasNewData) {
         Debug.Log ("Refresh Table Data");
         SetInteractableScrollbars (false);
         _tableView.ReloadData ();
         SetInteractableScrollbars (true);
         HasNewData = false;
     }
     // Display new score details
     if (_score != null) {
         Debug.Log ("Show score:" + _score.ToString());
         DisplayScore (_score);
         _score = null;
     }
     // Display modal where there is a new message
     if (_message != null) {
         Debug.Log ("Show message:" + _message.message);
         _modalAlert.Show(_message.message, _message.title);
         _message = null;
     }
 }
 private void OnLookupCompleted(IRestResponse<Highscore> response)
 {
     Debug.Log("OnLookupItemCompleted: " + response.Content );
     if (response.StatusCode == HttpStatusCode.OK)
     {
         Highscore item = response.Data;
         _score = item;
         // show message with some details
         string message = string.Format ("Scored {0} points on {1}", _score.score, _score.createdAt);
         _message = Message.Create(message, _score.username);
     }
     else
     {
         ResponseError err = JsonReader.Deserialize<ResponseError>(response.Content);
         Debug.Log("Lookup Error Status:" + response.StatusCode + " Code:" + err.code.ToString() + " " + err.error);
     }
 }
 private void OnInsertCompleted(IRestResponse<Highscore> response)
 {
     if (response.StatusCode == HttpStatusCode.Created)
     {
         Debug.Log( "OnInsertItemCompleted: " + response.Data );
         Highscore item = response.Data; // if successful the item will have an 'id' property value
         _score = item;
     }
     else
     {
         Debug.Log("Insert Error Status:" + response.StatusCode + " Uri: "+response.ResponseUri );
     }
 }