Can now take the dual of a grid
[sgt/puzzles] / loopy.c
CommitLineData
6193da8d 1/*
7c95608a 2 * loopy.c:
3 *
4 * An implementation of the Nikoli game 'Loop the loop'.
121aae4b 5 * (c) Mike Pinna, 2005, 2006
7c95608a 6 * Substantially rewritten to allowing for more general types of grid.
7 * (c) Lambros Lambrou 2008
6193da8d 8 *
9 * vim: set shiftwidth=4 :set textwidth=80:
7c95608a 10 */
6193da8d 11
12/*
a36a26d7 13 * Possible future solver enhancements:
14 *
15 * - There's an interesting deductive technique which makes use
16 * of topology rather than just graph theory. Each _face_ in
17 * the grid is either inside or outside the loop; you can tell
18 * that two faces are on the same side of the loop if they're
19 * separated by a LINE_NO (or, more generally, by a path
20 * crossing no LINE_UNKNOWNs and an even number of LINE_YESes),
21 * and on the opposite side of the loop if they're separated by
22 * a LINE_YES (or an odd number of LINE_YESes and no
23 * LINE_UNKNOWNs). Oh, and any face separated from the outside
24 * of the grid by a LINE_YES or a LINE_NO is on the inside or
25 * outside respectively. So if you can track this for all
26 * faces, you figure out the state of the line between a pair
27 * once their relative insideness is known.
28 * + The way I envisage this working is simply to keep an edsf
29 * of all _faces_, which indicates whether they're on
30 * opposite sides of the loop from one another. We also
31 * include a special entry in the edsf for the infinite
32 * exterior "face".
33 * + So, the simple way to do this is to just go through the
34 * edges: every time we see an edge in a state other than
35 * LINE_UNKNOWN which separates two faces that aren't in the
36 * same edsf class, we can rectify that by merging the
37 * classes. Then, conversely, an edge in LINE_UNKNOWN state
38 * which separates two faces that _are_ in the same edsf
39 * class can immediately have its state determined.
40 * + But you can go one better, if you're prepared to loop
41 * over all _pairs_ of edges. Suppose we have edges A and B,
42 * which respectively separate faces A1,A2 and B1,B2.
43 * Suppose that A,B are in the same edge-edsf class and that
44 * A1,B1 (wlog) are in the same face-edsf class; then we can
45 * immediately place A2,B2 into the same face-edsf class (as
46 * each other, not as A1 and A2) one way round or the other.
47 * And conversely again, if A1,B1 are in the same face-edsf
48 * class and so are A2,B2, then we can put A,B into the same
49 * face-edsf class.
50 * * Of course, this deduction requires a quadratic-time
51 * loop over all pairs of edges in the grid, so it should
52 * be reserved until there's nothing easier left to be
53 * done.
54 *
55 * - The generalised grid support has made me (SGT) notice a
56 * possible extension to the loop-avoidance code. When you have
57 * a path of connected edges such that no other edges at all
58 * are incident on any vertex in the middle of the path - or,
59 * alternatively, such that any such edges are already known to
60 * be LINE_NO - then you know those edges are either all
61 * LINE_YES or all LINE_NO. Hence you can mentally merge the
62 * entire path into a single long curly edge for the purposes
63 * of loop avoidance, and look directly at whether or not the
64 * extreme endpoints of the path are connected by some other
65 * route. I find this coming up fairly often when I play on the
66 * octagonal grid setting, so it might be worth implementing in
67 * the solver.
121aae4b 68 *
69 * - (Just a speed optimisation.) Consider some todo list queue where every
70 * time we modify something we mark it for consideration by other bits of
71 * the solver, to save iteration over things that have already been done.
6193da8d 72 */
73
74#include <stdio.h>
75#include <stdlib.h>
7126ca41 76#include <stddef.h>
6193da8d 77#include <string.h>
78#include <assert.h>
79#include <ctype.h>
80#include <math.h>
81
82#include "puzzles.h"
83#include "tree234.h"
7c95608a 84#include "grid.h"
b760b8bd 85#include "loopgen.h"
6193da8d 86
121aae4b 87/* Debugging options */
7c95608a 88
89/*
90#define DEBUG_CACHES
91#define SHOW_WORKING
92#define DEBUG_DLINES
93*/
121aae4b 94
95/* ----------------------------------------------------------------------
96 * Struct, enum and function declarations
97 */
98
99enum {
100 COL_BACKGROUND,
101 COL_FOREGROUND,
7c95608a 102 COL_LINEUNKNOWN,
121aae4b 103 COL_HIGHLIGHT,
104 COL_MISTAKE,
7c95608a 105 COL_SATISFIED,
ec909c7a 106 COL_FAINT,
121aae4b 107 NCOLOURS
108};
109
110struct game_state {
cebf0b0d 111 grid *game_grid; /* ref-counted (internally) */
7c95608a 112
113 /* Put -1 in a face that doesn't get a clue */
aa8ccc55 114 signed char *clues;
7c95608a 115
116 /* Array of line states, to store whether each line is
117 * YES, NO or UNKNOWN */
118 char *lines;
121aae4b 119
b6bf0adc 120 unsigned char *line_errors;
121
121aae4b 122 int solved;
123 int cheated;
124
7c95608a 125 /* Used in game_text_format(), so that it knows what type of
126 * grid it's trying to render as ASCII text. */
127 int grid_type;
121aae4b 128};
129
130enum solver_status {
131 SOLVER_SOLVED, /* This is the only solution the solver could find */
132 SOLVER_MISTAKE, /* This is definitely not a solution */
133 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
134 SOLVER_INCOMPLETE /* This may be a partial solution */
135};
136
7c95608a 137/* ------ Solver state ------ */
121aae4b 138typedef struct solver_state {
139 game_state *state;
121aae4b 140 enum solver_status solver_status;
141 /* NB looplen is the number of dots that are joined together at a point, ie a
142 * looplen of 1 means there are no lines to a particular dot */
143 int *looplen;
144
315e47b9 145 /* Difficulty level of solver. Used by solver functions that want to
146 * vary their behaviour depending on the requested difficulty level. */
147 int diff;
148
121aae4b 149 /* caches */
7c95608a 150 char *dot_yes_count;
151 char *dot_no_count;
152 char *face_yes_count;
153 char *face_no_count;
154 char *dot_solved, *face_solved;
121aae4b 155 int *dotdsf;
156
315e47b9 157 /* Information for Normal level deductions:
158 * For each dline, store a bitmask for whether we know:
159 * (bit 0) at least one is YES
160 * (bit 1) at most one is YES */
161 char *dlines;
162
163 /* Hard level information */
164 int *linedsf;
121aae4b 165} solver_state;
166
167/*
168 * Difficulty levels. I do some macro ickery here to ensure that my
169 * enum and the various forms of my name list always match up.
170 */
171
172#define DIFFLIST(A) \
315e47b9 173 A(EASY,Easy,e) \
174 A(NORMAL,Normal,n) \
175 A(TRICKY,Tricky,t) \
176 A(HARD,Hard,h)
177#define ENUM(upper,title,lower) DIFF_ ## upper,
178#define TITLE(upper,title,lower) #title,
179#define ENCODE(upper,title,lower) #lower
180#define CONFIG(upper,title,lower) ":" #title
1a739e2f 181enum { DIFFLIST(ENUM) DIFF_MAX };
121aae4b 182static char const *const diffnames[] = { DIFFLIST(TITLE) };
183static char const diffchars[] = DIFFLIST(ENCODE);
184#define DIFFCONFIG DIFFLIST(CONFIG)
315e47b9 185
186/*
187 * Solver routines, sorted roughly in order of computational cost.
188 * The solver will run the faster deductions first, and slower deductions are
189 * only invoked when the faster deductions are unable to make progress.
190 * Each function is associated with a difficulty level, so that the generated
191 * puzzles are solvable by applying only the functions with the chosen
192 * difficulty level or lower.
193 */
194#define SOLVERLIST(A) \
195 A(trivial_deductions, DIFF_EASY) \
196 A(dline_deductions, DIFF_NORMAL) \
197 A(linedsf_deductions, DIFF_HARD) \
198 A(loop_deductions, DIFF_EASY)
199#define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
200#define SOLVER_FN(fn,diff) &fn,
201#define SOLVER_DIFF(fn,diff) diff,
202SOLVERLIST(SOLVER_FN_DECL)
203static int (*(solver_fns[]))(solver_state *) = { SOLVERLIST(SOLVER_FN) };
204static int const solver_diffs[] = { SOLVERLIST(SOLVER_DIFF) };
fd66a01d 205static const int NUM_SOLVERS = sizeof(solver_diffs)/sizeof(*solver_diffs);
121aae4b 206
207struct game_params {
208 int w, h;
1a739e2f 209 int diff;
7c95608a 210 int type;
121aae4b 211};
212
b6bf0adc 213/* line_drawstate is the same as line_state, but with the extra ERROR
214 * possibility. The drawing code copies line_state to line_drawstate,
215 * except in the case that the line is an error. */
121aae4b 216enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
b6bf0adc 217enum line_drawstate { DS_LINE_YES, DS_LINE_UNKNOWN,
218 DS_LINE_NO, DS_LINE_ERROR };
121aae4b 219
7c95608a 220#define OPP(line_state) \
221 (2 - line_state)
121aae4b 222
121aae4b 223
224struct game_drawstate {
225 int started;
7c95608a 226 int tilesize;
121aae4b 227 int flashing;
e0936bbd 228 int *textx, *texty;
7c95608a 229 char *lines;
121aae4b 230 char *clue_error;
7c95608a 231 char *clue_satisfied;
121aae4b 232};
233
121aae4b 234static char *validate_desc(game_params *params, char *desc);
7c95608a 235static int dot_order(const game_state* state, int i, char line_type);
236static int face_order(const game_state* state, int i, char line_type);
315e47b9 237static solver_state *solve_game_rec(const solver_state *sstate);
121aae4b 238
239#ifdef DEBUG_CACHES
240static void check_caches(const solver_state* sstate);
241#else
242#define check_caches(s)
243#endif
244
7c95608a 245/* ------- List of grid generators ------- */
246#define GRIDLIST(A) \
cebf0b0d 247 A(Squares,GRID_SQUARE,3,3) \
248 A(Triangular,GRID_TRIANGULAR,3,3) \
249 A(Honeycomb,GRID_HONEYCOMB,3,3) \
250 A(Snub-Square,GRID_SNUBSQUARE,3,3) \
251 A(Cairo,GRID_CAIRO,3,4) \
252 A(Great-Hexagonal,GRID_GREATHEXAGONAL,3,3) \
253 A(Octagonal,GRID_OCTAGONAL,3,3) \
254 A(Kites,GRID_KITE,3,3) \
255 A(Floret,GRID_FLORET,1,2) \
256 A(Dodecagonal,GRID_DODECAGONAL,2,2) \
257 A(Great-Dodecagonal,GRID_GREATDODECAGONAL,2,2) \
258 A(Penrose (kite/dart),GRID_PENROSE_P2,3,3) \
43a45950 259 A(Penrose (rhombs),GRID_PENROSE_P3,3,3) \
260 A(Octagonal (dual),GRID_DUAL_OCTAGONAL,3,3)
cebf0b0d 261
262#define GRID_NAME(title,type,amin,omin) #title,
263#define GRID_CONFIG(title,type,amin,omin) ":" #title
264#define GRID_TYPE(title,type,amin,omin) type,
265#define GRID_SIZES(title,type,amin,omin) \
e3c9e042 266 {amin, omin, \
267 "Width and height for this grid type must both be at least " #amin, \
268 "At least one of width and height for this grid type must be at least " #omin,},
7c95608a 269static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
270#define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
cebf0b0d 271static grid_type grid_types[] = { GRIDLIST(GRID_TYPE) };
272#define NUM_GRID_TYPES (sizeof(grid_types) / sizeof(grid_types[0]))
e3c9e042 273static const struct {
274 int amin, omin;
275 char *aerr, *oerr;
276} grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
7c95608a 277
278/* Generates a (dynamically allocated) new grid, according to the
279 * type and size requested in params. Does nothing if the grid is already
cebf0b0d 280 * generated. */
281static grid *loopy_generate_grid(game_params *params, char *grid_desc)
7c95608a 282{
cebf0b0d 283 return grid_new(grid_types[params->type], params->w, params->h, grid_desc);
7c95608a 284}
285
121aae4b 286/* ----------------------------------------------------------------------
7c95608a 287 * Preprocessor magic
121aae4b 288 */
289
290/* General constants */
6193da8d 291#define PREFERRED_TILE_SIZE 32
7c95608a 292#define BORDER(tilesize) ((tilesize) / 2)
c0eb17ce 293#define FLASH_TIME 0.5F
6193da8d 294
121aae4b 295#define BIT_SET(field, bit) ((field) & (1<<(bit)))
296
297#define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
298 ((field) |= (1<<(bit)), TRUE))
299
300#define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
301 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
302
121aae4b 303#define CLUE2CHAR(c) \
918a098a 304 ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
121aae4b 305
121aae4b 306/* ----------------------------------------------------------------------
307 * General struct manipulation and other straightforward code
308 */
6193da8d 309
310static game_state *dup_game(game_state *state)
311{
312 game_state *ret = snew(game_state);
313
7c95608a 314 ret->game_grid = state->game_grid;
315 ret->game_grid->refcount++;
316
6193da8d 317 ret->solved = state->solved;
318 ret->cheated = state->cheated;
319
7c95608a 320 ret->clues = snewn(state->game_grid->num_faces, signed char);
321 memcpy(ret->clues, state->clues, state->game_grid->num_faces);
6193da8d 322
7c95608a 323 ret->lines = snewn(state->game_grid->num_edges, char);
324 memcpy(ret->lines, state->lines, state->game_grid->num_edges);
6193da8d 325
b6bf0adc 326 ret->line_errors = snewn(state->game_grid->num_edges, unsigned char);
327 memcpy(ret->line_errors, state->line_errors, state->game_grid->num_edges);
328
7c95608a 329 ret->grid_type = state->grid_type;
6193da8d 330 return ret;
331}
332
333static void free_game(game_state *state)
334{
335 if (state) {
7c95608a 336 grid_free(state->game_grid);
6193da8d 337 sfree(state->clues);
7c95608a 338 sfree(state->lines);
b6bf0adc 339 sfree(state->line_errors);
6193da8d 340 sfree(state);
341 }
342}
343
7c95608a 344static solver_state *new_solver_state(game_state *state, int diff) {
345 int i;
346 int num_dots = state->game_grid->num_dots;
347 int num_faces = state->game_grid->num_faces;
348 int num_edges = state->game_grid->num_edges;
6193da8d 349 solver_state *ret = snew(solver_state);
6193da8d 350
7c95608a 351 ret->state = dup_game(state);
352
353 ret->solver_status = SOLVER_INCOMPLETE;
315e47b9 354 ret->diff = diff;
6193da8d 355
7c95608a 356 ret->dotdsf = snew_dsf(num_dots);
357 ret->looplen = snewn(num_dots, int);
121aae4b 358
7c95608a 359 for (i = 0; i < num_dots; i++) {
121aae4b 360 ret->looplen[i] = 1;
361 }
362
7c95608a 363 ret->dot_solved = snewn(num_dots, char);
364 ret->face_solved = snewn(num_faces, char);
365 memset(ret->dot_solved, FALSE, num_dots);
366 memset(ret->face_solved, FALSE, num_faces);
121aae4b 367
7c95608a 368 ret->dot_yes_count = snewn(num_dots, char);
369 memset(ret->dot_yes_count, 0, num_dots);
370 ret->dot_no_count = snewn(num_dots, char);
371 memset(ret->dot_no_count, 0, num_dots);
372 ret->face_yes_count = snewn(num_faces, char);
373 memset(ret->face_yes_count, 0, num_faces);
374 ret->face_no_count = snewn(num_faces, char);
375 memset(ret->face_no_count, 0, num_faces);
121aae4b 376
377 if (diff < DIFF_NORMAL) {
315e47b9 378 ret->dlines = NULL;
121aae4b 379 } else {
315e47b9 380 ret->dlines = snewn(2*num_edges, char);
381 memset(ret->dlines, 0, 2*num_edges);
121aae4b 382 }
383
384 if (diff < DIFF_HARD) {
315e47b9 385 ret->linedsf = NULL;
121aae4b 386 } else {
315e47b9 387 ret->linedsf = snew_dsf(state->game_grid->num_edges);
6193da8d 388 }
389
390 return ret;
391}
392
393static void free_solver_state(solver_state *sstate) {
394 if (sstate) {
395 free_game(sstate->state);
9cfc03b7 396 sfree(sstate->dotdsf);
397 sfree(sstate->looplen);
121aae4b 398 sfree(sstate->dot_solved);
7c95608a 399 sfree(sstate->face_solved);
400 sfree(sstate->dot_yes_count);
401 sfree(sstate->dot_no_count);
402 sfree(sstate->face_yes_count);
403 sfree(sstate->face_no_count);
121aae4b 404
315e47b9 405 /* OK, because sfree(NULL) is a no-op */
406 sfree(sstate->dlines);
407 sfree(sstate->linedsf);
121aae4b 408
9cfc03b7 409 sfree(sstate);
6193da8d 410 }
411}
412
121aae4b 413static solver_state *dup_solver_state(const solver_state *sstate) {
7c95608a 414 game_state *state = sstate->state;
415 int num_dots = state->game_grid->num_dots;
416 int num_faces = state->game_grid->num_faces;
417 int num_edges = state->game_grid->num_edges;
6193da8d 418 solver_state *ret = snew(solver_state);
419
9cfc03b7 420 ret->state = state = dup_game(sstate->state);
6193da8d 421
6193da8d 422 ret->solver_status = sstate->solver_status;
315e47b9 423 ret->diff = sstate->diff;
6193da8d 424
7c95608a 425 ret->dotdsf = snewn(num_dots, int);
426 ret->looplen = snewn(num_dots, int);
427 memcpy(ret->dotdsf, sstate->dotdsf,
428 num_dots * sizeof(int));
429 memcpy(ret->looplen, sstate->looplen,
430 num_dots * sizeof(int));
431
432 ret->dot_solved = snewn(num_dots, char);
433 ret->face_solved = snewn(num_faces, char);
434 memcpy(ret->dot_solved, sstate->dot_solved, num_dots);
435 memcpy(ret->face_solved, sstate->face_solved, num_faces);
436
437 ret->dot_yes_count = snewn(num_dots, char);
438 memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
439 ret->dot_no_count = snewn(num_dots, char);
440 memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
441
442 ret->face_yes_count = snewn(num_faces, char);
443 memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
444 ret->face_no_count = snewn(num_faces, char);
445 memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
121aae4b 446
315e47b9 447 if (sstate->dlines) {
448 ret->dlines = snewn(2*num_edges, char);
449 memcpy(ret->dlines, sstate->dlines,
7c95608a 450 2*num_edges);
121aae4b 451 } else {
315e47b9 452 ret->dlines = NULL;
121aae4b 453 }
454
315e47b9 455 if (sstate->linedsf) {
456 ret->linedsf = snewn(num_edges, int);
457 memcpy(ret->linedsf, sstate->linedsf,
7c95608a 458 num_edges * sizeof(int));
121aae4b 459 } else {
315e47b9 460 ret->linedsf = NULL;
121aae4b 461 }
6193da8d 462
463 return ret;
464}
465
121aae4b 466static game_params *default_params(void)
6193da8d 467{
121aae4b 468 game_params *ret = snew(game_params);
6193da8d 469
121aae4b 470#ifdef SLOW_SYSTEM
7c95608a 471 ret->h = 7;
472 ret->w = 7;
121aae4b 473#else
474 ret->h = 10;
475 ret->w = 10;
476#endif
477 ret->diff = DIFF_EASY;
7c95608a 478 ret->type = 0;
479
121aae4b 480 return ret;
6193da8d 481}
482
121aae4b 483static game_params *dup_params(game_params *params)
6193da8d 484{
121aae4b 485 game_params *ret = snew(game_params);
7c95608a 486
121aae4b 487 *ret = *params; /* structure copy */
488 return ret;
489}
6193da8d 490
121aae4b 491static const game_params presets[] = {
b1535c90 492#ifdef SMALL_SCREEN
cebf0b0d 493 { 7, 7, DIFF_EASY, 0 },
494 { 7, 7, DIFF_NORMAL, 0 },
495 { 7, 7, DIFF_HARD, 0 },
496 { 7, 7, DIFF_HARD, 1 },
497 { 7, 7, DIFF_HARD, 2 },
498 { 5, 5, DIFF_HARD, 3 },
499 { 7, 7, DIFF_HARD, 4 },
500 { 5, 4, DIFF_HARD, 5 },
501 { 5, 5, DIFF_HARD, 6 },
502 { 5, 5, DIFF_HARD, 7 },
503 { 3, 3, DIFF_HARD, 8 },
504 { 3, 3, DIFF_HARD, 9 },
505 { 3, 3, DIFF_HARD, 10 },
506 { 6, 6, DIFF_HARD, 11 },
507 { 6, 6, DIFF_HARD, 12 },
b1535c90 508#else
cebf0b0d 509 { 7, 7, DIFF_EASY, 0 },
510 { 10, 10, DIFF_EASY, 0 },
511 { 7, 7, DIFF_NORMAL, 0 },
512 { 10, 10, DIFF_NORMAL, 0 },
513 { 7, 7, DIFF_HARD, 0 },
514 { 10, 10, DIFF_HARD, 0 },
515 { 10, 10, DIFF_HARD, 1 },
516 { 12, 10, DIFF_HARD, 2 },
517 { 7, 7, DIFF_HARD, 3 },
518 { 9, 9, DIFF_HARD, 4 },
519 { 5, 4, DIFF_HARD, 5 },
520 { 7, 7, DIFF_HARD, 6 },
521 { 5, 5, DIFF_HARD, 7 },
522 { 5, 5, DIFF_HARD, 8 },
523 { 5, 4, DIFF_HARD, 9 },
524 { 5, 4, DIFF_HARD, 10 },
525 { 10, 10, DIFF_HARD, 11 },
526 { 10, 10, DIFF_HARD, 12 }
b1535c90 527#endif
121aae4b 528};
6193da8d 529
121aae4b 530static int game_fetch_preset(int i, char **name, game_params **params)
6193da8d 531{
1a739e2f 532 game_params *tmppar;
121aae4b 533 char buf[80];
6193da8d 534
121aae4b 535 if (i < 0 || i >= lenof(presets))
536 return FALSE;
6193da8d 537
1a739e2f 538 tmppar = snew(game_params);
539 *tmppar = presets[i];
540 *params = tmppar;
7c95608a 541 sprintf(buf, "%dx%d %s - %s", tmppar->h, tmppar->w,
542 gridnames[tmppar->type], diffnames[tmppar->diff]);
121aae4b 543 *name = dupstr(buf);
544
545 return TRUE;
6193da8d 546}
547
548static void free_params(game_params *params)
549{
550 sfree(params);
551}
552
553static void decode_params(game_params *params, char const *string)
554{
555 params->h = params->w = atoi(string);
c0eb17ce 556 params->diff = DIFF_EASY;
6193da8d 557 while (*string && isdigit((unsigned char)*string)) string++;
558 if (*string == 'x') {
559 string++;
560 params->h = atoi(string);
121aae4b 561 while (*string && isdigit((unsigned char)*string)) string++;
6193da8d 562 }
7c95608a 563 if (*string == 't') {
6193da8d 564 string++;
7c95608a 565 params->type = atoi(string);
121aae4b 566 while (*string && isdigit((unsigned char)*string)) string++;
6193da8d 567 }
c0eb17ce 568 if (*string == 'd') {
569 int i;
c0eb17ce 570 string++;
121aae4b 571 for (i = 0; i < DIFF_MAX; i++)
572 if (*string == diffchars[i])
573 params->diff = i;
574 if (*string) string++;
c0eb17ce 575 }
6193da8d 576}
577
578static char *encode_params(game_params *params, int full)
579{
580 char str[80];
7c95608a 581 sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
6193da8d 582 if (full)
7c95608a 583 sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
6193da8d 584 return dupstr(str);
585}
586
587static config_item *game_configure(game_params *params)
588{
589 config_item *ret;
590 char buf[80];
591
7c95608a 592 ret = snewn(5, config_item);
6193da8d 593
594 ret[0].name = "Width";
595 ret[0].type = C_STRING;
596 sprintf(buf, "%d", params->w);
597 ret[0].sval = dupstr(buf);
598 ret[0].ival = 0;
599
600 ret[1].name = "Height";
601 ret[1].type = C_STRING;
602 sprintf(buf, "%d", params->h);
603 ret[1].sval = dupstr(buf);
604 ret[1].ival = 0;
605
7c95608a 606 ret[2].name = "Grid type";
c0eb17ce 607 ret[2].type = C_CHOICES;
7c95608a 608 ret[2].sval = GRID_CONFIGS;
609 ret[2].ival = params->type;
6193da8d 610
7c95608a 611 ret[3].name = "Difficulty";
612 ret[3].type = C_CHOICES;
613 ret[3].sval = DIFFCONFIG;
614 ret[3].ival = params->diff;
615
616 ret[4].name = NULL;
617 ret[4].type = C_END;
618 ret[4].sval = NULL;
619 ret[4].ival = 0;
6193da8d 620
621 return ret;
622}
623
624static game_params *custom_params(config_item *cfg)
625{
626 game_params *ret = snew(game_params);
627
628 ret->w = atoi(cfg[0].sval);
629 ret->h = atoi(cfg[1].sval);
7c95608a 630 ret->type = cfg[2].ival;
631 ret->diff = cfg[3].ival;
6193da8d 632
633 return ret;
634}
635
636static char *validate_params(game_params *params, int full)
637{
7c95608a 638 if (params->type < 0 || params->type >= NUM_GRID_TYPES)
639 return "Illegal grid type";
e3c9e042 640 if (params->w < grid_size_limits[params->type].amin ||
641 params->h < grid_size_limits[params->type].amin)
642 return grid_size_limits[params->type].aerr;
643 if (params->w < grid_size_limits[params->type].omin &&
644 params->h < grid_size_limits[params->type].omin)
645 return grid_size_limits[params->type].oerr;
c0eb17ce 646
647 /*
648 * This shouldn't be able to happen at all, since decode_params
649 * and custom_params will never generate anything that isn't
650 * within range.
651 */
1a739e2f 652 assert(params->diff < DIFF_MAX);
c0eb17ce 653
6193da8d 654 return NULL;
655}
656
121aae4b 657/* Returns a newly allocated string describing the current puzzle */
658static char *state_to_text(const game_state *state)
6193da8d 659{
7c95608a 660 grid *g = state->game_grid;
121aae4b 661 char *retval;
7c95608a 662 int num_faces = g->num_faces;
663 char *description = snewn(num_faces + 1, char);
121aae4b 664 char *dp = description;
665 int empty_count = 0;
7c95608a 666 int i;
6193da8d 667
7c95608a 668 for (i = 0; i < num_faces; i++) {
669 if (state->clues[i] < 0) {
121aae4b 670 if (empty_count > 25) {
671 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
672 empty_count = 0;
673 }
674 empty_count++;
675 } else {
676 if (empty_count) {
677 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
678 empty_count = 0;
679 }
7c95608a 680 dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
121aae4b 681 }
682 }
6193da8d 683
121aae4b 684 if (empty_count)
1a739e2f 685 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
121aae4b 686
687 retval = dupstr(description);
688 sfree(description);
689
690 return retval;
6193da8d 691}
692
cebf0b0d 693#define GRID_DESC_SEP '_'
694
695/* Splits up a (optional) grid_desc from the game desc. Returns the
696 * grid_desc (which needs freeing) and updates the desc pointer to
697 * start of real desc, or returns NULL if no desc. */
698static char *extract_grid_desc(char **desc)
699{
700 char *sep = strchr(*desc, GRID_DESC_SEP), *gd;
701 int gd_len;
702
703 if (!sep) return NULL;
704
705 gd_len = sep - (*desc);
706 gd = snewn(gd_len+1, char);
707 memcpy(gd, *desc, gd_len);
708 gd[gd_len] = '\0';
709
710 *desc = sep+1;
711
712 return gd;
713}
714
121aae4b 715/* We require that the params pass the test in validate_params and that the
716 * description fills the entire game area */
717static char *validate_desc(game_params *params, char *desc)
6193da8d 718{
121aae4b 719 int count = 0;
7c95608a 720 grid *g;
cebf0b0d 721 char *grid_desc, *ret;
722
723 /* It's pretty inefficient to do this just for validation. All we need to
724 * know is the precise number of faces. */
725 grid_desc = extract_grid_desc(&desc);
726 ret = grid_validate_desc(grid_types[params->type], params->w, params->h, grid_desc);
727 if (ret) return ret;
728
729 g = loopy_generate_grid(params, grid_desc);
730 if (grid_desc) sfree(grid_desc);
6193da8d 731
121aae4b 732 for (; *desc; ++desc) {
918a098a 733 if ((*desc >= '0' && *desc <= '9') || (*desc >= 'A' && *desc <= 'Z')) {
121aae4b 734 count++;
735 continue;
736 }
737 if (*desc >= 'a') {
738 count += *desc - 'a' + 1;
739 continue;
740 }
741 return "Unknown character in description";
6193da8d 742 }
743
7c95608a 744 if (count < g->num_faces)
121aae4b 745 return "Description too short for board size";
7c95608a 746 if (count > g->num_faces)
121aae4b 747 return "Description too long for board size";
6193da8d 748
cebf0b0d 749 grid_free(g);
750
121aae4b 751 return NULL;
6193da8d 752}
753
121aae4b 754/* Sums the lengths of the numbers in range [0,n) */
755/* See equivalent function in solo.c for justification of this. */
756static int len_0_to_n(int n)
6193da8d 757{
121aae4b 758 int len = 1; /* Counting 0 as a bit of a special case */
759 int i;
760
761 for (i = 1; i < n; i *= 10) {
762 len += max(n - i, 0);
6193da8d 763 }
121aae4b 764
765 return len;
6193da8d 766}
767
121aae4b 768static char *encode_solve_move(const game_state *state)
769{
7c95608a 770 int len;
121aae4b 771 char *ret, *p;
7c95608a 772 int i;
773 int num_edges = state->game_grid->num_edges;
774
121aae4b 775 /* This is going to return a string representing the moves needed to set
776 * every line in a grid to be the same as the ones in 'state'. The exact
777 * length of this string is predictable. */
6193da8d 778
121aae4b 779 len = 1; /* Count the 'S' prefix */
7c95608a 780 /* Numbers in all lines */
781 len += len_0_to_n(num_edges);
782 /* For each line we also have a letter */
783 len += num_edges;
6193da8d 784
121aae4b 785 ret = snewn(len + 1, char);
786 p = ret;
6193da8d 787
121aae4b 788 p += sprintf(p, "S");
6193da8d 789
7c95608a 790 for (i = 0; i < num_edges; i++) {
791 switch (state->lines[i]) {
792 case LINE_YES:
793 p += sprintf(p, "%dy", i);
794 break;
795 case LINE_NO:
796 p += sprintf(p, "%dn", i);
797 break;
6193da8d 798 }
6193da8d 799 }
121aae4b 800
801 /* No point in doing sums like that if they're going to be wrong */
802 assert(strlen(ret) <= (size_t)len);
803 return ret;
6193da8d 804}
805
121aae4b 806static game_ui *new_ui(game_state *state)
6193da8d 807{
121aae4b 808 return NULL;
809}
6193da8d 810
121aae4b 811static void free_ui(game_ui *ui)
812{
813}
6193da8d 814
121aae4b 815static char *encode_ui(game_ui *ui)
816{
817 return NULL;
818}
6193da8d 819
121aae4b 820static void decode_ui(game_ui *ui, char *encoding)
821{
822}
6193da8d 823
121aae4b 824static void game_changed_state(game_ui *ui, game_state *oldstate,
825 game_state *newstate)
826{
827}
6193da8d 828
121aae4b 829static void game_compute_size(game_params *params, int tilesize,
830 int *x, int *y)
831{
1515b973 832 int grid_width, grid_height, rendered_width, rendered_height;
cebf0b0d 833 int g_tilesize;
834
835 grid_compute_size(grid_types[params->type], params->w, params->h,
836 &g_tilesize, &grid_width, &grid_height);
1515b973 837
7c95608a 838 /* multiply first to minimise rounding error on integer division */
cebf0b0d 839 rendered_width = grid_width * tilesize / g_tilesize;
840 rendered_height = grid_height * tilesize / g_tilesize;
7c95608a 841 *x = rendered_width + 2 * BORDER(tilesize) + 1;
842 *y = rendered_height + 2 * BORDER(tilesize) + 1;
121aae4b 843}
6193da8d 844
121aae4b 845static void game_set_size(drawing *dr, game_drawstate *ds,
7c95608a 846 game_params *params, int tilesize)
121aae4b 847{
848 ds->tilesize = tilesize;
121aae4b 849}
6193da8d 850
121aae4b 851static float *game_colours(frontend *fe, int *ncolours)
852{
853 float *ret = snewn(4 * NCOLOURS, float);
6193da8d 854
121aae4b 855 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
856
857 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
858 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
859 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
860
32c231bb 861 /*
862 * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
863 * than the background. (I previously set it to 0.8,0.8,0, but
864 * found that this went badly with the 0.8,0.8,0.8 favoured as a
865 * background by the Java frontend.)
866 */
867 ret[COL_LINEUNKNOWN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
868 ret[COL_LINEUNKNOWN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
7c95608a 869 ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
870
121aae4b 871 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
872 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
873 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
874
875 ret[COL_MISTAKE * 3 + 0] = 1.0F;
876 ret[COL_MISTAKE * 3 + 1] = 0.0F;
877 ret[COL_MISTAKE * 3 + 2] = 0.0F;
878
7c95608a 879 ret[COL_SATISFIED * 3 + 0] = 0.0F;
880 ret[COL_SATISFIED * 3 + 1] = 0.0F;
881 ret[COL_SATISFIED * 3 + 2] = 0.0F;
882
ec909c7a 883 /* We want the faint lines to be a bit darker than the background.
884 * Except if the background is pretty dark already; then it ought to be a
885 * bit lighter. Oy vey.
886 */
887 ret[COL_FAINT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
888 ret[COL_FAINT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
889 ret[COL_FAINT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.9F;
890
121aae4b 891 *ncolours = NCOLOURS;
892 return ret;
893}
894
895static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
896{
897 struct game_drawstate *ds = snew(struct game_drawstate);
7c95608a 898 int num_faces = state->game_grid->num_faces;
899 int num_edges = state->game_grid->num_edges;
e0936bbd 900 int i;
121aae4b 901
7c95608a 902 ds->tilesize = 0;
121aae4b 903 ds->started = 0;
7c95608a 904 ds->lines = snewn(num_edges, char);
905 ds->clue_error = snewn(num_faces, char);
906 ds->clue_satisfied = snewn(num_faces, char);
e0936bbd 907 ds->textx = snewn(num_faces, int);
908 ds->texty = snewn(num_faces, int);
121aae4b 909 ds->flashing = 0;
910
7c95608a 911 memset(ds->lines, LINE_UNKNOWN, num_edges);
912 memset(ds->clue_error, 0, num_faces);
913 memset(ds->clue_satisfied, 0, num_faces);
e0936bbd 914 for (i = 0; i < num_faces; i++)
915 ds->textx[i] = ds->texty[i] = -1;
121aae4b 916
917 return ds;
918}
919
920static void game_free_drawstate(drawing *dr, game_drawstate *ds)
921{
a6bd4b9c 922 sfree(ds->textx);
923 sfree(ds->texty);
121aae4b 924 sfree(ds->clue_error);
7c95608a 925 sfree(ds->clue_satisfied);
926 sfree(ds->lines);
121aae4b 927 sfree(ds);
928}
929
930static int game_timing_state(game_state *state, game_ui *ui)
931{
932 return TRUE;
933}
934
935static float game_anim_length(game_state *oldstate, game_state *newstate,
936 int dir, game_ui *ui)
937{
938 return 0.0F;
939}
940
7c95608a 941static int game_can_format_as_text_now(game_params *params)
942{
943 if (params->type != 0)
944 return FALSE;
945 return TRUE;
946}
947
121aae4b 948static char *game_text_format(game_state *state)
949{
7c95608a 950 int w, h, W, H;
951 int x, y, i;
952 int cell_size;
953 char *ret;
954 grid *g = state->game_grid;
955 grid_face *f;
956
957 assert(state->grid_type == 0);
958
959 /* Work out the basic size unit */
960 f = g->faces; /* first face */
961 assert(f->order == 4);
962 /* The dots are ordered clockwise, so the two opposite
963 * corners are guaranteed to span the square */
964 cell_size = abs(f->dots[0]->x - f->dots[2]->x);
965
966 w = (g->highest_x - g->lowest_x) / cell_size;
967 h = (g->highest_y - g->lowest_y) / cell_size;
968
969 /* Create a blank "canvas" to "draw" on */
970 W = 2 * w + 2;
971 H = 2 * h + 1;
972 ret = snewn(W * H + 1, char);
973 for (y = 0; y < H; y++) {
974 for (x = 0; x < W-1; x++) {
975 ret[y*W + x] = ' ';
121aae4b 976 }
7c95608a 977 ret[y*W + W-1] = '\n';
978 }
979 ret[H*W] = '\0';
980
981 /* Fill in edge info */
982 for (i = 0; i < g->num_edges; i++) {
983 grid_edge *e = g->edges + i;
984 /* Cell coordinates, from (0,0) to (w-1,h-1) */
985 int x1 = (e->dot1->x - g->lowest_x) / cell_size;
986 int x2 = (e->dot2->x - g->lowest_x) / cell_size;
987 int y1 = (e->dot1->y - g->lowest_y) / cell_size;
988 int y2 = (e->dot2->y - g->lowest_y) / cell_size;
989 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
990 * cell coordinates) */
991 x = x1 + x2;
992 y = y1 + y2;
993 switch (state->lines[i]) {
994 case LINE_YES:
995 ret[y*W + x] = (y1 == y2) ? '-' : '|';
996 break;
997 case LINE_NO:
998 ret[y*W + x] = 'x';
999 break;
1000 case LINE_UNKNOWN:
1001 break; /* already a space */
1002 default:
1003 assert(!"Illegal line state");
121aae4b 1004 }
121aae4b 1005 }
7c95608a 1006
1007 /* Fill in clues */
1008 for (i = 0; i < g->num_faces; i++) {
1515b973 1009 int x1, x2, y1, y2;
1010
7c95608a 1011 f = g->faces + i;
1012 assert(f->order == 4);
1013 /* Cell coordinates, from (0,0) to (w-1,h-1) */
1515b973 1014 x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
1015 x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
1016 y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
1017 y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
7c95608a 1018 /* Midpoint, in canvas coordinates */
1019 x = x1 + x2;
1020 y = y1 + y2;
1021 ret[y*W + x] = CLUE2CHAR(state->clues[i]);
121aae4b 1022 }
121aae4b 1023 return ret;
1024}
1025
1026/* ----------------------------------------------------------------------
1027 * Debug code
1028 */
1029
1030#ifdef DEBUG_CACHES
1031static void check_caches(const solver_state* sstate)
1032{
7c95608a 1033 int i;
121aae4b 1034 const game_state *state = sstate->state;
7c95608a 1035 const grid *g = state->game_grid;
121aae4b 1036
7c95608a 1037 for (i = 0; i < g->num_dots; i++) {
1038 assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
1039 assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
121aae4b 1040 }
1041
7c95608a 1042 for (i = 0; i < g->num_faces; i++) {
1043 assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
1044 assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
121aae4b 1045 }
1046}
1047
1048#if 0
1049#define check_caches(s) \
1050 do { \
1051 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1052 check_caches(s); \
1053 } while (0)
1054#endif
1055#endif /* DEBUG_CACHES */
1056
1057/* ----------------------------------------------------------------------
1058 * Solver utility functions
1059 */
1060
7c95608a 1061/* Sets the line (with index i) to the new state 'line_new', and updates
1062 * the cached counts of any affected faces and dots.
1063 * Returns TRUE if this actually changed the line's state. */
1064static int solver_set_line(solver_state *sstate, int i,
1065 enum line_state line_new
121aae4b 1066#ifdef SHOW_WORKING
7c95608a 1067 , const char *reason
121aae4b 1068#endif
7c95608a 1069 )
121aae4b 1070{
1071 game_state *state = sstate->state;
7c95608a 1072 grid *g;
1073 grid_edge *e;
121aae4b 1074
1075 assert(line_new != LINE_UNKNOWN);
1076
1077 check_caches(sstate);
1078
7c95608a 1079 if (state->lines[i] == line_new) {
1080 return FALSE; /* nothing changed */
121aae4b 1081 }
7c95608a 1082 state->lines[i] = line_new;
121aae4b 1083
1084#ifdef SHOW_WORKING
7c95608a 1085 fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
1086 i, line_new == LINE_YES ? "YES" : "NO",
121aae4b 1087 reason);
1088#endif
1089
7c95608a 1090 g = state->game_grid;
1091 e = g->edges + i;
1092
1093 /* Update the cache for both dots and both faces affected by this. */
121aae4b 1094 if (line_new == LINE_YES) {
7c95608a 1095 sstate->dot_yes_count[e->dot1 - g->dots]++;
1096 sstate->dot_yes_count[e->dot2 - g->dots]++;
1097 if (e->face1) {
1098 sstate->face_yes_count[e->face1 - g->faces]++;
1099 }
1100 if (e->face2) {
1101 sstate->face_yes_count[e->face2 - g->faces]++;
1102 }
121aae4b 1103 } else {
7c95608a 1104 sstate->dot_no_count[e->dot1 - g->dots]++;
1105 sstate->dot_no_count[e->dot2 - g->dots]++;
1106 if (e->face1) {
1107 sstate->face_no_count[e->face1 - g->faces]++;
1108 }
1109 if (e->face2) {
1110 sstate->face_no_count[e->face2 - g->faces]++;
1111 }
1112 }
1113
121aae4b 1114 check_caches(sstate);
7c95608a 1115 return TRUE;
121aae4b 1116}
1117
1118#ifdef SHOW_WORKING
7c95608a 1119#define solver_set_line(a, b, c) \
1120 solver_set_line(a, b, c, __FUNCTION__)
121aae4b 1121#endif
1122
1123/*
1124 * Merge two dots due to the existence of an edge between them.
1125 * Updates the dsf tracking equivalence classes, and keeps track of
1126 * the length of path each dot is currently a part of.
1127 * Returns TRUE if the dots were already linked, ie if they are part of a
1128 * closed loop, and false otherwise.
1129 */
7c95608a 1130static int merge_dots(solver_state *sstate, int edge_index)
121aae4b 1131{
1132 int i, j, len;
7c95608a 1133 grid *g = sstate->state->game_grid;
1134 grid_edge *e = g->edges + edge_index;
121aae4b 1135
7c95608a 1136 i = e->dot1 - g->dots;
1137 j = e->dot2 - g->dots;
121aae4b 1138
1139 i = dsf_canonify(sstate->dotdsf, i);
1140 j = dsf_canonify(sstate->dotdsf, j);
1141
1142 if (i == j) {
1143 return TRUE;
1144 } else {
1145 len = sstate->looplen[i] + sstate->looplen[j];
1146 dsf_merge(sstate->dotdsf, i, j);
1147 i = dsf_canonify(sstate->dotdsf, i);
1148 sstate->looplen[i] = len;
1149 return FALSE;
1150 }
1151}
1152
121aae4b 1153/* Merge two lines because the solver has deduced that they must be either
1154 * identical or opposite. Returns TRUE if this is new information, otherwise
1155 * FALSE. */
7c95608a 1156static int merge_lines(solver_state *sstate, int i, int j, int inverse
121aae4b 1157#ifdef SHOW_WORKING
1158 , const char *reason
1159#endif
7c95608a 1160 )
121aae4b 1161{
7c95608a 1162 int inv_tmp;
121aae4b 1163
7c95608a 1164 assert(i < sstate->state->game_grid->num_edges);
1165 assert(j < sstate->state->game_grid->num_edges);
121aae4b 1166
315e47b9 1167 i = edsf_canonify(sstate->linedsf, i, &inv_tmp);
121aae4b 1168 inverse ^= inv_tmp;
315e47b9 1169 j = edsf_canonify(sstate->linedsf, j, &inv_tmp);
121aae4b 1170 inverse ^= inv_tmp;
1171
315e47b9 1172 edsf_merge(sstate->linedsf, i, j, inverse);
121aae4b 1173
1174#ifdef SHOW_WORKING
1175 if (i != j) {
7c95608a 1176 fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
1177 __FUNCTION__, i, j,
121aae4b 1178 inverse ? "inverse " : "", reason);
1179 }
1180#endif
1181 return (i != j);
1182}
1183
1184#ifdef SHOW_WORKING
7c95608a 1185#define merge_lines(a, b, c, d) \
1186 merge_lines(a, b, c, d, __FUNCTION__)
121aae4b 1187#endif
1188
1189/* Count the number of lines of a particular type currently going into the
7c95608a 1190 * given dot. */
1191static int dot_order(const game_state* state, int dot, char line_type)
121aae4b 1192{
1193 int n = 0;
7c95608a 1194 grid *g = state->game_grid;
1195 grid_dot *d = g->dots + dot;
1196 int i;
121aae4b 1197
7c95608a 1198 for (i = 0; i < d->order; i++) {
1199 grid_edge *e = d->edges[i];
1200 if (state->lines[e - g->edges] == line_type)
121aae4b 1201 ++n;
1202 }
121aae4b 1203 return n;
1204}
1205
1206/* Count the number of lines of a particular type currently surrounding the
7c95608a 1207 * given face */
1208static int face_order(const game_state* state, int face, char line_type)
121aae4b 1209{
1210 int n = 0;
7c95608a 1211 grid *g = state->game_grid;
1212 grid_face *f = g->faces + face;
1213 int i;
121aae4b 1214
7c95608a 1215 for (i = 0; i < f->order; i++) {
1216 grid_edge *e = f->edges[i];
1217 if (state->lines[e - g->edges] == line_type)
1218 ++n;
1219 }
121aae4b 1220 return n;
1221}
1222
7c95608a 1223/* Set all lines bordering a dot of type old_type to type new_type
121aae4b 1224 * Return value tells caller whether this function actually did anything */
7c95608a 1225static int dot_setall(solver_state *sstate, int dot,
1226 char old_type, char new_type)
121aae4b 1227{
1228 int retval = FALSE, r;
1229 game_state *state = sstate->state;
7c95608a 1230 grid *g;
1231 grid_dot *d;
1232 int i;
1233
121aae4b 1234 if (old_type == new_type)
1235 return FALSE;
1236
7c95608a 1237 g = state->game_grid;
1238 d = g->dots + dot;
121aae4b 1239
7c95608a 1240 for (i = 0; i < d->order; i++) {
1241 int line_index = d->edges[i] - g->edges;
1242 if (state->lines[line_index] == old_type) {
1243 r = solver_set_line(sstate, line_index, new_type);
1244 assert(r == TRUE);
1245 retval = TRUE;
1246 }
121aae4b 1247 }
121aae4b 1248 return retval;
1249}
1250
7c95608a 1251/* Set all lines bordering a face of type old_type to type new_type */
1252static int face_setall(solver_state *sstate, int face,
1253 char old_type, char new_type)
121aae4b 1254{
7c95608a 1255 int retval = FALSE, r;
121aae4b 1256 game_state *state = sstate->state;
7c95608a 1257 grid *g;
1258 grid_face *f;
1259 int i;
121aae4b 1260
7c95608a 1261 if (old_type == new_type)
1262 return FALSE;
1263
1264 g = state->game_grid;
1265 f = g->faces + face;
121aae4b 1266
7c95608a 1267 for (i = 0; i < f->order; i++) {
1268 int line_index = f->edges[i] - g->edges;
1269 if (state->lines[line_index] == old_type) {
1270 r = solver_set_line(sstate, line_index, new_type);
1271 assert(r == TRUE);
1272 retval = TRUE;
1273 }
1274 }
1275 return retval;
121aae4b 1276}
1277
1278/* ----------------------------------------------------------------------
1279 * Loop generation and clue removal
1280 */
1281
121aae4b 1282static void add_full_clues(game_state *state, random_state *rs)
1283{
7c95608a 1284 signed char *clues = state->clues;
7c95608a 1285 grid *g = state->game_grid;
b760b8bd 1286 char *board = snewn(g->num_faces, char);
1287 int i;
7126ca41 1288
b760b8bd 1289 generate_loop(g, board, rs, NULL, NULL);
7c95608a 1290
1291 /* Fill out all the clues by initialising to 0, then iterating over
1292 * all edges and incrementing each clue as we find edges that border
7126ca41 1293 * between BLACK/WHITE faces. While we're at it, we verify that the
1294 * algorithm does work, and there aren't any GREY faces still there. */
b760b8bd 1295 memset(clues, 0, g->num_faces);
7c95608a 1296 for (i = 0; i < g->num_edges; i++) {
1297 grid_edge *e = g->edges + i;
1298 grid_face *f1 = e->face1;
1299 grid_face *f2 = e->face2;
7126ca41 1300 enum face_colour c1 = FACE_COLOUR(f1);
1301 enum face_colour c2 = FACE_COLOUR(f2);
1302 assert(c1 != FACE_GREY);
1303 assert(c2 != FACE_GREY);
1304 if (c1 != c2) {
7c95608a 1305 if (f1) clues[f1 - g->faces]++;
1306 if (f2) clues[f2 - g->faces]++;
1307 }
121aae4b 1308 }
121aae4b 1309 sfree(board);
1310}
1311
7c95608a 1312
1a739e2f 1313static int game_has_unique_soln(const game_state *state, int diff)
121aae4b 1314{
1315 int ret;
1316 solver_state *sstate_new;
1317 solver_state *sstate = new_solver_state((game_state *)state, diff);
7c95608a 1318
315e47b9 1319 sstate_new = solve_game_rec(sstate);
121aae4b 1320
1321 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1322 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1323
1324 free_solver_state(sstate_new);
1325 free_solver_state(sstate);
1326
1327 return ret;
1328}
1329
7c95608a 1330
121aae4b 1331/* Remove clues one at a time at random. */
7c95608a 1332static game_state *remove_clues(game_state *state, random_state *rs,
1a739e2f 1333 int diff)
121aae4b 1334{
7c95608a 1335 int *face_list;
1336 int num_faces = state->game_grid->num_faces;
121aae4b 1337 game_state *ret = dup_game(state), *saved_ret;
1338 int n;
121aae4b 1339
1340 /* We need to remove some clues. We'll do this by forming a list of all
1341 * available clues, shuffling it, then going along one at a
1342 * time clearing each clue in turn for which doing so doesn't render the
1343 * board unsolvable. */
7c95608a 1344 face_list = snewn(num_faces, int);
1345 for (n = 0; n < num_faces; ++n) {
1346 face_list[n] = n;
121aae4b 1347 }
1348
7c95608a 1349 shuffle(face_list, num_faces, sizeof(int), rs);
121aae4b 1350
7c95608a 1351 for (n = 0; n < num_faces; ++n) {
1352 saved_ret = dup_game(ret);
1353 ret->clues[face_list[n]] = -1;
121aae4b 1354
1355 if (game_has_unique_soln(ret, diff)) {
1356 free_game(saved_ret);
1357 } else {
1358 free_game(ret);
1359 ret = saved_ret;
1360 }
1361 }
7c95608a 1362 sfree(face_list);
121aae4b 1363
1364 return ret;
1365}
1366
7c95608a 1367
121aae4b 1368static char *new_game_desc(game_params *params, random_state *rs,
1369 char **aux, int interactive)
1370{
1371 /* solution and description both use run-length encoding in obvious ways */
cebf0b0d 1372 char *retval, *game_desc, *grid_desc;
7c95608a 1373 grid *g;
1374 game_state *state = snew(game_state);
1375 game_state *state_new;
cebf0b0d 1376
1377 grid_desc = grid_new_desc(grid_types[params->type], params->w, params->h, rs);
1378 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1379
7c95608a 1380 state->clues = snewn(g->num_faces, signed char);
1381 state->lines = snewn(g->num_edges, char);
b6bf0adc 1382 state->line_errors = snewn(g->num_edges, unsigned char);
121aae4b 1383
7c95608a 1384 state->grid_type = params->type;
121aae4b 1385
7c95608a 1386 newboard_please:
121aae4b 1387
7c95608a 1388 memset(state->lines, LINE_UNKNOWN, g->num_edges);
b6bf0adc 1389 memset(state->line_errors, 0, g->num_edges);
121aae4b 1390
1391 state->solved = state->cheated = FALSE;
121aae4b 1392
1393 /* Get a new random solvable board with all its clues filled in. Yes, this
1394 * can loop for ever if the params are suitably unfavourable, but
1395 * preventing games smaller than 4x4 seems to stop this happening */
121aae4b 1396 do {
1397 add_full_clues(state, rs);
1398 } while (!game_has_unique_soln(state, params->diff));
1399
1400 state_new = remove_clues(state, rs, params->diff);
1401 free_game(state);
1402 state = state_new;
1403
7c95608a 1404
121aae4b 1405 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1a739e2f 1406#ifdef SHOW_WORKING
121aae4b 1407 fprintf(stderr, "Rejecting board, it is too easy\n");
1a739e2f 1408#endif
121aae4b 1409 goto newboard_please;
1410 }
1411
cebf0b0d 1412 game_desc = state_to_text(state);
121aae4b 1413
1414 free_game(state);
7c95608a 1415
cebf0b0d 1416 if (grid_desc) {
1417 retval = snewn(strlen(grid_desc) + 1 + strlen(game_desc) + 1, char);
fd66a01d 1418 sprintf(retval, "%s%c%s", grid_desc, (int)GRID_DESC_SEP, game_desc);
cebf0b0d 1419 sfree(grid_desc);
1420 sfree(game_desc);
1421 } else {
1422 retval = game_desc;
1423 }
1424
121aae4b 1425 assert(!validate_desc(params, retval));
1426
1427 return retval;
1428}
1429
1430static game_state *new_game(midend *me, game_params *params, char *desc)
1431{
7c95608a 1432 int i;
121aae4b 1433 game_state *state = snew(game_state);
1434 int empties_to_make = 0;
918a098a 1435 int n,n2;
cebf0b0d 1436 const char *dp;
1437 char *grid_desc;
7c95608a 1438 grid *g;
1515b973 1439 int num_faces, num_edges;
1440
cebf0b0d 1441 grid_desc = extract_grid_desc(&desc);
1442 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1443 if (grid_desc) sfree(grid_desc);
1444
1445 dp = desc;
1446
1515b973 1447 num_faces = g->num_faces;
1448 num_edges = g->num_edges;
121aae4b 1449
7c95608a 1450 state->clues = snewn(num_faces, signed char);
1451 state->lines = snewn(num_edges, char);
b6bf0adc 1452 state->line_errors = snewn(num_edges, unsigned char);
121aae4b 1453
1454 state->solved = state->cheated = FALSE;
1455
7c95608a 1456 state->grid_type = params->type;
1457
1458 for (i = 0; i < num_faces; i++) {
121aae4b 1459 if (empties_to_make) {
1460 empties_to_make--;
7c95608a 1461 state->clues[i] = -1;
121aae4b 1462 continue;
1463 }
1464
1465 assert(*dp);
1466 n = *dp - '0';
918a098a 1467 n2 = *dp - 'A' + 10;
121aae4b 1468 if (n >= 0 && n < 10) {
7c95608a 1469 state->clues[i] = n;
918a098a 1470 } else if (n2 >= 10 && n2 < 36) {
1471 state->clues[i] = n2;
121aae4b 1472 } else {
1473 n = *dp - 'a' + 1;
1474 assert(n > 0);
7c95608a 1475 state->clues[i] = -1;
121aae4b 1476 empties_to_make = n - 1;
1477 }
1478 ++dp;
1479 }
1480
7c95608a 1481 memset(state->lines, LINE_UNKNOWN, num_edges);
b6bf0adc 1482 memset(state->line_errors, 0, num_edges);
121aae4b 1483 return state;
1484}
1485
b6bf0adc 1486/* Calculates the line_errors data, and checks if the current state is a
1487 * solution */
1488static int check_completion(game_state *state)
1489{
1490 grid *g = state->game_grid;
1491 int *dsf;
1492 int num_faces = g->num_faces;
1493 int i;
1494 int infinite_area, finite_area;
1495 int loops_found = 0;
1496 int found_edge_not_in_loop = FALSE;
1497
1498 memset(state->line_errors, 0, g->num_edges);
1499
1500 /* LL implementation of SGT's idea:
1501 * A loop will partition the grid into an inside and an outside.
1502 * If there is more than one loop, the grid will be partitioned into
1503 * even more distinct regions. We can therefore track equivalence of
1504 * faces, by saying that two faces are equivalent when there is a non-YES
1505 * edge between them.
1506 * We could keep track of the number of connected components, by counting
1507 * the number of dsf-merges that aren't no-ops.
1508 * But we're only interested in 3 separate cases:
1509 * no loops, one loop, more than one loop.
1510 *
1511 * No loops: all faces are equivalent to the infinite face.
1512 * One loop: only two equivalence classes - finite and infinite.
1513 * >= 2 loops: there are 2 distinct finite regions.
1514 *
1515 * So we simply make two passes through all the edges.
1516 * In the first pass, we dsf-merge the two faces bordering each non-YES
1517 * edge.
1518 * In the second pass, we look for YES-edges bordering:
1519 * a) two non-equivalent faces.
1520 * b) two non-equivalent faces, and one of them is part of a different
1521 * finite area from the first finite area we've seen.
1522 *
1523 * An occurrence of a) means there is at least one loop.
1524 * An occurrence of b) means there is more than one loop.
1525 * Edges satisfying a) are marked as errors.
1526 *
1527 * While we're at it, we set a flag if we find a YES edge that is not
1528 * part of a loop.
1529 * This information will help decide, if there's a single loop, whether it
1530 * is a candidate for being a solution (that is, all YES edges are part of
1531 * this loop).
1532 *
1533 * If there is a candidate loop, we then go through all clues and check
1534 * they are all satisfied. If so, we have found a solution and we can
1535 * unmark all line_errors.
1536 */
1537
1538 /* Infinite face is at the end - its index is num_faces.
1539 * This macro is just to make this obvious! */
1540 #define INF_FACE num_faces
1541 dsf = snewn(num_faces + 1, int);
1542 dsf_init(dsf, num_faces + 1);
1543
1544 /* First pass */
1545 for (i = 0; i < g->num_edges; i++) {
1546 grid_edge *e = g->edges + i;
1547 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1548 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1549 if (state->lines[i] != LINE_YES)
1550 dsf_merge(dsf, f1, f2);
1551 }
1552
1553 /* Second pass */
1554 infinite_area = dsf_canonify(dsf, INF_FACE);
1555 finite_area = -1;
1556 for (i = 0; i < g->num_edges; i++) {
1557 grid_edge *e = g->edges + i;
1558 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1559 int can1 = dsf_canonify(dsf, f1);
1560 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1561 int can2 = dsf_canonify(dsf, f2);
1562 if (state->lines[i] != LINE_YES) continue;
1563
1564 if (can1 == can2) {
1565 /* Faces are equivalent, so this edge not part of a loop */
1566 found_edge_not_in_loop = TRUE;
1567 continue;
1568 }
1569 state->line_errors[i] = TRUE;
1570 if (loops_found == 0) loops_found = 1;
1571
1572 /* Don't bother with further checks if we've already found 2 loops */
1573 if (loops_found == 2) continue;
1574
1575 if (finite_area == -1) {
1576 /* Found our first finite area */
1577 if (can1 != infinite_area)
1578 finite_area = can1;
1579 else
1580 finite_area = can2;
1581 }
1582
1583 /* Have we found a second area? */
1584 if (finite_area != -1) {
1585 if (can1 != infinite_area && can1 != finite_area) {
1586 loops_found = 2;
1587 continue;
1588 }
1589 if (can2 != infinite_area && can2 != finite_area) {
1590 loops_found = 2;
1591 }
1592 }
1593 }
1594
1595/*
1596 printf("loops_found = %d\n", loops_found);
1597 printf("found_edge_not_in_loop = %s\n",
1598 found_edge_not_in_loop ? "TRUE" : "FALSE");
1599*/
1600
1601 sfree(dsf); /* No longer need the dsf */
1602
1603 /* Have we found a candidate loop? */
1604 if (loops_found == 1 && !found_edge_not_in_loop) {
1605 /* Yes, so check all clues are satisfied */
1606 int found_clue_violation = FALSE;
1607 for (i = 0; i < num_faces; i++) {
1608 int c = state->clues[i];
1609 if (c >= 0) {
1610 if (face_order(state, i, LINE_YES) != c) {
1611 found_clue_violation = TRUE;
1612 break;
1613 }
1614 }
1615 }
1616
1617 if (!found_clue_violation) {
1618 /* The loop is good */
1619 memset(state->line_errors, 0, g->num_edges);
1620 return TRUE; /* No need to bother checking for dot violations */
1621 }
1622 }
1623
1624 /* Check for dot violations */
1625 for (i = 0; i < g->num_dots; i++) {
1626 int yes = dot_order(state, i, LINE_YES);
1627 int unknown = dot_order(state, i, LINE_UNKNOWN);
1628 if ((yes == 1 && unknown == 0) || (yes >= 3)) {
1629 /* violation, so mark all YES edges as errors */
1630 grid_dot *d = g->dots + i;
1631 int j;
1632 for (j = 0; j < d->order; j++) {
1633 int e = d->edges[j] - g->edges;
1634 if (state->lines[e] == LINE_YES)
1635 state->line_errors[e] = TRUE;
1636 }
1637 }
1638 }
1639 return FALSE;
1640}
121aae4b 1641
1642/* ----------------------------------------------------------------------
1643 * Solver logic
1644 *
1645 * Our solver modes operate as follows. Each mode also uses the modes above it.
1646 *
1647 * Easy Mode
1648 * Just implement the rules of the game.
1649 *
315e47b9 1650 * Normal and Tricky Modes
7c95608a 1651 * For each (adjacent) pair of lines through each dot we store a bit for
1652 * whether at least one of them is on and whether at most one is on. (If we
1653 * know both or neither is on that's already stored more directly.)
121aae4b 1654 *
1655 * Advanced Mode
1656 * Use edsf data structure to make equivalence classes of lines that are
1657 * known identical to or opposite to one another.
1658 */
1659
121aae4b 1660
7c95608a 1661/* DLines:
1662 * For general grids, we consider "dlines" to be pairs of lines joined
1663 * at a dot. The lines must be adjacent around the dot, so we can think of
1664 * a dline as being a dot+face combination. Or, a dot+edge combination where
1665 * the second edge is taken to be the next clockwise edge from the dot.
1666 * Original loopy code didn't have this extra restriction of the lines being
1667 * adjacent. From my tests with square grids, this extra restriction seems to
1668 * take little, if anything, away from the quality of the puzzles.
1669 * A dline can be uniquely identified by an edge/dot combination, given that
1670 * a dline-pair always goes clockwise around its common dot. The edge/dot
1671 * combination can be represented by an edge/bool combination - if bool is
1672 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1673 * exactly twice the number of edges in the grid - although the dlines
1674 * spanning the infinite face are not all that useful to the solver.
1675 * Note that, by convention, a dline goes clockwise around its common dot,
1676 * which means the dline goes anti-clockwise around its common face.
1677 */
121aae4b 1678
7c95608a 1679/* Helper functions for obtaining an index into an array of dlines, given
1680 * various information. We assume the grid layout conventions about how
1681 * the various lists are interleaved - see grid_make_consistent() for
1682 * details. */
121aae4b 1683
7c95608a 1684/* i points to the first edge of the dline pair, reading clockwise around
1685 * the dot. */
1686static int dline_index_from_dot(grid *g, grid_dot *d, int i)
121aae4b 1687{
7c95608a 1688 grid_edge *e = d->edges[i];
121aae4b 1689 int ret;
7c95608a 1690#ifdef DEBUG_DLINES
1691 grid_edge *e2;
1692 int i2 = i+1;
1693 if (i2 == d->order) i2 = 0;
1694 e2 = d->edges[i2];
1695#endif
1696 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1697#ifdef DEBUG_DLINES
1698 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1699 (int)(d - g->dots), i, (int)(e - g->edges),
1700 (int)(e2 - g->edges), ret);
121aae4b 1701#endif
1702 return ret;
1703}
7c95608a 1704/* i points to the second edge of the dline pair, reading clockwise around
1705 * the face. That is, the edges of the dline, starting at edge{i}, read
1706 * anti-clockwise around the face. By layout conventions, the common dot
1707 * of the dline will be f->dots[i] */
1708static int dline_index_from_face(grid *g, grid_face *f, int i)
121aae4b 1709{
7c95608a 1710 grid_edge *e = f->edges[i];
1711 grid_dot *d = f->dots[i];
121aae4b 1712 int ret;
7c95608a 1713#ifdef DEBUG_DLINES
1714 grid_edge *e2;
1715 int i2 = i - 1;
1716 if (i2 < 0) i2 += f->order;
1717 e2 = f->edges[i2];
1718#endif
1719 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1720#ifdef DEBUG_DLINES
1721 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1722 (int)(f - g->faces), i, (int)(e - g->edges),
1723 (int)(e2 - g->edges), ret);
121aae4b 1724#endif
1725 return ret;
1726}
7c95608a 1727static int is_atleastone(const char *dline_array, int index)
121aae4b 1728{
7c95608a 1729 return BIT_SET(dline_array[index], 0);
121aae4b 1730}
7c95608a 1731static int set_atleastone(char *dline_array, int index)
121aae4b 1732{
7c95608a 1733 return SET_BIT(dline_array[index], 0);
121aae4b 1734}
7c95608a 1735static int is_atmostone(const char *dline_array, int index)
121aae4b 1736{
7c95608a 1737 return BIT_SET(dline_array[index], 1);
1738}
1739static int set_atmostone(char *dline_array, int index)
1740{
1741 return SET_BIT(dline_array[index], 1);
121aae4b 1742}
121aae4b 1743
1744static void array_setall(char *array, char from, char to, int len)
1745{
1746 char *p = array, *p_old = p;
1747 int len_remaining = len;
1748
1749 while ((p = memchr(p, from, len_remaining))) {
1750 *p = to;
1751 len_remaining -= p - p_old;
1752 p_old = p;
1753 }
1754}
6193da8d 1755
7c95608a 1756/* Helper, called when doing dline dot deductions, in the case where we
1757 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1758 * them (because of dline atmostone/atleastone).
1759 * On entry, edge points to the first of these two UNKNOWNs. This function
1760 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1761 * and set their corresponding dline to atleastone. (Setting atmostone
1762 * already happens in earlier dline deductions) */
1763static int dline_set_opp_atleastone(solver_state *sstate,
1764 grid_dot *d, int edge)
121aae4b 1765{
7c95608a 1766 game_state *state = sstate->state;
1767 grid *g = state->game_grid;
1768 int N = d->order;
1769 int opp, opp2;
1770 for (opp = 0; opp < N; opp++) {
1771 int opp_dline_index;
1772 if (opp == edge || opp == edge+1 || opp == edge-1)
1773 continue;
1774 if (opp == 0 && edge == N-1)
1775 continue;
1776 if (opp == N-1 && edge == 0)
1777 continue;
1778 opp2 = opp + 1;
1779 if (opp2 == N) opp2 = 0;
1780 /* Check if opp, opp2 point to LINE_UNKNOWNs */
1781 if (state->lines[d->edges[opp] - g->edges] != LINE_UNKNOWN)
1782 continue;
1783 if (state->lines[d->edges[opp2] - g->edges] != LINE_UNKNOWN)
1784 continue;
1785 /* Found opposite UNKNOWNS and they're next to each other */
1786 opp_dline_index = dline_index_from_dot(g, d, opp);
315e47b9 1787 return set_atleastone(sstate->dlines, opp_dline_index);
121aae4b 1788 }
7c95608a 1789 return FALSE;
121aae4b 1790}
6193da8d 1791
121aae4b 1792
7c95608a 1793/* Set pairs of lines around this face which are known to be identical, to
121aae4b 1794 * the given line_state */
7c95608a 1795static int face_setall_identical(solver_state *sstate, int face_index,
1796 enum line_state line_new)
121aae4b 1797{
1798 /* can[dir] contains the canonical line associated with the line in
1799 * direction dir from the square in question. Similarly inv[dir] is
1800 * whether or not the line in question is inverse to its canonical
1801 * element. */
121aae4b 1802 int retval = FALSE;
7c95608a 1803 game_state *state = sstate->state;
1804 grid *g = state->game_grid;
1805 grid_face *f = g->faces + face_index;
1806 int N = f->order;
1807 int i, j;
1808 int can1, can2, inv1, inv2;
6193da8d 1809
7c95608a 1810 for (i = 0; i < N; i++) {
1811 int line1_index = f->edges[i] - g->edges;
1812 if (state->lines[line1_index] != LINE_UNKNOWN)
1813 continue;
1814 for (j = i + 1; j < N; j++) {
1815 int line2_index = f->edges[j] - g->edges;
1816 if (state->lines[line2_index] != LINE_UNKNOWN)
121aae4b 1817 continue;
6193da8d 1818
7c95608a 1819 /* Found two UNKNOWNS */
315e47b9 1820 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
1821 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
7c95608a 1822 if (can1 == can2 && inv1 == inv2) {
1823 solver_set_line(sstate, line1_index, line_new);
1824 solver_set_line(sstate, line2_index, line_new);
6193da8d 1825 }
1826 }
6193da8d 1827 }
121aae4b 1828 return retval;
1829}
1830
7c95608a 1831/* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
1832 * return the edge indices into e. */
1833static void find_unknowns(game_state *state,
1834 grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
1835 int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
1836 int *e /* Returned edge indices */)
1837{
1838 int c = 0;
1839 grid *g = state->game_grid;
1840 while (c < expected_count) {
1841 int line_index = *edge_list - g->edges;
1842 if (state->lines[line_index] == LINE_UNKNOWN) {
1843 e[c] = line_index;
1844 c++;
6193da8d 1845 }
7c95608a 1846 ++edge_list;
6193da8d 1847 }
6193da8d 1848}
1849
7c95608a 1850/* If we have a list of edges, and we know whether the number of YESs should
1851 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
1852 * linedsf deductions. This can be used for both face and dot deductions.
1853 * Returns the difficulty level of the next solver that should be used,
1854 * or DIFF_MAX if no progress was made. */
1855static int parity_deductions(solver_state *sstate,
1856 grid_edge **edge_list, /* Edge list (from a face or a dot) */
1857 int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
1858 int unknown_count)
6193da8d 1859{
121aae4b 1860 game_state *state = sstate->state;
7c95608a 1861 int diff = DIFF_MAX;
315e47b9 1862 int *linedsf = sstate->linedsf;
7c95608a 1863
1864 if (unknown_count == 2) {
1865 /* Lines are known alike/opposite, depending on inv. */
1866 int e[2];
1867 find_unknowns(state, edge_list, 2, e);
1868 if (merge_lines(sstate, e[0], e[1], total_parity))
1869 diff = min(diff, DIFF_HARD);
1870 } else if (unknown_count == 3) {
1871 int e[3];
1872 int can[3]; /* canonical edges */
1873 int inv[3]; /* whether can[x] is inverse to e[x] */
1874 find_unknowns(state, edge_list, 3, e);
1875 can[0] = edsf_canonify(linedsf, e[0], inv);
1876 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1877 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1878 if (can[0] == can[1]) {
1879 if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
1880 LINE_YES : LINE_NO))
1881 diff = min(diff, DIFF_EASY);
1882 }
1883 if (can[0] == can[2]) {
1884 if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
1885 LINE_YES : LINE_NO))
1886 diff = min(diff, DIFF_EASY);
1887 }
1888 if (can[1] == can[2]) {
1889 if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
1890 LINE_YES : LINE_NO))
1891 diff = min(diff, DIFF_EASY);
1892 }
1893 } else if (unknown_count == 4) {
1894 int e[4];
1895 int can[4]; /* canonical edges */
1896 int inv[4]; /* whether can[x] is inverse to e[x] */
1897 find_unknowns(state, edge_list, 4, e);
1898 can[0] = edsf_canonify(linedsf, e[0], inv);
1899 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1900 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1901 can[3] = edsf_canonify(linedsf, e[3], inv+3);
1902 if (can[0] == can[1]) {
1903 if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
1904 diff = min(diff, DIFF_HARD);
1905 } else if (can[0] == can[2]) {
1906 if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
1907 diff = min(diff, DIFF_HARD);
1908 } else if (can[0] == can[3]) {
1909 if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
1910 diff = min(diff, DIFF_HARD);
1911 } else if (can[1] == can[2]) {
1912 if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
1913 diff = min(diff, DIFF_HARD);
1914 } else if (can[1] == can[3]) {
1915 if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
1916 diff = min(diff, DIFF_HARD);
1917 } else if (can[2] == can[3]) {
1918 if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
1919 diff = min(diff, DIFF_HARD);
6193da8d 1920 }
1921 }
7c95608a 1922 return diff;
6193da8d 1923}
1924
7c95608a 1925
121aae4b 1926/*
7c95608a 1927 * These are the main solver functions.
121aae4b 1928 *
1929 * Their return values are diff values corresponding to the lowest mode solver
1930 * that would notice the work that they have done. For example if the normal
1931 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
1932 * easy mode solver might be able to make progress using that. It doesn't make
1933 * sense for one of them to return a diff value higher than that of the
7c95608a 1934 * function itself.
121aae4b 1935 *
1936 * Each function returns the lowest value it can, as early as possible, in
1937 * order to try and pass as much work as possible back to the lower level
1938 * solvers which progress more quickly.
1939 */
6193da8d 1940
121aae4b 1941/* PROPOSED NEW DESIGN:
1942 * We have a work queue consisting of 'events' notifying us that something has
1943 * happened that a particular solver mode might be interested in. For example
1944 * the hard mode solver might do something that helps the normal mode solver at
1945 * dot [x,y] in which case it will enqueue an event recording this fact. Then
1946 * we pull events off the work queue, and hand each in turn to the solver that
1947 * is interested in them. If a solver reports that it failed we pass the same
1948 * event on to progressively more advanced solvers and the loop detector. Once
1949 * we've exhausted an event, or it has helped us progress, we drop it and
1950 * continue to the next one. The events are sorted first in order of solver
1951 * complexity (easy first) then order of insertion (oldest first).
1952 * Once we run out of events we loop over each permitted solver in turn
1953 * (easiest first) until either a deduction is made (and an event therefore
1954 * emerges) or no further deductions can be made (in which case we've failed).
1955 *
7c95608a 1956 * QUESTIONS:
121aae4b 1957 * * How do we 'loop over' a solver when both dots and squares are concerned.
1958 * Answer: first all squares then all dots.
1959 */
1960
315e47b9 1961static int trivial_deductions(solver_state *sstate)
6193da8d 1962{
7c95608a 1963 int i, current_yes, current_no;
1964 game_state *state = sstate->state;
1965 grid *g = state->game_grid;
1a739e2f 1966 int diff = DIFF_MAX;
6193da8d 1967
7c95608a 1968 /* Per-face deductions */
1969 for (i = 0; i < g->num_faces; i++) {
1970 grid_face *f = g->faces + i;
1971
1972 if (sstate->face_solved[i])
121aae4b 1973 continue;
6193da8d 1974
7c95608a 1975 current_yes = sstate->face_yes_count[i];
1976 current_no = sstate->face_no_count[i];
c0eb17ce 1977
7c95608a 1978 if (current_yes + current_no == f->order) {
1979 sstate->face_solved[i] = TRUE;
121aae4b 1980 continue;
1981 }
6193da8d 1982
7c95608a 1983 if (state->clues[i] < 0)
121aae4b 1984 continue;
6193da8d 1985
dba1fdaf 1986 /*
1987 * This code checks whether the numeric clue on a face is so
1988 * large as to permit all its remaining LINE_UNKNOWNs to be
1989 * filled in as LINE_YES, or alternatively so small as to
1990 * permit them all to be filled in as LINE_NO.
1991 */
1992
7c95608a 1993 if (state->clues[i] < current_yes) {
121aae4b 1994 sstate->solver_status = SOLVER_MISTAKE;
1995 return DIFF_EASY;
1996 }
7c95608a 1997 if (state->clues[i] == current_yes) {
1998 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
121aae4b 1999 diff = min(diff, DIFF_EASY);
7c95608a 2000 sstate->face_solved[i] = TRUE;
121aae4b 2001 continue;
2002 }
c0eb17ce 2003
7c95608a 2004 if (f->order - state->clues[i] < current_no) {
121aae4b 2005 sstate->solver_status = SOLVER_MISTAKE;
2006 return DIFF_EASY;
2007 }
7c95608a 2008 if (f->order - state->clues[i] == current_no) {
2009 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
121aae4b 2010 diff = min(diff, DIFF_EASY);
7c95608a 2011 sstate->face_solved[i] = TRUE;
121aae4b 2012 continue;
2013 }
dba1fdaf 2014
2015 if (f->order - state->clues[i] == current_no + 1 &&
2016 f->order - current_yes - current_no > 2) {
2017 /*
2018 * One small refinement to the above: we also look for any
2019 * adjacent pair of LINE_UNKNOWNs around the face with
2020 * some LINE_YES incident on it from elsewhere. If we find
2021 * one, then we know that pair of LINE_UNKNOWNs can't
2022 * _both_ be LINE_YES, and hence that pushes us one line
2023 * closer to being able to determine all the rest.
2024 */
2025 int j, k, e1, e2, e, d;
2026
2027 for (j = 0; j < f->order; j++) {
2028 e1 = f->edges[j] - g->edges;
2029 e2 = f->edges[j+1 < f->order ? j+1 : 0] - g->edges;
2030
2031 if (g->edges[e1].dot1 == g->edges[e2].dot1 ||
2032 g->edges[e1].dot1 == g->edges[e2].dot2) {
2033 d = g->edges[e1].dot1 - g->dots;
2034 } else {
2035 assert(g->edges[e1].dot2 == g->edges[e2].dot1 ||
2036 g->edges[e1].dot2 == g->edges[e2].dot2);
2037 d = g->edges[e1].dot2 - g->dots;
2038 }
2039
2040 if (state->lines[e1] == LINE_UNKNOWN &&
2041 state->lines[e2] == LINE_UNKNOWN) {
2042 for (k = 0; k < g->dots[d].order; k++) {
2043 int e = g->dots[d].edges[k] - g->edges;
2044 if (state->lines[e] == LINE_YES)
2045 goto found; /* multi-level break */
2046 }
2047 }
2048 }
2049 continue;
2050
2051 found:
2052 /*
2053 * If we get here, we've found such a pair of edges, and
2054 * they're e1 and e2.
2055 */
2056 for (j = 0; j < f->order; j++) {
2057 e = f->edges[j] - g->edges;
2058 if (state->lines[e] == LINE_UNKNOWN && e != e1 && e != e2) {
2059 int r = solver_set_line(sstate, e, LINE_YES);
2060 assert(r);
2061 diff = min(diff, DIFF_EASY);
2062 }
2063 }
2064 }
121aae4b 2065 }
6193da8d 2066
121aae4b 2067 check_caches(sstate);
6193da8d 2068
121aae4b 2069 /* Per-dot deductions */
7c95608a 2070 for (i = 0; i < g->num_dots; i++) {
2071 grid_dot *d = g->dots + i;
2072 int yes, no, unknown;
2073
2074 if (sstate->dot_solved[i])
121aae4b 2075 continue;
c0eb17ce 2076
7c95608a 2077 yes = sstate->dot_yes_count[i];
2078 no = sstate->dot_no_count[i];
2079 unknown = d->order - yes - no;
2080
2081 if (yes == 0) {
2082 if (unknown == 0) {
2083 sstate->dot_solved[i] = TRUE;
2084 } else if (unknown == 1) {
2085 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
121aae4b 2086 diff = min(diff, DIFF_EASY);
7c95608a 2087 sstate->dot_solved[i] = TRUE;
2088 }
2089 } else if (yes == 1) {
2090 if (unknown == 0) {
121aae4b 2091 sstate->solver_status = SOLVER_MISTAKE;
2092 return DIFF_EASY;
7c95608a 2093 } else if (unknown == 1) {
2094 dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
2095 diff = min(diff, DIFF_EASY);
2096 }
2097 } else if (yes == 2) {
2098 if (unknown > 0) {
2099 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2100 diff = min(diff, DIFF_EASY);
2101 }
2102 sstate->dot_solved[i] = TRUE;
2103 } else {
2104 sstate->solver_status = SOLVER_MISTAKE;
2105 return DIFF_EASY;
6193da8d 2106 }
2107 }
6193da8d 2108
121aae4b 2109 check_caches(sstate);
6193da8d 2110
121aae4b 2111 return diff;
6193da8d 2112}
2113
315e47b9 2114static int dline_deductions(solver_state *sstate)
6193da8d 2115{
121aae4b 2116 game_state *state = sstate->state;
7c95608a 2117 grid *g = state->game_grid;
315e47b9 2118 char *dlines = sstate->dlines;
7c95608a 2119 int i;
1a739e2f 2120 int diff = DIFF_MAX;
6193da8d 2121
7c95608a 2122 /* ------ Face deductions ------ */
2123
2124 /* Given a set of dline atmostone/atleastone constraints, need to figure
2125 * out if we can deduce any further info. For more general faces than
2126 * squares, this turns out to be a tricky problem.
2127 * The approach taken here is to define (per face) NxN matrices:
2128 * "maxs" and "mins".
2129 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2130 * for the possible number of edges that are YES between positions j and k
2131 * going clockwise around the face. Can think of j and k as marking dots
2132 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2133 * edge1 joins dot1 to dot2 etc).
2134 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2135 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2136 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2137 * the dline atmostone/atleastone status for edges j and j+1.
2138 *
2139 * Then we calculate the remaining entries recursively. We definitely
2140 * know that
2141 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2142 * This is because any valid placement of YESs between j and k must give
2143 * a valid placement between j and u, and also between u and k.
2144 * I believe it's sufficient to use just the two values of u:
2145 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2146 * are rigorous, even if they might not be best-possible.
2147 *
2148 * Once we have maxs and mins calculated, we can make inferences about
2149 * each dline{j,j+1} by looking at the possible complementary edge-counts
2150 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2151 * As well as dlines, we can make similar inferences about single edges.
2152 * For example, consider a pentagon with clue 3, and we know at most one
2153 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2154 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2155 * that final edge would have to be YES to make the count up to 3.
2156 */
121aae4b 2157
7c95608a 2158 /* Much quicker to allocate arrays on the stack than the heap, so
2159 * define the largest possible face size, and base our array allocations
2160 * on that. We check this with an assertion, in case someone decides to
2161 * make a grid which has larger faces than this. Note, this algorithm
2162 * could get quite expensive if there are many large faces. */
918a098a 2163#define MAX_FACE_SIZE 12
7c95608a 2164
2165 for (i = 0; i < g->num_faces; i++) {
2166 int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
2167 int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
2168 grid_face *f = g->faces + i;
2169 int N = f->order;
2170 int j,m;
2171 int clue = state->clues[i];
2172 assert(N <= MAX_FACE_SIZE);
2173 if (sstate->face_solved[i])
6193da8d 2174 continue;
7c95608a 2175 if (clue < 0) continue;
2176
2177 /* Calculate the (j,j+1) entries */
2178 for (j = 0; j < N; j++) {
2179 int edge_index = f->edges[j] - g->edges;
2180 int dline_index;
2181 enum line_state line1 = state->lines[edge_index];
2182 enum line_state line2;
2183 int tmp;
2184 int k = j + 1;
2185 if (k >= N) k = 0;
2186 maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
2187 mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
2188 /* Calculate the (j,j+2) entries */
2189 dline_index = dline_index_from_face(g, f, k);
2190 edge_index = f->edges[k] - g->edges;
2191 line2 = state->lines[edge_index];
2192 k++;
2193 if (k >= N) k = 0;
2194
2195 /* max */
2196 tmp = 2;
2197 if (line1 == LINE_NO) tmp--;
2198 if (line2 == LINE_NO) tmp--;
2199 if (tmp == 2 && is_atmostone(dlines, dline_index))
2200 tmp = 1;
2201 maxs[j][k] = tmp;
2202
2203 /* min */
2204 tmp = 0;
2205 if (line1 == LINE_YES) tmp++;
2206 if (line2 == LINE_YES) tmp++;
2207 if (tmp == 0 && is_atleastone(dlines, dline_index))
2208 tmp = 1;
2209 mins[j][k] = tmp;
2210 }
121aae4b 2211
7c95608a 2212 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2213 for (m = 3; m < N; m++) {
2214 for (j = 0; j < N; j++) {
2215 int k = j + m;
2216 int u = j + 1;
2217 int v = j + 2;
2218 int tmp;
2219 if (k >= N) k -= N;
2220 if (u >= N) u -= N;
2221 if (v >= N) v -= N;
2222 maxs[j][k] = maxs[j][u] + maxs[u][k];
2223 mins[j][k] = mins[j][u] + mins[u][k];
2224 tmp = maxs[j][v] + maxs[v][k];
2225 maxs[j][k] = min(maxs[j][k], tmp);
2226 tmp = mins[j][v] + mins[v][k];
2227 mins[j][k] = max(mins[j][k], tmp);
2228 }
2229 }
121aae4b 2230
7c95608a 2231 /* See if we can make any deductions */
2232 for (j = 0; j < N; j++) {
2233 int k;
2234 grid_edge *e = f->edges[j];
2235 int line_index = e - g->edges;
2236 int dline_index;
121aae4b 2237
7c95608a 2238 if (state->lines[line_index] != LINE_UNKNOWN)
2239 continue;
2240 k = j + 1;
2241 if (k >= N) k = 0;
121aae4b 2242
7c95608a 2243 /* minimum YESs in the complement of this edge */
2244 if (mins[k][j] > clue) {
2245 sstate->solver_status = SOLVER_MISTAKE;
2246 return DIFF_EASY;
2247 }
2248 if (mins[k][j] == clue) {
2249 /* setting this edge to YES would make at least
2250 * (clue+1) edges - contradiction */
2251 solver_set_line(sstate, line_index, LINE_NO);
2252 diff = min(diff, DIFF_EASY);
2253 }
2254 if (maxs[k][j] < clue - 1) {
2255 sstate->solver_status = SOLVER_MISTAKE;
2256 return DIFF_EASY;
2257 }
2258 if (maxs[k][j] == clue - 1) {
2259 /* Only way to satisfy the clue is to set edge{j} as YES */
2260 solver_set_line(sstate, line_index, LINE_YES);
2261 diff = min(diff, DIFF_EASY);
2262 }
2263
315e47b9 2264 /* More advanced deduction that allows propagation along diagonal
2265 * chains of faces connected by dots, for example, 3-2-...-2-3
2266 * in square grids. */
2267 if (sstate->diff >= DIFF_TRICKY) {
2268 /* Now see if we can make dline deduction for edges{j,j+1} */
2269 e = f->edges[k];
2270 if (state->lines[e - g->edges] != LINE_UNKNOWN)
2271 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2272 * Dlines where one of the edges is known, are handled in the
2273 * dot-deductions */
2274 continue;
2275
2276 dline_index = dline_index_from_face(g, f, k);
2277 k++;
2278 if (k >= N) k = 0;
2279
2280 /* minimum YESs in the complement of this dline */
2281 if (mins[k][j] > clue - 2) {
2282 /* Adding 2 YESs would break the clue */
2283 if (set_atmostone(dlines, dline_index))
2284 diff = min(diff, DIFF_NORMAL);
2285 }
2286 /* maximum YESs in the complement of this dline */
2287 if (maxs[k][j] < clue) {
2288 /* Adding 2 NOs would mean not enough YESs */
2289 if (set_atleastone(dlines, dline_index))
2290 diff = min(diff, DIFF_NORMAL);
2291 }
7c95608a 2292 }
6193da8d 2293 }
6193da8d 2294 }
2295
121aae4b 2296 if (diff < DIFF_NORMAL)
2297 return diff;
6193da8d 2298
7c95608a 2299 /* ------ Dot deductions ------ */
6193da8d 2300
7c95608a 2301 for (i = 0; i < g->num_dots; i++) {
2302 grid_dot *d = g->dots + i;
2303 int N = d->order;
2304 int yes, no, unknown;
2305 int j;
2306 if (sstate->dot_solved[i])
2307 continue;
2308 yes = sstate->dot_yes_count[i];
2309 no = sstate->dot_no_count[i];
2310 unknown = N - yes - no;
2311
2312 for (j = 0; j < N; j++) {
2313 int k;
2314 int dline_index;
2315 int line1_index, line2_index;
2316 enum line_state line1, line2;
2317 k = j + 1;
2318 if (k >= N) k = 0;
2319 dline_index = dline_index_from_dot(g, d, j);
2320 line1_index = d->edges[j] - g->edges;
2321 line2_index = d->edges[k] - g->edges;
2322 line1 = state->lines[line1_index];
2323 line2 = state->lines[line2_index];
2324
2325 /* Infer dline state from line state */
2326 if (line1 == LINE_NO || line2 == LINE_NO) {
2327 if (set_atmostone(dlines, dline_index))
2328 diff = min(diff, DIFF_NORMAL);
2329 }
2330 if (line1 == LINE_YES || line2 == LINE_YES) {
2331 if (set_atleastone(dlines, dline_index))
2332 diff = min(diff, DIFF_NORMAL);
2333 }
2334 /* Infer line state from dline state */
2335 if (is_atmostone(dlines, dline_index)) {
2336 if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
2337 solver_set_line(sstate, line2_index, LINE_NO);
2338 diff = min(diff, DIFF_EASY);
2339 }
2340 if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
2341 solver_set_line(sstate, line1_index, LINE_NO);
2342 diff = min(diff, DIFF_EASY);
2343 }
2344 }
2345 if (is_atleastone(dlines, dline_index)) {
2346 if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
2347 solver_set_line(sstate, line2_index, LINE_YES);
2348 diff = min(diff, DIFF_EASY);
2349 }
2350 if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
2351 solver_set_line(sstate, line1_index, LINE_YES);
2352 diff = min(diff, DIFF_EASY);
2353 }
2354 }
2355 /* Deductions that depend on the numbers of lines.
2356 * Only bother if both lines are UNKNOWN, otherwise the
2357 * easy-mode solver (or deductions above) would have taken
2358 * care of it. */
2359 if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
2360 continue;
6193da8d 2361
7c95608a 2362 if (yes == 0 && unknown == 2) {
2363 /* Both these unknowns must be identical. If we know
2364 * atmostone or atleastone, we can make progress. */
2365 if (is_atmostone(dlines, dline_index)) {
2366 solver_set_line(sstate, line1_index, LINE_NO);
2367 solver_set_line(sstate, line2_index, LINE_NO);
2368 diff = min(diff, DIFF_EASY);
2369 }
2370 if (is_atleastone(dlines, dline_index)) {
2371 solver_set_line(sstate, line1_index, LINE_YES);
2372 solver_set_line(sstate, line2_index, LINE_YES);
2373 diff = min(diff, DIFF_EASY);
2374 }
2375 }
2376 if (yes == 1) {
2377 if (set_atmostone(dlines, dline_index))
2378 diff = min(diff, DIFF_NORMAL);
2379 if (unknown == 2) {
2380 if (set_atleastone(dlines, dline_index))
2381 diff = min(diff, DIFF_NORMAL);
2382 }
121aae4b 2383 }
6193da8d 2384
315e47b9 2385 /* More advanced deduction that allows propagation along diagonal
2386 * chains of faces connected by dots, for example: 3-2-...-2-3
2387 * in square grids. */
2388 if (sstate->diff >= DIFF_TRICKY) {
2389 /* If we have atleastone set for this dline, infer
2390 * atmostone for each "opposite" dline (that is, each
2391 * dline without edges in common with this one).
2392 * Again, this test is only worth doing if both these
2393 * lines are UNKNOWN. For if one of these lines were YES,
2394 * the (yes == 1) test above would kick in instead. */
2395 if (is_atleastone(dlines, dline_index)) {
2396 int opp;
2397 for (opp = 0; opp < N; opp++) {
2398 int opp_dline_index;
2399 if (opp == j || opp == j+1 || opp == j-1)
2400 continue;
2401 if (j == 0 && opp == N-1)
2402 continue;
2403 if (j == N-1 && opp == 0)
2404 continue;
2405 opp_dline_index = dline_index_from_dot(g, d, opp);
2406 if (set_atmostone(dlines, opp_dline_index))
2407 diff = min(diff, DIFF_NORMAL);
2408 }
2409 if (yes == 0 && is_atmostone(dlines, dline_index)) {
2410 /* This dline has *exactly* one YES and there are no
2411 * other YESs. This allows more deductions. */
2412 if (unknown == 3) {
2413 /* Third unknown must be YES */
2414 for (opp = 0; opp < N; opp++) {
2415 int opp_index;
2416 if (opp == j || opp == k)
2417 continue;
2418 opp_index = d->edges[opp] - g->edges;
2419 if (state->lines[opp_index] == LINE_UNKNOWN) {
2420 solver_set_line(sstate, opp_index,
2421 LINE_YES);
2422 diff = min(diff, DIFF_EASY);
2423 }
121aae4b 2424 }
315e47b9 2425 } else if (unknown == 4) {
2426 /* Exactly one of opposite UNKNOWNS is YES. We've
2427 * already set atmostone, so set atleastone as
2428 * well.
2429 */
2430 if (dline_set_opp_atleastone(sstate, d, j))
2431 diff = min(diff, DIFF_NORMAL);
121aae4b 2432 }
2433 }
121aae4b 2434 }
6193da8d 2435 }
6193da8d 2436 }
121aae4b 2437 }
121aae4b 2438 return diff;
6193da8d 2439}
2440
315e47b9 2441static int linedsf_deductions(solver_state *sstate)
6193da8d 2442{
121aae4b 2443 game_state *state = sstate->state;
7c95608a 2444 grid *g = state->game_grid;
315e47b9 2445 char *dlines = sstate->dlines;
7c95608a 2446 int i;
1a739e2f 2447 int diff = DIFF_MAX;
7c95608a 2448 int diff_tmp;
121aae4b 2449
7c95608a 2450 /* ------ Face deductions ------ */
6193da8d 2451
7c95608a 2452 /* A fully-general linedsf deduction seems overly complicated
2453 * (I suspect the problem is NP-complete, though in practice it might just
2454 * be doable because faces are limited in size).
2455 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2456 * known to be identical. If setting them both to YES (or NO) would break
2457 * the clue, set them to NO (or YES). */
121aae4b 2458
7c95608a 2459 for (i = 0; i < g->num_faces; i++) {
2460 int N, yes, no, unknown;
2461 int clue;
6193da8d 2462
7c95608a 2463 if (sstate->face_solved[i])
121aae4b 2464 continue;
7c95608a 2465 clue = state->clues[i];
2466 if (clue < 0)
121aae4b 2467 continue;
6193da8d 2468
7c95608a 2469 N = g->faces[i].order;
2470 yes = sstate->face_yes_count[i];
2471 if (yes + 1 == clue) {
2472 if (face_setall_identical(sstate, i, LINE_NO))
2473 diff = min(diff, DIFF_EASY);
121aae4b 2474 }
7c95608a 2475 no = sstate->face_no_count[i];
2476 if (no + 1 == N - clue) {
2477 if (face_setall_identical(sstate, i, LINE_YES))
2478 diff = min(diff, DIFF_EASY);
6193da8d 2479 }
6193da8d 2480
7c95608a 2481 /* Reload YES count, it might have changed */
2482 yes = sstate->face_yes_count[i];
2483 unknown = N - no - yes;
2484
2485 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2486 * parity of lines. */
2487 diff_tmp = parity_deductions(sstate, g->faces[i].edges,
2488 (clue - yes) % 2, unknown);
2489 diff = min(diff, diff_tmp);
2490 }
2491
2492 /* ------ Dot deductions ------ */
2493 for (i = 0; i < g->num_dots; i++) {
2494 grid_dot *d = g->dots + i;
2495 int N = d->order;
2496 int j;
2497 int yes, no, unknown;
2498 /* Go through dlines, and do any dline<->linedsf deductions wherever
2499 * we find two UNKNOWNS. */
2500 for (j = 0; j < N; j++) {
2501 int dline_index = dline_index_from_dot(g, d, j);
2502 int line1_index;
2503 int line2_index;
2504 int can1, can2, inv1, inv2;
2505 int j2;
2506 line1_index = d->edges[j] - g->edges;
2507 if (state->lines[line1_index] != LINE_UNKNOWN)
121aae4b 2508 continue;
7c95608a 2509 j2 = j + 1;
2510 if (j2 == N) j2 = 0;
2511 line2_index = d->edges[j2] - g->edges;
2512 if (state->lines[line2_index] != LINE_UNKNOWN)
121aae4b 2513 continue;
7c95608a 2514 /* Infer dline flags from linedsf */
315e47b9 2515 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
2516 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
7c95608a 2517 if (can1 == can2 && inv1 != inv2) {
2518 /* These are opposites, so set dline atmostone/atleastone */
2519 if (set_atmostone(dlines, dline_index))
2520 diff = min(diff, DIFF_NORMAL);
2521 if (set_atleastone(dlines, dline_index))
2522 diff = min(diff, DIFF_NORMAL);
121aae4b 2523 continue;
7c95608a 2524 }
2525 /* Infer linedsf from dline flags */
2526 if (is_atmostone(dlines, dline_index)
2527 && is_atleastone(dlines, dline_index)) {
2528 if (merge_lines(sstate, line1_index, line2_index, 1))
121aae4b 2529 diff = min(diff, DIFF_HARD);
121aae4b 2530 }
2531 }
7c95608a 2532
2533 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2534 * parity of lines. */
2535 yes = sstate->dot_yes_count[i];
2536 no = sstate->dot_no_count[i];
2537 unknown = N - yes - no;
2538 diff_tmp = parity_deductions(sstate, d->edges,
2539 yes % 2, unknown);
2540 diff = min(diff, diff_tmp);
121aae4b 2541 }
6193da8d 2542
7c95608a 2543 /* ------ Edge dsf deductions ------ */
2544
2545 /* If the state of a line is known, deduce the state of its canonical line
2546 * too, and vice versa. */
2547 for (i = 0; i < g->num_edges; i++) {
2548 int can, inv;
2549 enum line_state s;
315e47b9 2550 can = edsf_canonify(sstate->linedsf, i, &inv);
7c95608a 2551 if (can == i)
2552 continue;
2553 s = sstate->state->lines[can];
2554 if (s != LINE_UNKNOWN) {
2555 if (solver_set_line(sstate, i, inv ? OPP(s) : s))
2556 diff = min(diff, DIFF_EASY);
2557 } else {
2558 s = sstate->state->lines[i];
2559 if (s != LINE_UNKNOWN) {
2560 if (solver_set_line(sstate, can, inv ? OPP(s) : s))
121aae4b 2561 diff = min(diff, DIFF_EASY);
2562 }
2563 }
2564 }
6193da8d 2565
121aae4b 2566 return diff;
2567}
6193da8d 2568
121aae4b 2569static int loop_deductions(solver_state *sstate)
2570{
2571 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2572 game_state *state = sstate->state;
7c95608a 2573 grid *g = state->game_grid;
2574 int shortest_chainlen = g->num_dots;
121aae4b 2575 int loop_found = FALSE;
121aae4b 2576 int dots_connected;
2577 int progress = FALSE;
7c95608a 2578 int i;
6193da8d 2579
121aae4b 2580 /*
2581 * Go through the grid and update for all the new edges.
2582 * Since merge_dots() is idempotent, the simplest way to
2583 * do this is just to update for _all_ the edges.
7c95608a 2584 * Also, while we're here, we count the edges.
121aae4b 2585 */
7c95608a 2586 for (i = 0; i < g->num_edges; i++) {
2587 if (state->lines[i] == LINE_YES) {
2588 loop_found |= merge_dots(sstate, i);
121aae4b 2589 edgecount++;
2590 }
7c95608a 2591 }
6193da8d 2592
7c95608a 2593 /*
2594 * Count the clues, count the satisfied clues, and count the
2595 * satisfied-minus-one clues.
2596 */
2597 for (i = 0; i < g->num_faces; i++) {
2598 int c = state->clues[i];
2599 if (c >= 0) {
2600 int o = sstate->face_yes_count[i];
121aae4b 2601 if (o == c)
2602 satclues++;
2603 else if (o == c-1)
2604 sm1clues++;
2605 clues++;
2606 }
2607 }
6193da8d 2608
7c95608a 2609 for (i = 0; i < g->num_dots; ++i) {
2610 dots_connected =
121aae4b 2611 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2612 if (dots_connected > 1)
2613 shortest_chainlen = min(shortest_chainlen, dots_connected);
6193da8d 2614 }
6193da8d 2615
121aae4b 2616 assert(sstate->solver_status == SOLVER_INCOMPLETE);
6c42c563 2617
121aae4b 2618 if (satclues == clues && shortest_chainlen == edgecount) {
2619 sstate->solver_status = SOLVER_SOLVED;
2620 /* This discovery clearly counts as progress, even if we haven't
2621 * just added any lines or anything */
7c95608a 2622 progress = TRUE;
121aae4b 2623 goto finished_loop_deductionsing;
2624 }
6193da8d 2625
121aae4b 2626 /*
2627 * Now go through looking for LINE_UNKNOWN edges which
2628 * connect two dots that are already in the same
2629 * equivalence class. If we find one, test to see if the
2630 * loop it would create is a solution.
2631 */
7c95608a 2632 for (i = 0; i < g->num_edges; i++) {
2633 grid_edge *e = g->edges + i;
2634 int d1 = e->dot1 - g->dots;
2635 int d2 = e->dot2 - g->dots;
2636 int eqclass, val;
2637 if (state->lines[i] != LINE_UNKNOWN)
2638 continue;
121aae4b 2639
7c95608a 2640 eqclass = dsf_canonify(sstate->dotdsf, d1);
2641 if (eqclass != dsf_canonify(sstate->dotdsf, d2))
2642 continue;
121aae4b 2643
7c95608a 2644 val = LINE_NO; /* loop is bad until proven otherwise */
6193da8d 2645
7c95608a 2646 /*
2647 * This edge would form a loop. Next
2648 * question: how long would the loop be?
2649 * Would it equal the total number of edges
2650 * (plus the one we'd be adding if we added
2651 * it)?
2652 */
2653 if (sstate->looplen[eqclass] == edgecount + 1) {
2654 int sm1_nearby;
121aae4b 2655
2656 /*
7c95608a 2657 * This edge would form a loop which
2658 * took in all the edges in the entire
2659 * grid. So now we need to work out
2660 * whether it would be a valid solution
2661 * to the puzzle, which means we have to
2662 * check if it satisfies all the clues.
2663 * This means that every clue must be
2664 * either satisfied or satisfied-minus-
2665 * 1, and also that the number of
2666 * satisfied-minus-1 clues must be at
2667 * most two and they must lie on either
2668 * side of this edge.
121aae4b 2669 */
7c95608a 2670 sm1_nearby = 0;
2671 if (e->face1) {
2672 int f = e->face1 - g->faces;
2673 int c = state->clues[f];
2674 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
121aae4b 2675 sm1_nearby++;
6c42c563 2676 }
7c95608a 2677 if (e->face2) {
2678 int f = e->face2 - g->faces;
2679 int c = state->clues[f];
2680 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2681 sm1_nearby++;
6c42c563 2682 }
7c95608a 2683 if (sm1clues == sm1_nearby &&
2684 sm1clues + satclues == clues) {
2685 val = LINE_YES; /* loop is good! */
6c42c563 2686 }
121aae4b 2687 }
7c95608a 2688
2689 /*
2690 * Right. Now we know that adding this edge
2691 * would form a loop, and we know whether
2692 * that loop would be a viable solution or
2693 * not.
2694 *
2695 * If adding this edge produces a solution,
2696 * then we know we've found _a_ solution but
2697 * we don't know that it's _the_ solution -
2698 * if it were provably the solution then
2699 * we'd have deduced this edge some time ago
2700 * without the need to do loop detection. So
2701 * in this state we return SOLVER_AMBIGUOUS,
2702 * which has the effect that hitting Solve
2703 * on a user-provided puzzle will fill in a
2704 * solution but using the solver to
2705 * construct new puzzles won't consider this
2706 * a reasonable deduction for the user to
2707 * make.
2708 */
2709 progress = solver_set_line(sstate, i, val);
2710 assert(progress == TRUE);
2711 if (val == LINE_YES) {
2712 sstate->solver_status = SOLVER_AMBIGUOUS;
2713 goto finished_loop_deductionsing;
2714 }
6193da8d 2715 }
6193da8d 2716
7c95608a 2717 finished_loop_deductionsing:
121aae4b 2718 return progress ? DIFF_EASY : DIFF_MAX;
c0eb17ce 2719}
6193da8d 2720
2721/* This will return a dynamically allocated solver_state containing the (more)
2722 * solved grid */
315e47b9 2723static solver_state *solve_game_rec(const solver_state *sstate_start)
121aae4b 2724{
315e47b9 2725 solver_state *sstate;
6193da8d 2726
315e47b9 2727 /* Index of the solver we should call next. */
2728 int i = 0;
2729
2730 /* As a speed-optimisation, we avoid re-running solvers that we know
2731 * won't make any progress. This happens when a high-difficulty
2732 * solver makes a deduction that can only help other high-difficulty
2733 * solvers.
2734 * For example: if a new 'dline' flag is set by dline_deductions, the
2735 * trivial_deductions solver cannot do anything with this information.
2736 * If we've already run the trivial_deductions solver (because it's
2737 * earlier in the list), there's no point running it again.
2738 *
2739 * Therefore: if a solver is earlier in the list than "threshold_index",
2740 * we don't bother running it if it's difficulty level is less than
2741 * "threshold_diff".
2742 */
2743 int threshold_diff = 0;
2744 int threshold_index = 0;
2745
121aae4b 2746 sstate = dup_solver_state(sstate_start);
7c95608a 2747
121aae4b 2748 check_caches(sstate);
6193da8d 2749
315e47b9 2750 while (i < NUM_SOLVERS) {
121aae4b 2751 if (sstate->solver_status == SOLVER_MISTAKE)
2752 return sstate;
7c95608a 2753 if (sstate->solver_status == SOLVER_SOLVED ||
121aae4b 2754 sstate->solver_status == SOLVER_AMBIGUOUS) {
315e47b9 2755 /* solver finished */
121aae4b 2756 break;
2757 }
99dd160e 2758
315e47b9 2759 if ((solver_diffs[i] >= threshold_diff || i >= threshold_index)
2760 && solver_diffs[i] <= sstate->diff) {
2761 /* current_solver is eligible, so use it */
2762 int next_diff = solver_fns[i](sstate);
2763 if (next_diff != DIFF_MAX) {
2764 /* solver made progress, so use new thresholds and
2765 * start again at top of list. */
2766 threshold_diff = next_diff;
2767 threshold_index = i;
2768 i = 0;
2769 continue;
2770 }
2771 }
2772 /* current_solver is ineligible, or failed to make progress, so
2773 * go to the next solver in the list */
2774 i++;
2775 }
121aae4b 2776
2777 if (sstate->solver_status == SOLVER_SOLVED ||
2778 sstate->solver_status == SOLVER_AMBIGUOUS) {
2779 /* s/LINE_UNKNOWN/LINE_NO/g */
7c95608a 2780 array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
2781 sstate->state->game_grid->num_edges);
121aae4b 2782 return sstate;
2783 }
6193da8d 2784
121aae4b 2785 return sstate;
6193da8d 2786}
2787
6193da8d 2788static char *solve_game(game_state *state, game_state *currstate,
2789 char *aux, char **error)
2790{
2791 char *soln = NULL;
2792 solver_state *sstate, *new_sstate;
2793
121aae4b 2794 sstate = new_solver_state(state, DIFF_MAX);
315e47b9 2795 new_sstate = solve_game_rec(sstate);
6193da8d 2796
2797 if (new_sstate->solver_status == SOLVER_SOLVED) {
2798 soln = encode_solve_move(new_sstate->state);
2799 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2800 soln = encode_solve_move(new_sstate->state);
2801 /**error = "Solver found ambiguous solutions"; */
2802 } else {
2803 soln = encode_solve_move(new_sstate->state);
2804 /**error = "Solver failed"; */
2805 }
2806
2807 free_solver_state(new_sstate);
2808 free_solver_state(sstate);
2809
2810 return soln;
2811}
2812
121aae4b 2813/* ----------------------------------------------------------------------
2814 * Drawing and mouse-handling
2815 */
6193da8d 2816
2817static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2818 int x, int y, int button)
2819{
7c95608a 2820 grid *g = state->game_grid;
2821 grid_edge *e;
2822 int i;
6193da8d 2823 char *ret, buf[80];
2824 char button_char = ' ';
2825 enum line_state old_state;
2826
2827 button &= ~MOD_MASK;
2828
7c95608a 2829 /* Convert mouse-click (x,y) to grid coordinates */
2830 x -= BORDER(ds->tilesize);
2831 y -= BORDER(ds->tilesize);
2832 x = x * g->tilesize / ds->tilesize;
2833 y = y * g->tilesize / ds->tilesize;
2834 x += g->lowest_x;
2835 y += g->lowest_y;
6193da8d 2836
7c95608a 2837 e = grid_nearest_edge(g, x, y);
2838 if (e == NULL)
6193da8d 2839 return NULL;
2840
7c95608a 2841 i = e - g->edges;
6193da8d 2842
2843 /* I think it's only possible to play this game with mouse clicks, sorry */
2844 /* Maybe will add mouse drag support some time */
7c95608a 2845 old_state = state->lines[i];
6193da8d 2846
2847 switch (button) {
7c95608a 2848 case LEFT_BUTTON:
2849 switch (old_state) {
2850 case LINE_UNKNOWN:
2851 button_char = 'y';
2852 break;
2853 case LINE_YES:
80e7e37c 2854#ifdef STYLUS_BASED
2855 button_char = 'n';
2856 break;
2857#endif
7c95608a 2858 case LINE_NO:
2859 button_char = 'u';
2860 break;
2861 }
2862 break;
2863 case MIDDLE_BUTTON:
2864 button_char = 'u';
2865 break;
2866 case RIGHT_BUTTON:
2867 switch (old_state) {
2868 case LINE_UNKNOWN:
2869 button_char = 'n';
2870 break;
2871 case LINE_NO:
80e7e37c 2872#ifdef STYLUS_BASED
2873 button_char = 'y';
2874 break;
2875#endif
7c95608a 2876 case LINE_YES:
2877 button_char = 'u';
2878 break;
2879 }
2880 break;
2881 default:
2882 return NULL;
2883 }
2884
2885
2886 sprintf(buf, "%d%c", i, (int)button_char);
6193da8d 2887 ret = dupstr(buf);
2888
2889 return ret;
2890}
2891
2892static game_state *execute_move(game_state *state, char *move)
2893{
7c95608a 2894 int i;
6193da8d 2895 game_state *newstate = dup_game(state);
2896
2897 if (move[0] == 'S') {
2898 move++;
2899 newstate->cheated = TRUE;
2900 }
2901
2902 while (*move) {
2903 i = atoi(move);
8719c2e7 2904 if (i < 0 || i >= newstate->game_grid->num_edges)
2905 goto fail;
6193da8d 2906 move += strspn(move, "1234567890");
2907 switch (*(move++)) {
7c95608a 2908 case 'y':
2909 newstate->lines[i] = LINE_YES;
2910 break;
2911 case 'n':
2912 newstate->lines[i] = LINE_NO;
2913 break;
2914 case 'u':
2915 newstate->lines[i] = LINE_UNKNOWN;
2916 break;
2917 default:
2918 goto fail;
6193da8d 2919 }
2920 }
2921
2922 /*
2923 * Check for completion.
2924 */
b6bf0adc 2925 if (check_completion(newstate))
121aae4b 2926 newstate->solved = TRUE;
6193da8d 2927
6193da8d 2928 return newstate;
2929
7c95608a 2930 fail:
6193da8d 2931 free_game(newstate);
2932 return NULL;
2933}
2934
2935/* ----------------------------------------------------------------------
2936 * Drawing routines.
2937 */
7c95608a 2938
2939/* Convert from grid coordinates to screen coordinates */
2940static void grid_to_screen(const game_drawstate *ds, const grid *g,
2941 int grid_x, int grid_y, int *x, int *y)
2942{
2943 *x = grid_x - g->lowest_x;
2944 *y = grid_y - g->lowest_y;
2945 *x = *x * ds->tilesize / g->tilesize;
2946 *y = *y * ds->tilesize / g->tilesize;
2947 *x += BORDER(ds->tilesize);
2948 *y += BORDER(ds->tilesize);
2949}
2950
2951/* Returns (into x,y) position of centre of face for rendering the text clue.
2952 */
2953static void face_text_pos(const game_drawstate *ds, const grid *g,
e64991db 2954 grid_face *f, int *xret, int *yret)
7c95608a 2955{
e0936bbd 2956 int faceindex = f - g->faces;
7c95608a 2957
e0936bbd 2958 /*
2959 * Return the cached position for this face, if we've already
2960 * worked it out.
2961 */
2962 if (ds->textx[faceindex] >= 0) {
2963 *xret = ds->textx[faceindex];
2964 *yret = ds->texty[faceindex];
2965 return;
2966 }
7c95608a 2967
e0936bbd 2968 /*
e64991db 2969 * Otherwise, use the incentre computed by grid.c and convert it
2970 * to screen coordinates.
e0936bbd 2971 */
e64991db 2972 grid_find_incentre(f);
2973 grid_to_screen(ds, g, f->ix, f->iy,
e0936bbd 2974 &ds->textx[faceindex], &ds->texty[faceindex]);
2975
2976 *xret = ds->textx[faceindex];
2977 *yret = ds->texty[faceindex];
7c95608a 2978}
2979
1463f9f1 2980static void face_text_bbox(game_drawstate *ds, grid *g, grid_face *f,
2981 int *x, int *y, int *w, int *h)
2982{
2983 int xx, yy;
2984 face_text_pos(ds, g, f, &xx, &yy);
2985
2986 /* There seems to be a certain amount of trial-and-error involved
2987 * in working out the correct bounding-box for the text. */
2988
2989 *x = xx - ds->tilesize/4 - 1;
2990 *y = yy - ds->tilesize/4 - 3;
2991 *w = ds->tilesize/2 + 2;
2992 *h = ds->tilesize/2 + 5;
2993}
2994
d68b2c10 2995static void game_redraw_clue(drawing *dr, game_drawstate *ds,
2996 game_state *state, int i)
2997{
2998 grid *g = state->game_grid;
2999 grid_face *f = g->faces + i;
3000 int x, y;
918a098a 3001 char c[3];
d68b2c10 3002
918a098a 3003 if (state->clues[i] < 10) {
3004 c[0] = CLUE2CHAR(state->clues[i]);
3005 c[1] = '\0';
3006 } else {
3007 sprintf(c, "%d", state->clues[i]);
3008 }
d68b2c10 3009
3010 face_text_pos(ds, g, f, &x, &y);
3011 draw_text(dr, x, y,
3012 FONT_VARIABLE, ds->tilesize/2,
3013 ALIGN_VCENTRE | ALIGN_HCENTRE,
3014 ds->clue_error[i] ? COL_MISTAKE :
3015 ds->clue_satisfied[i] ? COL_SATISFIED : COL_FOREGROUND, c);
3016}
3017
1463f9f1 3018static void edge_bbox(game_drawstate *ds, grid *g, grid_edge *e,
3019 int *x, int *y, int *w, int *h)
3020{
3021 int x1 = e->dot1->x;
3022 int y1 = e->dot1->y;
3023 int x2 = e->dot2->x;
3024 int y2 = e->dot2->y;
3025 int xmin, xmax, ymin, ymax;
3026
3027 grid_to_screen(ds, g, x1, y1, &x1, &y1);
3028 grid_to_screen(ds, g, x2, y2, &x2, &y2);
3029 /* Allow extra margin for dots, and thickness of lines */
3030 xmin = min(x1, x2) - 2;
3031 xmax = max(x1, x2) + 2;
3032 ymin = min(y1, y2) - 2;
3033 ymax = max(y1, y2) + 2;
3034
3035 *x = xmin;
3036 *y = ymin;
3037 *w = xmax - xmin + 1;
3038 *h = ymax - ymin + 1;
3039}
3040
3041static void dot_bbox(game_drawstate *ds, grid *g, grid_dot *d,
3042 int *x, int *y, int *w, int *h)
3043{
3044 int x1, y1;
3045
3046 grid_to_screen(ds, g, d->x, d->y, &x1, &y1);
3047
3048 *x = x1 - 2;
3049 *y = y1 - 2;
3050 *w = 5;
3051 *h = 5;
3052}
3053
b0a2ee96 3054static const int loopy_line_redraw_phases[] = {
3055 COL_FAINT, COL_LINEUNKNOWN, COL_FOREGROUND, COL_HIGHLIGHT, COL_MISTAKE
3056};
3057#define NPHASES lenof(loopy_line_redraw_phases)
3058
d68b2c10 3059static void game_redraw_line(drawing *dr, game_drawstate *ds,
b0a2ee96 3060 game_state *state, int i, int phase)
d68b2c10 3061{
3062 grid *g = state->game_grid;
3063 grid_edge *e = g->edges + i;
3064 int x1, x2, y1, y2;
d68b2c10 3065 int line_colour;
3066
3067 if (state->line_errors[i])
3068 line_colour = COL_MISTAKE;
3069 else if (state->lines[i] == LINE_UNKNOWN)
3070 line_colour = COL_LINEUNKNOWN;
3071 else if (state->lines[i] == LINE_NO)
3072 line_colour = COL_FAINT;
3073 else if (ds->flashing)
3074 line_colour = COL_HIGHLIGHT;
3075 else
3076 line_colour = COL_FOREGROUND;
b0a2ee96 3077 if (line_colour != loopy_line_redraw_phases[phase])
3078 return;
d68b2c10 3079
3080 /* Convert from grid to screen coordinates */
3081 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3082 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3083
d68b2c10 3084 if (line_colour == COL_FAINT) {
3085 static int draw_faint_lines = -1;
3086 if (draw_faint_lines < 0) {
3087 char *env = getenv("LOOPY_FAINT_LINES");
3088 draw_faint_lines = (!env || (env[0] == 'y' ||
3089 env[0] == 'Y'));
3090 }
3091 if (draw_faint_lines)
3092 draw_line(dr, x1, y1, x2, y2, line_colour);
3093 } else {
3094 draw_thick_line(dr, 3.0,
3095 x1 + 0.5, y1 + 0.5,
3096 x2 + 0.5, y2 + 0.5,
3097 line_colour);
3098 }
3099}
3100
3101static void game_redraw_dot(drawing *dr, game_drawstate *ds,
3102 game_state *state, int i)
3103{
3104 grid *g = state->game_grid;
3105 grid_dot *d = g->dots + i;
3106 int x, y;
3107
3108 grid_to_screen(ds, g, d->x, d->y, &x, &y);
3109 draw_circle(dr, x, y, 2, COL_FOREGROUND, COL_FOREGROUND);
3110}
3111
1463f9f1 3112static int boxes_intersect(int x0, int y0, int w0, int h0,
3113 int x1, int y1, int w1, int h1)
3114{
3115 /*
3116 * Two intervals intersect iff neither is wholly on one side of
3117 * the other. Two boxes intersect iff their horizontal and
3118 * vertical intervals both intersect.
3119 */
3120 return (x0 < x1+w1 && x1 < x0+w0 && y0 < y1+h1 && y1 < y0+h0);
3121}
3122
3123static void game_redraw_in_rect(drawing *dr, game_drawstate *ds,
3124 game_state *state, int x, int y, int w, int h)
3125{
3126 grid *g = state->game_grid;
3127 int i, phase;
3128 int bx, by, bw, bh;
3129
3130 clip(dr, x, y, w, h);
3131 draw_rect(dr, x, y, w, h, COL_BACKGROUND);
3132
3133 for (i = 0; i < g->num_faces; i++) {
75a52b16 3134 if (state->clues[i] >= 0) {
3135 face_text_bbox(ds, g, &g->faces[i], &bx, &by, &bw, &bh);
3136 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3137 game_redraw_clue(dr, ds, state, i);
3138 }
1463f9f1 3139 }
3140 for (phase = 0; phase < NPHASES; phase++) {
3141 for (i = 0; i < g->num_edges; i++) {
3142 edge_bbox(ds, g, &g->edges[i], &bx, &by, &bw, &bh);
3143 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3144 game_redraw_line(dr, ds, state, i, phase);
3145 }
3146 }
3147 for (i = 0; i < g->num_dots; i++) {
3148 dot_bbox(ds, g, &g->dots[i], &bx, &by, &bw, &bh);
3149 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3150 game_redraw_dot(dr, ds, state, i);
3151 }
3152
3153 unclip(dr);
3154 draw_update(dr, x, y, w, h);
3155}
3156
6193da8d 3157static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3158 game_state *state, int dir, game_ui *ui,
3159 float animtime, float flashtime)
3160{
d68b2c10 3161#define REDRAW_OBJECTS_LIMIT 16 /* Somewhat arbitrary tradeoff */
3162
7c95608a 3163 grid *g = state->game_grid;
3164 int border = BORDER(ds->tilesize);
1463f9f1 3165 int i;
d68b2c10 3166 int flash_changed;
3167 int redraw_everything = FALSE;
3168
3169 int edges[REDRAW_OBJECTS_LIMIT], nedges = 0;
3170 int faces[REDRAW_OBJECTS_LIMIT], nfaces = 0;
3171
3172 /* Redrawing is somewhat involved.
3173 *
3174 * An update can theoretically affect an arbitrary number of edges
3175 * (consider, for example, completing or breaking a cycle which doesn't
3176 * satisfy all the clues -- we'll switch many edges between error and
3177 * normal states). On the other hand, redrawing the whole grid takes a
3178 * while, making the game feel sluggish, and many updates are actually
3179 * quite well localized.
3180 *
3181 * This redraw algorithm attempts to cope with both situations gracefully
3182 * and correctly. For localized changes, we set a clip rectangle, fill
3183 * it with background, and then redraw (a plausible but conservative
3184 * guess at) the objects which intersect the rectangle; if several
3185 * objects need redrawing, we'll do them individually. However, if lots
3186 * of objects are affected, we'll just redraw everything.
3187 *
3188 * The reason for all of this is that it's just not safe to do the redraw
3189 * piecemeal. If you try to draw an antialiased diagonal line over
3190 * itself, you get a slightly thicker antialiased diagonal line, which
3191 * looks rather ugly after a while.
3192 *
3193 * So, we take two passes over the grid. The first attempts to work out
3194 * what needs doing, and the second actually does it.
3195 */
3196
3197 if (!ds->started)
3198 redraw_everything = TRUE;
3199 else {
3200
3201 /* First, trundle through the faces. */
3202 for (i = 0; i < g->num_faces; i++) {
3203 grid_face *f = g->faces + i;
3204 int sides = f->order;
3205 int clue_mistake;
3206 int clue_satisfied;
3207 int n = state->clues[i];
3208 if (n < 0)
3209 continue;
3210
3211 clue_mistake = (face_order(state, i, LINE_YES) > n ||
3212 face_order(state, i, LINE_NO ) > (sides-n));
3213 clue_satisfied = (face_order(state, i, LINE_YES) == n &&
3214 face_order(state, i, LINE_NO ) == (sides-n));
3215
3216 if (clue_mistake != ds->clue_error[i] ||
3217 clue_satisfied != ds->clue_satisfied[i]) {
3218 ds->clue_error[i] = clue_mistake;
3219 ds->clue_satisfied[i] = clue_satisfied;
3220 if (nfaces == REDRAW_OBJECTS_LIMIT)
3221 redraw_everything = TRUE;
3222 else
3223 faces[nfaces++] = i;
3224 }
3225 }
3226
3227 /* Work out what the flash state needs to be. */
3228 if (flashtime > 0 &&
3229 (flashtime <= FLASH_TIME/3 ||
3230 flashtime >= FLASH_TIME*2/3)) {
3231 flash_changed = !ds->flashing;
3232 ds->flashing = TRUE;
3233 } else {
3234 flash_changed = ds->flashing;
3235 ds->flashing = FALSE;
3236 }
3237
3238 /* Now, trundle through the edges. */
3239 for (i = 0; i < g->num_edges; i++) {
3240 char new_ds =
3241 state->line_errors[i] ? DS_LINE_ERROR : state->lines[i];
3242 if (new_ds != ds->lines[i] ||
3243 (flash_changed && state->lines[i] == LINE_YES)) {
3244 ds->lines[i] = new_ds;
3245 if (nedges == REDRAW_OBJECTS_LIMIT)
3246 redraw_everything = TRUE;
3247 else
3248 edges[nedges++] = i;
3249 }
3250 }
3251 }
3252
3253 /* Pass one is now done. Now we do the actual drawing. */
3254 if (redraw_everything) {
7c95608a 3255 int grid_width = g->highest_x - g->lowest_x;
3256 int grid_height = g->highest_y - g->lowest_y;
3257 int w = grid_width * ds->tilesize / g->tilesize;
3258 int h = grid_height * ds->tilesize / g->tilesize;
6193da8d 3259
1463f9f1 3260 game_redraw_in_rect(dr, ds, state,
3261 0, 0, w + 2*border + 1, h + 2*border + 1);
d68b2c10 3262 } else {
c0eb17ce 3263
d68b2c10 3264 /* Right. Now we roll up our sleeves. */
3265
3266 for (i = 0; i < nfaces; i++) {
3267 grid_face *f = g->faces + faces[i];
d68b2c10 3268 int x, y, w, h;
1463f9f1 3269
3270 face_text_bbox(ds, g, f, &x, &y, &w, &h);
3271 game_redraw_in_rect(dr, ds, state, x, y, w, h);
d68b2c10 3272 }
c0eb17ce 3273
d68b2c10 3274 for (i = 0; i < nedges; i++) {
1463f9f1 3275 grid_edge *e = g->edges + edges[i];
3276 int x, y, w, h;
6193da8d 3277
1463f9f1 3278 edge_bbox(ds, g, e, &x, &y, &w, &h);
3279 game_redraw_in_rect(dr, ds, state, x, y, w, h);
d68b2c10 3280 }
6193da8d 3281 }
d68b2c10 3282
7c95608a 3283 ds->started = TRUE;
6193da8d 3284}
3285
6193da8d 3286static float game_flash_length(game_state *oldstate, game_state *newstate,
3287 int dir, game_ui *ui)
3288{
3289 if (!oldstate->solved && newstate->solved &&
3290 !oldstate->cheated && !newstate->cheated) {
3291 return FLASH_TIME;
3292 }
3293
3294 return 0.0F;
3295}
3296
1cea529f 3297static int game_status(game_state *state)
4496362f 3298{
1cea529f 3299 return state->solved ? +1 : 0;
4496362f 3300}
3301
6193da8d 3302static void game_print_size(game_params *params, float *x, float *y)
3303{
3304 int pw, ph;
3305
3306 /*
7c95608a 3307 * I'll use 7mm "squares" by default.
6193da8d 3308 */
3309 game_compute_size(params, 700, &pw, &ph);
3310 *x = pw / 100.0F;
3311 *y = ph / 100.0F;
3312}
3313
3314static void game_print(drawing *dr, game_state *state, int tilesize)
3315{
6193da8d 3316 int ink = print_mono_colour(dr, 0);
7c95608a 3317 int i;
6193da8d 3318 game_drawstate ads, *ds = &ads;
7c95608a 3319 grid *g = state->game_grid;
4413ef0f 3320
092e9395 3321 ds->tilesize = tilesize;
8acc8766 3322 ds->textx = snewn(g->num_faces, int);
3323 ds->texty = snewn(g->num_faces, int);
3324 for (i = 0; i < g->num_faces; i++)
3325 ds->textx[i] = ds->texty[i] = -1;
6193da8d 3326
7c95608a 3327 for (i = 0; i < g->num_dots; i++) {
3328 int x, y;
3329 grid_to_screen(ds, g, g->dots[i].x, g->dots[i].y, &x, &y);
3330 draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
121aae4b 3331 }
6193da8d 3332
3333 /*
3334 * Clues.
3335 */
7c95608a 3336 for (i = 0; i < g->num_faces; i++) {
3337 grid_face *f = g->faces + i;
3338 int clue = state->clues[i];
3339 if (clue >= 0) {
121aae4b 3340 char c[2];
7c95608a 3341 int x, y;
3342 c[0] = CLUE2CHAR(clue);
121aae4b 3343 c[1] = '\0';
7c95608a 3344 face_text_pos(ds, g, f, &x, &y);
3345 draw_text(dr, x, y,
3346 FONT_VARIABLE, ds->tilesize / 2,
121aae4b 3347 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3348 }
3349 }
6193da8d 3350
3351 /*
7c95608a 3352 * Lines.
6193da8d 3353 */
7c95608a 3354 for (i = 0; i < g->num_edges; i++) {
3355 int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
3356 grid_edge *e = g->edges + i;
3357 int x1, y1, x2, y2;
3358 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3359 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3360 if (state->lines[i] == LINE_YES)
3361 {
3362 /* (dx, dy) points from (x1, y1) to (x2, y2).
3363 * The line is then "fattened" in a perpendicular
3364 * direction to create a thin rectangle. */
3365 double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
3366 double dx = (x2 - x1) / d;
3367 double dy = (y2 - y1) / d;
1515b973 3368 int points[8];
3369
7c95608a 3370 dx = (dx * ds->tilesize) / thickness;
3371 dy = (dy * ds->tilesize) / thickness;
b1535c90 3372 points[0] = x1 + (int)dy;
3373 points[1] = y1 - (int)dx;
3374 points[2] = x1 - (int)dy;
3375 points[3] = y1 + (int)dx;
3376 points[4] = x2 - (int)dy;
3377 points[5] = y2 + (int)dx;
3378 points[6] = x2 + (int)dy;
3379 points[7] = y2 - (int)dx;
7c95608a 3380 draw_polygon(dr, points, 4, ink, ink);
3381 }
3382 else
3383 {
3384 /* Draw a dotted line */
3385 int divisions = 6;
3386 int j;
3387 for (j = 1; j < divisions; j++) {
3388 /* Weighted average */
3389 int x = (x1 * (divisions -j) + x2 * j) / divisions;
3390 int y = (y1 * (divisions -j) + y2 * j) / divisions;
3391 draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
3392 }
3393 }
121aae4b 3394 }
8acc8766 3395
3396 sfree(ds->textx);
3397 sfree(ds->texty);
6193da8d 3398}
3399
3400#ifdef COMBINED
3401#define thegame loopy
3402#endif
3403
3404const struct game thegame = {
750037d7 3405 "Loopy", "games.loopy", "loopy",
6193da8d 3406 default_params,
3407 game_fetch_preset,
3408 decode_params,
3409 encode_params,
3410 free_params,
3411 dup_params,
3412 TRUE, game_configure, custom_params,
3413 validate_params,
3414 new_game_desc,
3415 validate_desc,
3416 new_game,
3417 dup_game,
3418 free_game,
3419 1, solve_game,
fa3abef5 3420 TRUE, game_can_format_as_text_now, game_text_format,
6193da8d 3421 new_ui,
3422 free_ui,
3423 encode_ui,
3424 decode_ui,
3425 game_changed_state,
3426 interpret_move,
3427 execute_move,
3428 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3429 game_colours,
3430 game_new_drawstate,
3431 game_free_drawstate,
3432 game_redraw,
3433 game_anim_length,
3434 game_flash_length,
1cea529f 3435 game_status,
6193da8d 3436 TRUE, FALSE, game_print_size, game_print,
121aae4b 3437 FALSE /* wants_statusbar */,
6193da8d 3438 FALSE, game_timing_state,
121aae4b 3439 0, /* mouse_priorities */
6193da8d 3440};
5ca89681 3441
3442#ifdef STANDALONE_SOLVER
3443
3444/*
3445 * Half-hearted standalone solver. It can't output the solution to
3446 * anything but a square puzzle, and it can't log the deductions
3447 * it makes either. But it can solve square puzzles, and more
3448 * importantly it can use its solver to grade the difficulty of
3449 * any puzzle you give it.
3450 */
3451
3452#include <stdarg.h>
3453
3454int main(int argc, char **argv)
3455{
3456 game_params *p;
3457 game_state *s;
3458 char *id = NULL, *desc, *err;
3459 int grade = FALSE;
3460 int ret, diff;
3461#if 0 /* verbose solver not supported here (yet) */
3462 int really_verbose = FALSE;
3463#endif
3464
3465 while (--argc > 0) {
3466 char *p = *++argv;
3467#if 0 /* verbose solver not supported here (yet) */
3468 if (!strcmp(p, "-v")) {
3469 really_verbose = TRUE;
3470 } else
3471#endif
3472 if (!strcmp(p, "-g")) {
3473 grade = TRUE;
3474 } else if (*p == '-') {
3475 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3476 return 1;
3477 } else {
3478 id = p;
3479 }
3480 }
3481
3482 if (!id) {
3483 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3484 return 1;
3485 }
3486
3487 desc = strchr(id, ':');
3488 if (!desc) {
3489 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3490 return 1;
3491 }
3492 *desc++ = '\0';
3493
3494 p = default_params();
3495 decode_params(p, id);
3496 err = validate_desc(p, desc);
3497 if (err) {
3498 fprintf(stderr, "%s: %s\n", argv[0], err);
3499 return 1;
3500 }
3501 s = new_game(NULL, p, desc);
3502
3503 /*
3504 * When solving an Easy puzzle, we don't want to bother the
3505 * user with Hard-level deductions. For this reason, we grade
3506 * the puzzle internally before doing anything else.
3507 */
3508 ret = -1; /* placate optimiser */
3509 for (diff = 0; diff < DIFF_MAX; diff++) {
3510 solver_state *sstate_new;
3511 solver_state *sstate = new_solver_state((game_state *)s, diff);
3512
315e47b9 3513 sstate_new = solve_game_rec(sstate);
5ca89681 3514
3515 if (sstate_new->solver_status == SOLVER_MISTAKE)
3516 ret = 0;
3517 else if (sstate_new->solver_status == SOLVER_SOLVED)
3518 ret = 1;
3519 else
3520 ret = 2;
3521
3522 free_solver_state(sstate_new);
3523 free_solver_state(sstate);
3524
3525 if (ret < 2)
3526 break;
3527 }
3528
3529 if (diff == DIFF_MAX) {
3530 if (grade)
3531 printf("Difficulty rating: harder than Hard, or ambiguous\n");
3532 else
3533 printf("Unable to find a unique solution\n");
3534 } else {
3535 if (grade) {
3536 if (ret == 0)
3537 printf("Difficulty rating: impossible (no solution exists)\n");
3538 else if (ret == 1)
3539 printf("Difficulty rating: %s\n", diffnames[diff]);
3540 } else {
3541 solver_state *sstate_new;
3542 solver_state *sstate = new_solver_state((game_state *)s, diff);
3543
3544 /* If we supported a verbose solver, we'd set verbosity here */
3545
315e47b9 3546 sstate_new = solve_game_rec(sstate);
5ca89681 3547
3548 if (sstate_new->solver_status == SOLVER_MISTAKE)
3549 printf("Puzzle is inconsistent\n");
3550 else {
3551 assert(sstate_new->solver_status == SOLVER_SOLVED);
3552 if (s->grid_type == 0) {
3553 fputs(game_text_format(sstate_new->state), stdout);
3554 } else {
3555 printf("Unable to output non-square grids\n");
3556 }
3557 }
3558
3559 free_solver_state(sstate_new);
3560 free_solver_state(sstate);
3561 }
3562 }
3563
3564 return 0;
3565}
3566
3567#endif
cebf0b0d 3568
3569/* vim: set shiftwidth=4 tabstop=8: */