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