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