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