libGDX: Using preferences for highscore

前端 未结 1 1892
北海茫月
北海茫月 2021-01-27 14:54

I know I have asked this question so similar before but I get there no more answer ... I would like, as soon as I lost in my game, my HighScore displayed. Here is the code:

相关标签:
1条回答
  • 2021-01-27 15:25

    First you get the object:

    Preferences preferences = Gdx.app.getPreferences("My preferences");
    

    Then, when you lose in your game, you get the value. I usually check if I lose in the render method with a boolean. In this case you compare your highscore with your current score:

    if(IsGameFinished)
    {
        int highscore = preferences.getInteger("High score",0);
        if(highscore>=yourCurrentScore)
        {
              // display highscore
        }
        else
        {
              // display yourCurrentScore
             preferences.putInteger("High score", yourCurrentScore);
             preferences.flush();
        }
    }
    

    Furthermore in your code there is an error:

    protected Preferences HighScore () {
    
    if (score > highscore) { 
        prefs.putInteger("highscore", score); 
        prefs.flush(); // YOU SHOULD FLUSH BEFORE!
        this.highscore = prefs.getInteger("highscore", 0);
    }
    return prefs;
    }
    

    And, why do you return the Preferences? Returning your highscore as an int should be better.

    0 讨论(0)
提交回复
热议问题