Highsocre manager für benutztung von Highscores eingefügt
parent
d1fcac31ca
commit
e832fc5f6f
|
@ -0,0 +1,75 @@
|
|||
package de.deversmann.domain;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class HighscoreManager {
|
||||
private final Map<String, List<HighscoreEntry>> highscoreMap;
|
||||
|
||||
public HighscoreManager() {
|
||||
highscoreMap = new HashMap<>();
|
||||
}
|
||||
|
||||
public void addHighscore(String spielfeld, String name, long zeit, int fehler) {
|
||||
HighscoreEntry entry = new HighscoreEntry(name, zeit, fehler);
|
||||
highscoreMap.computeIfAbsent(spielfeld, k -> new ArrayList<>()).add(entry);
|
||||
saveHighscores();
|
||||
}
|
||||
|
||||
public List<HighscoreEntry> getHighscores(String spielfeld) {
|
||||
return highscoreMap.getOrDefault(spielfeld, new ArrayList<>());
|
||||
}
|
||||
|
||||
public double getDurchschnittszeit(String spielfeld) {
|
||||
List<HighscoreEntry> highscores = getHighscores(spielfeld);
|
||||
return highscores.stream().mapToLong(HighscoreEntry::getZeit).average().orElse(0);
|
||||
}
|
||||
|
||||
private void saveHighscores() {
|
||||
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("highscores.dat"))) {
|
||||
oos.writeObject(highscoreMap);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Fehler beim Speichern der Highscores: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void loadHighscores() {
|
||||
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("highscores.dat"))) {
|
||||
Map<String, List<HighscoreEntry>> loadedMap = (Map<String, List<HighscoreEntry>>) ois.readObject();
|
||||
highscoreMap.clear();
|
||||
highscoreMap.putAll(loadedMap);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
System.err.println("Fehler beim Laden der Highscores: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static class HighscoreEntry implements Serializable {
|
||||
private final String name;
|
||||
private final long zeit;
|
||||
private final int fehler;
|
||||
|
||||
public HighscoreEntry(String name, long zeit, int fehler) {
|
||||
this.name = name;
|
||||
this.zeit = zeit;
|
||||
this.fehler = fehler;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public long getZeit() {
|
||||
return zeit;
|
||||
}
|
||||
|
||||
public int getFehler() {
|
||||
return fehler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + ": " + zeit + "ms, Fehler: " + fehler;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue