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