HighScoreManager
This commit is contained in:
@ -18,7 +18,7 @@ public class GameStateManager {
|
||||
GameOverState gameOverState = new GameOverState(this, new HighScoreManager());
|
||||
states.put(GameStateType.PLAYING, new PlayingState(game, this, gameOverState));
|
||||
states.put(GameStateType.GAME_OVER, gameOverState);
|
||||
setState(GameStateType.GAME_OVER);
|
||||
setState(GameStateType.PLAYING);
|
||||
}
|
||||
|
||||
public void setState(GameStateType type) {
|
||||
|
||||
@ -1,7 +1,42 @@
|
||||
package se.urmo.game.state;
|
||||
|
||||
public class HighScoreManager {
|
||||
public void submit(int finalScore) {
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class HighScoreManager {
|
||||
private final Path file = Path.of("highscores.dat");
|
||||
private final int maxEntries = 10;
|
||||
private final List<Integer> scores = new ArrayList<>();
|
||||
|
||||
public HighScoreManager() { load(); }
|
||||
|
||||
public void submit(int score) {
|
||||
scores.add(score);
|
||||
scores.sort(Comparator.reverseOrder());
|
||||
if (scores.size() > maxEntries) scores.remove(scores.size() - 1);
|
||||
save();
|
||||
}
|
||||
|
||||
public List<Integer> top() { return List.copyOf(scores); }
|
||||
|
||||
private void load() {
|
||||
try {
|
||||
if (!Files.exists(file)) return;
|
||||
for (String line : Files.readAllLines(file)) {
|
||||
scores.add(Integer.parseInt(line.trim()));
|
||||
}
|
||||
scores.sort(Comparator.reverseOrder());
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
|
||||
private void save() {
|
||||
try {
|
||||
var lines = scores.stream().map(String::valueOf).toList();
|
||||
Files.write(file, lines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user