![](/img/trans.png)
[英]Adding highscores to java game - From console to JPanel - Saving highscore in encrypted text file
[英]Getting highscore for snake game from .txt file
private int score = 0;
private int highScore = 0;
private void gameOver(Graphics g) {
try{
PrintWriter writer = new PrintWriter(new FileWriter("C:\\Users\\Videvik\\workspace\\madu\\logi1.txt", true));
writer.println(score);
writer.close();
} catch(Exception ex){ex.printStackTrace();}//creates .txt file
File file = new File("logi1.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) // read the score file line by line
{
try {
int score2 = Integer.parseInt(line.trim()); // parse each line as an int
if (score2 > highScore) // and keep track of the largest
{
highScore = score;
}
} catch (NumberFormatException e1) {
// ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR reading scores from file");
String msg = "Game over!";//works
String msg2 = "Points: "+score;//works
String msg3 = "MaxPoints: "+highScore;//does not work
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.red);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
g.drawString(msg2, (B_WIDTH - metr.stringWidth(msg2)) / 4, B_HEIGHT / 4);
g.drawString(msg3, (B_WIDTH - metr.stringWidth(msg3)) / 6, B_HEIGHT / 6);
}
}
好吧,我的問題是我無法從.txt文件在屏幕上打印出最高分。 第一個程序創建一個.txt文件,其中保存了所有樂譜(有效)。 之后的第二個函數應該從那里找到最高分數並將其繪制出來(不起作用)。(它繪制出“ Points”和“ Game over!”。)Eclipse在代碼中不顯示任何錯誤。 我做錯了什么? 我必須在下周三解決這個問題,否則我的考試不會通過
我認為潛在的錯誤是這兩個:
一種途徑是絕對途徑,另一種途徑是相對途徑。 FileWriter接受File作為參數,那么為什么不同時為讀取器和寫入器使用“文件”? 這樣,您可以確保它們指向同一位置。
還要檢查您的Highscore是否確實在某處更新。 它也永遠不會顯示0作為高分,否則您將需要更改:
if(highscore2 > highscore)
至
if(highscore2 >= highscore)
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.