我有以下任务:
我们希望保持以前的最高得分 游戏。该分数将保存在文件中,并将在 如果当前得分高于最高得分,则结束每个游戏 到目前为止。
最高分数文件名应该是高分数,并且应该位于 在运行游戏的文件夹中。此文件将仅包含一个 包含以下内容的单行:迄今为止的最高分数是: XXX。
如果这是我们第一次运行游戏,则需要创建文件 用当前分数。下次运行游戏时, 您需要将新分数与存储在 文件并仅在达到最高分数时才更新文件。
我的代码是:
public class ScorePersistence {
private int score;
private File highscores;
private int currentHighScore;
private ScorePersistence(int finalScore) {
this.score = finalScore;
}
public void ShouldUpdate() {
File highScores = new File("highscores.txt");
if (highScores.exists()) {
if (currentHighScore < the score that inside of highscores.txt){
currentHighScore = the score that inside of highscores.txt
highscores.write("The highest score so far is: "+ the score that inside of highscores.txt)
}
else{
break; //means the currentHighScore is bigger than there is no reason to update the file
}
}
else {
//means that there is no file yet, which means this is the first time we run the game on the computer.
currentHighScore = score;
highScore.write("The highest score so far is: "+ score).
}
}
}
我从负责运行关卡和游戏的班级获得了“ int finalScore”。
您怎么看?您如何看待,我应该从该文本文件中获取分数并将其与我从当前游戏中获得的“得分”进行比较吗?
谢谢。这是一个简单的离线游戏。砖块和击中它们的球。
这是在线游戏还是离线游戏?
[如果这是一款离线游戏,我认为在开始加载游戏时读取文本文件并将其保存在整个游戏的局部变量中就足够了。这样,您可以避免不必要的文件读取,并且只有在需要时才可以更新高分。
如果这是一个在线游戏,我需要更多信息。您如何处理服务器操作?我问这个问题是因为在这种情况下,您还应该处理文件锁定请求(多个用户试图同时读取/写入数据)。我建议为此目的使用数据库,而不是使用文本文件。