【发布时间】:2021-09-14 09:53:39
【问题描述】:
我使用首选项来保存值。它运行良好并保存了高分,但是当我重新打开游戏时,高分变为默认零
有没有办法让我重新打开应用程序时分数保持不变?
我只有一个扩展应用程序适配器的类,而我的偏好代码在渲染方法中是问题的原因吗?
这是我的代码 -
Override
public void render()
{
if (secondsLeft <= 0)
{
gameOver = true;
}
Gdx.gl.glClearColor(r, g, b, 0.5f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
if (!gameOver)
{
sadMusic.stop();
bgMusic.setVolume(0.4f);
bgMusic.setLooping(true);
bgMusic.play();
batch.draw(targetTexture, targetRect.x, targetRect.y, targetRect.width, targetRect.height);
font.draw(batch, "Time Left: " + secondsLeft, 250, Gdx.graphics.getHeight() - 60);
font.draw(batch, "Your Score: " + score, 210, 150);
if (Gdx.input.justTouched())
{
System.out.println(delay);
Vector2 touchPosition = new Vector2(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
Rectangle touchedRect = new Rectangle(touchPosition.x, touchPosition.y, 1, 1);
if (Intersector.overlaps(touchedRect, targetRect))
{
score++;
long id = tapSound.play(1.0f);
tapSound.setPitch(id, 0.1f);
tapSound.setLooping(id, false);
changeTargetPosition();
Gdx.gl.glClearColor(r, g, b, 0.5f);
}
}
pref= Gdx.app.getPreferences("highScore");
if (score >= highScore) {
pref.putInteger("High Score", score);
pref.flush();
}
highScore = pref.getInteger("High Score", 0);
}
else
{
bgMusic.stop();
sadMusic.setVolume(0.4f);
sadMusic.setLooping(true);
sadMusic.play();
Gdx.gl.glClearColor(1, 0, 0, 0.5f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
font.draw(batch, "Game over!", 240, Gdx.graphics.getHeight() - 60);
font.draw(batch, "Score was: " + score, 220, Gdx.graphics.getHeight() - 170);
font.draw(batch, "Tap To Restart", 220, Gdx.graphics.getHeight() - 709);
font.draw(batch, "High Score: " + highScore, 200, Gdx.graphics.getHeight() - 750);
/* using this so that usr wont click the screen bymistakenly
bcz when we were playing the game it kind of catches
the rythem, and hence needs some time to stop */
delay += Gdx.graphics.getDeltaTime();
if (delay >= 1f) {
if (Gdx.input.justTouched())
{
startGame();
}
}
}
batch.end();
}
【问题讨论】:
-
也许在你获取高分后检查分数是否大于高分?