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