-1

I'm creating a game that needs to keep track of the highscores as different people play it. I'd like it to be able to organize itself, so that the top player stays at the top, and the file isn't always overwritten when a new score is added. I need at least 6 scores saved at once.

Here is my highscore writing method:

public void high_score() throws IOException {
    Writer output = null;
    String text = "Highscore:" + replay_score;
    File file = new File("C:\\Users\\Liam\\Desktop\\BOMB GAME\\Bomb_Highscores.txt");
    output = new BufferedWriter(new FileWriter(file));
    output.write(text);
    output.close();
    System.out.println("Your file has been written"); 
}

Where replay_score is the number of times you've replayed the game until you've scored high enough to beat it.

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
Hoberfinkle
  • 35
  • 1
  • 7
  • 2
    Either sort the contents of the file before you write it or after you read it... – MadProgrammer Oct 16 '13 at 04:57
  • Try `new FileWriter(file, true)` to append instead of overwriting. – Zong Oct 16 '13 at 04:59
  • So what is it that you need help with? – chrylis -cautiouslyoptimistic- Oct 16 '13 at 05:03
  • As I had mentioned, I need it to organize all the different scores from the top player to the bottom player, without over writing the file. Zong Zheng Li helped out with the new FileWriter(file, true), but I still need it to be organized from top score to last score and everything in between. – Hoberfinkle Oct 16 '13 at 05:13
  • MadProgrammer has already stated what must be done. You will have to sort the scores in memory (aka use an array or list of scores) as there is no easy way to enforce the contents of a text file to be ordered by some arbitrary metric. – Zong Oct 16 '13 at 05:25
  • Do not sort during the writing. Sort it when you are reading it. – Rudy Oct 16 '13 at 05:58

1 Answers1

0

You should maintain SortedSet, but it is not an easy way in the means of coding.

Lets say you have a class User

class User implements Comparable<User> {
    //implement getter and setter of score and maintain this property
    public int compareTo(User o) {
        return o.getScore() - this.getScore();
    }
}

In your method where you want to add the score to file you should read the existing file line by line, create User object and populate SortedSet. Now add new score to this Set. Once you added a loop through this set overwrite this file. Within this loop you can also maintain the maximum number of scores you want to write.

Edeph
  • 732
  • 2
  • 12
  • 29
user2880879
  • 297
  • 1
  • 3
  • 1
    `return Integer.compare(o.getScore(), this.getScore())` would be better to avoid overflows and corner cases. – Zong Oct 16 '13 at 13:13