HitoriMitMaven/src/main/java/domain/HitoriBoardLoader.java

124 lines
4.3 KiB
Java

package domain;
import java.io.*;
import java.net.URL;
import java.util.*;
public class HitoriBoardLoader {
private Map<String, int[][]> availableBoards;
private Map<String, List<int[]>> solutions;
public HitoriBoardLoader() {
availableBoards = new HashMap<>();
solutions = new HashMap<>();
loadAllBoards();
}
private void loadAllBoards() {
try {
// Define all board file names
String[] boardFiles = {
"Hitori4x4_leicht.csv",
"Hitori5x5leicht.csv",
"Hitori8x8leicht.csv",
"Hitori8x8medium.csv",
"Hitori10x10medium.csv",
"Hitori15x15_medium.csv"
};
// Try to load each board
for (String fileName : boardFiles) {
try {
InputStream is = getClass().getResourceAsStream("/META-INF/" + fileName);
if (is == null) {
is = getClass().getResourceAsStream("/" + fileName);
}
if (is != null) {
loadBoard(fileName, is);
}
} catch (Exception e) {
System.out.println("Failed to load board: " + fileName);
e.printStackTrace();
}
}
if (availableBoards.isEmpty()) {
System.out.println("No board files found. Please ensure .csv files are in the resources folder.");
} else {
System.out.println("Successfully loaded " + availableBoards.size() + " boards.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadBoard(String fileName, InputStream inputStream) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
List<String> lines = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
// Find where the solution starts
int solutionIndex = -1;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains("//")) {
solutionIndex = i;
break;
}
}
// Parse the board
List<String[]> boardRows = new ArrayList<>();
for (int i = 0; i < (solutionIndex == -1 ? lines.size() : solutionIndex); i++) {
line = lines.get(i).trim();
if (!line.isEmpty()) {
boardRows.add(line.split(","));
}
}
if (!boardRows.isEmpty()) {
int rows = boardRows.size();
int cols = boardRows.get(0).length;
int[][] board = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
board[i][j] = Integer.parseInt(boardRows.get(i)[j].trim());
}
}
availableBoards.put(fileName, board);
// Parse the solution if available
List<int[]> solutionCoordinates = new ArrayList<>();
if (solutionIndex != -1) {
for (int i = solutionIndex + 1; i < lines.size(); i++) {
line = lines.get(i).trim();
if (!line.isEmpty() && !line.startsWith("//")) {
String[] coords = line.split(",");
solutionCoordinates.add(new int[]{
Integer.parseInt(coords[0].trim()) - 1,
Integer.parseInt(coords[1].trim()) - 1
});
}
}
solutions.put(fileName, solutionCoordinates);
}
}
}
}
public Set<String> getAvailableBoardNames() {
return availableBoards.keySet();
}
public int[][] getBoard(String boardName) {
return availableBoards.get(boardName);
}
public List<int[]> getSolution(String boardName) {
return solutions.get(boardName);
}
}