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