package dev.kske.minesweeper;
import static dev.kske.minesweeper.BoardConfig.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
/**
* Project: Minesweeper
* File: ScoreManager.java
* Created: 15.05.2019
* Author: Kai S. K. Engelbart
*/
public class ScoreManager {
private List easy, medium, hard;
private final String scoresFile = "scores.ser";
public ScoreManager() {
easy = new ArrayList<>();
medium = new ArrayList<>();
hard = new ArrayList<>();
}
public void addScore(GameOverEvent evt) {
// Determine board config
BoardConfig config = evt.getBoardConfig();
if (config == EASY && (easy.size() < 10 || easy.get(9).getDuration() > evt.getDuration())) {
String name = JOptionPane.showInputDialog("Please enter your name");
Score score = new Score(name, evt.getDuration(), new Date());
sortInsert(score, easy);
} else
if (
config == MEDIUM
&& (medium.size() < 10 || medium.get(9).getDuration() > evt.getDuration())
) {
String name = JOptionPane.showInputDialog("Please enter your name");
Score score = new Score(name, evt.getDuration(), new Date());
sortInsert(score, medium);
} else
if (
config == HARD
&& (hard.size() < 10 || hard.get(9).getDuration() > evt.getDuration())
) {
String name = JOptionPane.showInputDialog("Please enter your name");
Score score = new Score(name, evt.getDuration(), new Date());
sortInsert(score, hard);
}
}
private void sortInsert(Score score, List list) {
for (int i = 0; i < list.size(); i++)
if (list.get(i).getDuration() > score.getDuration()) {
list.add(i, score);
return;
}
list.add(score);
}
public void displayEasy() {
new ScoreDialog(easy, "Easy").setVisible(true);
}
public void displayMedium() {
new ScoreDialog(medium, "Medium").setVisible(true);
}
public void displayHard() {
new ScoreDialog(hard, "Hard").setVisible(true);
}
@SuppressWarnings("unchecked")
public void loadScores() {
try (var in = new ObjectInputStream(new FileInputStream(scoresFile))) {
Object obj = in.readObject();
if (obj instanceof ArrayList>)
easy = (ArrayList) obj;
obj = in.readObject();
if (obj instanceof ArrayList>)
medium = (ArrayList) obj;
obj = in.readObject();
if (obj instanceof ArrayList>)
hard = (ArrayList) obj;
else
throw new IOException("Serialized object has the wrong class.");
} catch (FileNotFoundException ex) {} catch (IOException | ClassNotFoundException ex) {
JOptionPane.showMessageDialog(
null,
"The score file seems to be corrupted. It will be replaced when closing the game.",
"File error",
JOptionPane.ERROR_MESSAGE
);
}
}
public void saveScores() {
try (var out = new ObjectOutputStream(new FileOutputStream(scoresFile))) {
out.writeObject(easy);
out.writeObject(medium);
out.writeObject(hard);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}