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