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