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