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