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