如何修复Java游戏关闭后最高分重置为0的问题
修复方案
现有代码核心问题
- 程序启动阶段没有读取本地存储的最高分文件,
highScore变量被固定初始化为Nobody:0,导致每次重启默认最高分都是0 - 写文件使用追加模式,会累计存储所有历史高分记录,没有只保留当前最高值,后续读取时需要额外筛选最大值
具体修复步骤
1. 新增本地最高分读取逻辑
在游戏初始化阶段调用该方法,提前把历史最高分加载到highScore变量中:
// 程序启动时调用该方法加载历史最高分 public void loadHighScore() { File scoreFile = new File("highscore.dat"); // 文件不存在就保持默认的Nobody:0即可 if (!scoreFile.exists()) { return; } BufferedReader reader = null; int maxScore = 0; String maxScoreLine = "Nobody:0"; try { reader = new BufferedReader(new FileReader(scoreFile)); String line; // 遍历所有历史记录,找出最高分 while ((line = reader.readLine()) != null) { if (line.trim().isEmpty()) continue; int currentScore = Integer.parseInt(line.split(":")[1].trim()); if (currentScore > maxScore) { maxScore = currentScore; maxScoreLine = line; } } highScore = maxScoreLine; } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); } catch (Exception e) {} } }
2. 优化最高分校验&存储逻辑
把追加写改成覆盖写,避免无效历史记录堆积,后续读取效率更高:
private String highScore = "Nobody:0"; public void CheckHighScore() { int currentHigh = Integer.parseInt(highScore.split(":")[1]); if (score > currentHigh) { String name = JOptionPane.showInputDialog("你创造了新的最高分!请输入你的名字:"); highScore = name + ":" + score; File scoreFile = new File("highscore.dat"); if (!scoreFile.exists()) { try { scoreFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } BufferedWriter writer = null; try { // 第二个参数改成false代表覆盖写,只存最新的最高分 writer = new BufferedWriter(new FileWriter(scoreFile, false)); writer.write(this.highScore); writer.newLine(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (Exception e) { e.printStackTrace(); } } } }
3. 调整调用时序
确保游戏启动时先执行loadHighScore()加载历史最高分,游戏结束后再调用CheckHighScore()校验是否破纪录即可。
内容的提问来源于stack exchange,提问作者Trainer Chad
相关产品推荐
相关产品推荐

