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