libGDX:使用首选项获得高分 [英] libGDX: Using preferences for highscore
问题描述
我知道我之前曾经问过这个问题,但是我没有其他答案……我想,一旦我输了游戏,我的HighScore就会显示出来.这是代码:
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:
protected Preferences HighScore () {
if (score > highscore) {
prefs.putInteger("highscore", score);
this.highscore = prefs.getInteger("highscore", 0);
prefs.flush();
}
return prefs;
}
但是,如果我运行我的应用程序,则只会显示此错误:
But if I run my application, only this error is displayed:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at de.firstdemo.game.states.PlayState.HighScore(PlayState.java:641)
at de.firstdemo.game.states.PlayState.render(PlayState.java:601)
at de.firstdemo.game.states.GameStateManager.render(GameStateManager.java:50)
at de.firstdemo.game.RiskyDemo.render(RiskyDemo.java:37)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
我在网上看了却找不到任何解决方案...
I looked in the web but couldn't find any solution...
感谢您的回答! :)
推荐答案
首先获得对象:
Preferences preferences = Gdx.app.getPreferences("My preferences");
然后,当您输掉比赛时,便会获得价值.我通常会检查是否在布尔值的render方法中迷失了方向.在这种情况下,您可以将您的高分与当前分数进行比较:
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.
这篇关于libGDX:使用首选项获得高分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!