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