addo save in json files
All checks were successful
Linux arm64 / Build (push) Successful in 40s

This commit is contained in:
Janet-Doe
2025-01-28 18:58:26 +01:00
parent 4208e7058f
commit a6dea76785
4 changed files with 47 additions and 18 deletions

View File

@@ -1,5 +1,6 @@
package sudoku.io;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@@ -14,7 +15,7 @@ import sudoku.structure.SudokuFactory;
public class SudokuSerializer {
public static String serializeSudoku(final MultiDoku multidoku) {
public static JSONObject serializeSudoku(final MultiDoku multidoku) {
List<Cell> cellIds = new ArrayList<>();
List<Block> blockIds = new ArrayList<>();
@@ -39,11 +40,11 @@ public class SudokuSerializer {
}
int blockID = blockIds.indexOf(block);
int symboleIndex = cell.getSymbolIndex();
int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject();
cellJsonObject.put("blockID", blockID);
cellJsonObject.put("symboleIndex", symboleIndex);
cellJsonObject.put("symbolIndex", symbolIndex);
if (!cell.isMutable()) {
cellJsonObject.put("immutable", true);
}
@@ -96,11 +97,38 @@ public class SudokuSerializer {
jsonRoot.put("multidoku", jsonSudokus);
jsonRoot.put("cells", jsonCells);
jsonRoot.put("blocks", jsonBlocks);
return jsonRoot.toString();
return jsonRoot;
}
public static MultiDoku deserializeSudoku(final String data) {
JSONObject jsonObject = new JSONObject(data);
public static void saveMultiDoku(final MultiDoku doku) {
JSONObject jsonRoot = serializeSudoku(doku);
File f = new File("save", "save.json");
InputStream is = null;
int i = 1;
while (f.exists()) {
String newName = "save-" + i + ".json";
f = new File("save", newName);
i++;
}
try (FileWriter file = new FileWriter(f)) {
file.write(jsonRoot.toString(3));
//file.flush();
} catch (IOException e) {
e.fillInStackTrace();
}
}
public static MultiDoku deserializeSudoku(final String json) {
JSONObject jsonRoot = new JSONObject(json);
return deserializeSudoku(jsonRoot);
}
public static MultiDoku deserializeSudoku(final JSONObject jsonObject) {
List<Cell> cells = new ArrayList<>();
List<Block> blocks = new ArrayList<>();
@@ -110,11 +138,11 @@ public class SudokuSerializer {
JSONArray cellsJson = jsonObject.getJSONArray("cells");
for (int i = 0; i < cellsJson.length(); i++) {
JSONObject entry = cellsJson.getJSONObject(i);
int symboleIndex = entry.getInt("symboleIndex");
int symbolIndex = entry.getInt("symbolIndex");
if (entry.has("immutable")) {
cells.add(new Cell(symboleIndex, false));
cells.add(new Cell(symbolIndex, false));
} else {
cells.add(new Cell(symboleIndex));
cells.add(new Cell(symbolIndex));
}
}