-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPipsJSON.java
More file actions
260 lines (212 loc) · 9.27 KB
/
PipsJSON.java
File metadata and controls
260 lines (212 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import processing.core.PApplet;
import processing.data.JSONArray;
import processing.data.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
/**
* PipsJSON handles the fetching, caching, and parsing of NYT Pips puzzle data.
* It manages the transition from raw JSON to the internal PipsGame model.
*/
public class PipsJSON {
private final PApplet app;
private final File cacheDirectory;
public PipsJSON(PApplet app) {
this.app = app;
this.cacheDirectory = new File(app.sketchPath(PipsConstants.GAME_FOLDER));
ensureDirectoryExists(cacheDirectory);
}
private static void ensureDirectoryExists(File folder) {
if (!folder.exists()) folder.mkdirs();
}
private static String readUTF8File(File file) {
try {
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
return null;
}
}
/**
* Entry point: retrieves puzzle data from local cache or remote URL and parses it.
*/
public PipsGame getPipsGame(String dateStr, String difficulty) {
String jsonContent = fetchJsonContent(dateStr, difficulty);
return parsePipsGame(jsonContent, difficulty);
}
/**
* Checks local storage for a cached puzzle file before attempting a download.
*/
private String fetchJsonContent(String dateStr, String difficulty) {
String fileName = String.format("NYT_Pips_%s_%s.json", dateStr, difficulty);
File cacheFile = new File(cacheDirectory, fileName);
if (cacheFile.exists()) {
String cachedData = readUTF8File(cacheFile);
// Verify data is not corrupted or effectively null
if (cachedData != null && !cachedData.trim().equals("null")) {
return cachedData;
}
}
return downloadAndCacheJSON(dateStr, difficulty, cacheFile);
}
/**
* Downloads puzzle data from NYT and saves it to the local cache.
*/
private String downloadAndCacheJSON(String dateStr, String difficulty, File targetFile) {
String url = PipsConstants.NYT_JSON + dateStr + ".json";
try {
JSONObject jsonResponse = app.loadJSONObject(url);
if (jsonResponse == null || jsonResponse.size() == 0) {
System.err.println("Failed to retrieve or empty JSON from: " + url);
return null;
}
// Save the raw JSON for future offline use
app.saveJSONObject(jsonResponse, targetFile.getAbsolutePath());
return jsonResponse.toString();
} catch (Exception e) {
System.err.println("Network or I/O Error: " + e.getMessage());
return null;
}
}
/**
* Core logic to map JSON fields to the PipsGame object.
*/
private PipsGame parsePipsGame(String jsonStr, String difficulty) {
if (jsonStr == null || jsonStr.isEmpty()) return null;
JSONObject root = app.parseJSONObject(jsonStr);
if (root == null || !root.hasKey(difficulty)) return null;
JSONObject gameData = root.getJSONObject(difficulty);
PipsGame game = new PipsGame();
// Basic Metadata
game.id = gameData.getInt("id", -1);
game.backendId = gameData.getString("backendId", "");
// Handle optional solution array
JSONArray solutionArray = gameData.hasKey("solution") ? gameData.getJSONArray("solution") : null;
// Parse list of puzzle creators
game.constructors = parseStringOrObjectArray(gameData, "constructors");
// Parse Dominoes (the pieces available for the puzzle)
JSONArray dominoArray = gameData.getJSONArray("dominoes");
game.dominoes.clear();
for (int i = 0; i < dominoArray.size(); i++) {
JSONArray pair = dominoArray.getJSONArray(i);
if (pair.size() == 2) {
game.dominoes.add(new Domino(pair.getInt(0), pair.getInt(1)));
}
}
// Sort dominoes by total pip count for easier UI/Solver handling
game.dominoes.sort((d1, d2) -> Integer.compare(d1.a + d1.b, d2.a + d2.b));
// Parse Regions (the constraints placed on specific grid cells)
parseRegions(game, gameData);
// Finalize state if solution exists
if (solutionArray != null) {
game.JSONSolution = buildSolutionGridString(solutionArray, dominoArray);
}
game.finaliseGrid();
game.initialSupply(); // Initial pip inventory
game.initialSumState(); // Status of region sums
return game;
}
/**
* Iterates through the 'regions' array and maps JSON logic to internal enums/types.
*/
private void parseRegions(PipsGame game, JSONObject gameData) {
JSONArray regionsArray = gameData.getJSONArray("regions");
game.regions.clear();
for (int i = 0; i < regionsArray.size(); i++) {
JSONObject regionJson = regionsArray.getJSONObject(i);
Region region = new Region();
region.id = i;
// Map NYT constraint names to ID based constants
String rawType = regionJson.getString("type", "empty").toLowerCase();
switch (rawType) {
case "equals":
region.constraintTypeId = PipsConstants.TYPE_ALL_EQUAL;
break;
case "unequal":
region.constraintTypeId = PipsConstants.TYPE_NOT_EQUAL;
break;
case "sum":
region.constraintTypeId = PipsConstants.TYPE_SUM;
break;
case "less":
region.constraintTypeId = PipsConstants.TYPE_LESS_THAN;
break;
case "greater":
region.constraintTypeId = PipsConstants.TYPE_GREATER_THAN;
break;
default:
region.constraintTypeId = PipsConstants.TYPE_EMPTY;
break;
}
region.target = regionJson.getInt("target", 0);
// Map 0-indexed JSON coordinates to 1-indexed Game coordinates
JSONArray indices = regionJson.getJSONArray("indices");
for (int j = 0; j < indices.size(); j++) {
JSONArray coord = indices.getJSONArray(j);
// Calculate values first
int row = coord.getInt(0) + 1;
int col = coord.getInt(1) + 1;
int rId = i;
Cell cell = new Cell(row, col, rId);
region.cells.add(cell);
}
game.regions.add(region);
}
}
/**
* Converts the nested solution arrays into a human-readable ASCII grid.
*/
private String buildSolutionGridString(JSONArray solArray, JSONArray domArray) {
int maxR = 0, maxC = 0;
// Find grid boundaries
for (int i = 0; i < solArray.size(); i++) {
JSONArray pair = solArray.getJSONArray(i);
for (int j = 0; j < 2; j++) {
maxR = Math.max(maxR, pair.getJSONArray(j).getInt(0));
maxC = Math.max(maxC, pair.getJSONArray(j).getInt(1));
}
}
int[][] grid = new int[maxR + 1][maxC + 1];
for (int r = 0; r <= maxR; r++) {
for (int c = 0; c <= maxC; c++) grid[r][c] = -1;
}
// Map values to grid positions
for (int i = 0; i < solArray.size(); i++) {
JSONArray locPair = solArray.getJSONArray(i);
JSONArray valPair = domArray.getJSONArray(i);
grid[locPair.getJSONArray(0).getInt(0)][locPair.getJSONArray(0).getInt(1)] = valPair.getInt(0);
grid[locPair.getJSONArray(1).getInt(0)][locPair.getJSONArray(1).getInt(1)] = valPair.getInt(1);
}
StringBuilder sb = new StringBuilder();
for (int[] row : grid) {
for (int val : row) {
sb.append(val == -1 ? " . " : " " + val + " ");
}
sb.append("\n");
}
return sb.toString();
}
/**
* Flexible parser for fields that might be a String, an Array of Strings,
* or an Array of Objects (e.g., 'constructors').
*/
private String[] parseStringOrObjectArray(JSONObject parent, String key) {
if (!parent.hasKey(key)) return null;
Object val = parent.get(key);
if (val instanceof JSONArray) {
JSONArray arr = (JSONArray) val; // Manual cast required
String[] result = new String[arr.size()];
for (int i = 0; i < arr.size(); i++) {
Object item = arr.get(i);
if (item instanceof JSONObject) {
JSONObject obj = (JSONObject) item; // Manual cast required
result[i] = obj.getString("name", obj.toString());
} else {
result[i] = item.toString();
}
}
return result;
}
return new String[]{val.toString()};
}
}