chiark / gitweb /
Patch from Mike: fix an array indexing error in the clue
[sgt-puzzles.git] / loopy.c
1 /*
2  * loopy.c: An implementation of the Nikoli game 'Loop the loop'.
3  * (c) Mike Pinna, 2005
4  *
5  * vim: set shiftwidth=4 :set textwidth=80:
6  */ 
7
8 /*
9  * TODO:
10  *
11  *  - setting very high recursion depth seems to cause memory
12  *    munching: are we recursing before checking completion, by any
13  *    chance?
14  *
15  *  - there's an interesting deductive technique which makes use of
16  *    topology rather than just graph theory. Each _square_ in the
17  *    grid is either inside or outside the loop; you can tell that
18  *    two squares are on the same side of the loop if they're
19  *    separated by an x (or, more generally, by a path crossing no
20  *    LINE_UNKNOWNs and an even number of LINE_YESes), and on the
21  *    opposite side of the loop if they're separated by a line (or
22  *    an odd number of LINE_YESes and no LINE_UNKNOWNs). Oh, and
23  *    any square separated from the outside of the grid by a
24  *    LINE_YES or a LINE_NO is on the inside or outside
25  *    respectively. So if you can track this for all squares, you
26  *    can occasionally spot that two squares are separated by a
27  *    LINE_UNKNOWN but their relative insideness is known, and
28  *    therefore deduce the state of the edge between them.
29  *     + An efficient way to track this would be by augmenting the
30  *       disjoint set forest data structure. Each element, along
31  *       with a pointer to a parent member of its equivalence
32  *       class, would also carry a one-bit field indicating whether
33  *       it was equal or opposite to its parent. Then you could
34  *       keep flipping a bit as you ascended the tree during
35  *       dsf_canonify(), and hence you'd be able to return the
36  *       relationship of the input value to its ultimate parent
37  *       (and also you could then get all those bits right when you
38  *       went back up the tree rewriting). So you'd be able to
39  *       query whether any two elements were known-equal,
40  *       known-opposite, or not-known, and you could add new
41  *       equalities or oppositenesses to increase your knowledge.
42  *       (Of course the algorithm would have to fail an assertion
43  *       if you tried to tell it two things it already knew to be
44  *       opposite were equal, or vice versa!)
45  *       This data structure would also be useful in the
46  *       graph-theoretic part of the solver, where it could be used
47  *       for storing information about which lines are known-identical
48  *       or known-opposite.  (For example if two lines bordering a 3
49  *       are known-identical they must both be LINE_YES, and if they
50  *       are known-opposite, the *other* two lines bordering that clue
51  *       must be LINE_YES, etc).  This may duplicate some
52  *       functionality already present in the solver but it is more
53  *       general and we could remove the old code, so that's no bad
54  *       thing.
55  */
56
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <assert.h>
61 #include <ctype.h>
62 #include <math.h>
63
64 #include "puzzles.h"
65 #include "tree234.h"
66
67 #define PREFERRED_TILE_SIZE 32
68 #define TILE_SIZE (ds->tilesize)
69 #define LINEWIDTH TILE_SIZE / 16
70 #define BORDER (TILE_SIZE / 2)
71
72 #define FLASH_TIME 0.5F
73
74 #define HL_COUNT(state) ((state)->w * ((state)->h + 1))
75 #define VL_COUNT(state) (((state)->w + 1) * (state)->h)
76 #define DOT_COUNT(state) (((state)->w + 1) * ((state)->h + 1))
77 #define SQUARE_COUNT(state) ((state)->w * (state)->h)
78
79 #define ABOVE_SQUARE(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
80 #define BELOW_SQUARE(state, i, j) ABOVE_SQUARE(state, i, (j)+1)
81
82 #define LEFTOF_SQUARE(state, i, j)  ((state)->vl[(i) + ((state)->w + 1) * (j)])
83 #define RIGHTOF_SQUARE(state, i, j) LEFTOF_SQUARE(state, (i)+1, j)
84
85 #define LEGAL_DOT(state, i, j) ((i) >= 0 && (j) >= 0 &&                 \
86                                 (i) <= (state)->w && (j) <= (state)->h)
87
88 /*
89  * These macros return rvalues only, but can cope with being passed
90  * out-of-range coordinates.
91  */
92 #define ABOVE_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j <= 0) ?  \
93                                 LINE_NO : LV_ABOVE_DOT(state, i, j))
94 #define BELOW_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j >= (state)->h) ? \
95                                 LINE_NO : LV_BELOW_DOT(state, i, j))
96
97 #define LEFTOF_DOT(state, i, j)  ((!LEGAL_DOT(state, i, j) || i <= 0) ? \
98                                   LINE_NO : LV_LEFTOF_DOT(state, i, j))
99 #define RIGHTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i >= (state)->w)?\
100                                   LINE_NO : LV_RIGHTOF_DOT(state, i, j))
101
102 /*
103  * These macros expect to be passed valid coordinates, and return
104  * lvalues.
105  */
106 #define LV_BELOW_DOT(state, i, j) ((state)->vl[(i) + ((state)->w + 1) * (j)])
107 #define LV_ABOVE_DOT(state, i, j) LV_BELOW_DOT(state, i, (j)-1)
108
109 #define LV_RIGHTOF_DOT(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
110 #define LV_LEFTOF_DOT(state, i, j)  LV_RIGHTOF_DOT(state, (i)-1, j)
111
112 #define CLUE_AT(state, i, j) ((i < 0 || i >= (state)->w || \
113                                j < 0 || j >= (state)->h) ? \
114                              ' ' : LV_CLUE_AT(state, i, j))
115                              
116 #define LV_CLUE_AT(state, i, j) ((state)->clues[(i) + (state)->w * (j)])
117
118 #define OPP(dir) (dir == LINE_UNKNOWN ? LINE_UNKNOWN : \
119                   dir == LINE_YES ? LINE_NO : LINE_YES)
120
121 static char *game_text_format(game_state *state);
122
123 enum {
124     COL_BACKGROUND,
125     COL_FOREGROUND,
126     COL_HIGHLIGHT,
127     COL_MISTAKE,
128     NCOLOURS
129 };
130
131 /*
132  * Difficulty levels. I do some macro ickery here to ensure that my
133  * enum and the various forms of my name list always match up.
134  */
135 #define DIFFLIST(A) \
136     A(EASY,Easy,e) \
137     A(NORMAL,Normal,n)
138 #define ENUM(upper,title,lower) DIFF_ ## upper,
139 #define TITLE(upper,title,lower) #title,
140 #define ENCODE(upper,title,lower) #lower
141 #define CONFIG(upper,title,lower) ":" #title
142 enum { DIFFLIST(ENUM) DIFFCOUNT };
143 static char const *const loopy_diffnames[] = { DIFFLIST(TITLE) };
144 static char const loopy_diffchars[] = DIFFLIST(ENCODE);
145 #define DIFFCONFIG DIFFLIST(CONFIG)
146
147 /* LINE_YES_ERROR is only used in the drawing routine */
148 enum line_state { LINE_UNKNOWN, LINE_YES, LINE_NO /*, LINE_YES_ERROR*/ };
149
150 enum direction { UP, DOWN, LEFT, RIGHT };
151
152 struct game_params {
153     int w, h, diff, rec;
154 };
155
156 struct game_state {
157     int w, h;
158     
159     /* Put ' ' in a square that doesn't get a clue */
160     char *clues;
161     
162     /* Arrays of line states, stored left-to-right, top-to-bottom */
163     char *hl, *vl;
164
165     int solved;
166     int cheated;
167
168     int recursion_depth;
169 };
170
171 static game_state *dup_game(game_state *state)
172 {
173     game_state *ret = snew(game_state);
174
175     ret->h = state->h;
176     ret->w = state->w;
177     ret->solved = state->solved;
178     ret->cheated = state->cheated;
179
180     ret->clues   = snewn(SQUARE_COUNT(state), char);
181     memcpy(ret->clues, state->clues, SQUARE_COUNT(state));
182
183     ret->hl      = snewn(HL_COUNT(state), char);
184     memcpy(ret->hl, state->hl, HL_COUNT(state));
185
186     ret->vl      = snewn(VL_COUNT(state), char);
187     memcpy(ret->vl, state->vl, VL_COUNT(state));
188
189     ret->recursion_depth = state->recursion_depth;
190
191     return ret;
192 }
193
194 static void free_game(game_state *state)
195 {
196     if (state) {
197         sfree(state->clues);
198         sfree(state->hl);
199         sfree(state->vl);
200         sfree(state);
201     }
202 }
203
204 enum solver_status {
205     SOLVER_SOLVED,    /* This is the only solution the solver could find */
206     SOLVER_MISTAKE,   /* This is definitely not a solution */
207     SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
208     SOLVER_INCOMPLETE /* This may be a partial solution */
209 };
210
211 typedef struct solver_state {
212   game_state *state;
213    /* XXX dot_atleastone[i,j, dline] is equivalent to */
214    /*     dot_atmostone[i,j,OPP_DLINE(dline)] */
215   char *dot_atleastone;
216   char *dot_atmostone;
217 /*   char *dline_identical; */
218   int recursion_remaining;
219   enum solver_status solver_status;
220   int *dotdsf, *looplen;
221 } solver_state;
222
223 static solver_state *new_solver_state(game_state *state) {
224     solver_state *ret = snew(solver_state);
225     int i;
226
227     ret->state = dup_game(state);
228     
229     ret->dot_atmostone = snewn(DOT_COUNT(state), char);
230     memset(ret->dot_atmostone, 0, DOT_COUNT(state));
231     ret->dot_atleastone = snewn(DOT_COUNT(state), char);
232     memset(ret->dot_atleastone, 0, DOT_COUNT(state));
233
234 #if 0
235     dline_identical = snewn(DOT_COUNT(state), char);
236     memset(dline_identical, 0, DOT_COUNT(state));
237 #endif
238
239     ret->recursion_remaining = state->recursion_depth;
240     ret->solver_status = SOLVER_INCOMPLETE; /* XXX This may be a lie */
241
242     ret->dotdsf = snewn(DOT_COUNT(state), int);
243     ret->looplen = snewn(DOT_COUNT(state), int);
244     for (i = 0; i < DOT_COUNT(state); i++) {
245         ret->dotdsf[i] = i;
246         ret->looplen[i] = 1;
247     }
248
249     return ret;
250 }
251
252 static void free_solver_state(solver_state *sstate) {
253     if (sstate) {
254         free_game(sstate->state);
255         sfree(sstate->dot_atleastone);
256         sfree(sstate->dot_atmostone);
257         /*    sfree(sstate->dline_identical); */
258         sfree(sstate->dotdsf);
259         sfree(sstate->looplen);
260         sfree(sstate);
261     }
262 }
263
264 static solver_state *dup_solver_state(solver_state *sstate) {
265     game_state *state;
266
267     solver_state *ret = snew(solver_state);
268
269     ret->state = state = dup_game(sstate->state);
270
271     ret->dot_atmostone = snewn(DOT_COUNT(state), char);
272     memcpy(ret->dot_atmostone, sstate->dot_atmostone, DOT_COUNT(state));
273
274     ret->dot_atleastone = snewn(DOT_COUNT(state), char);
275     memcpy(ret->dot_atleastone, sstate->dot_atleastone, DOT_COUNT(state));
276
277 #if 0
278     ret->dline_identical = snewn((state->w + 1) * (state->h + 1), char);
279     memcpy(ret->dline_identical, state->dot_atmostone, 
280            (state->w + 1) * (state->h + 1));
281 #endif
282
283     ret->recursion_remaining = sstate->recursion_remaining;
284     ret->solver_status = sstate->solver_status;
285
286     ret->dotdsf = snewn(DOT_COUNT(state), int);
287     ret->looplen = snewn(DOT_COUNT(state), int);
288     memcpy(ret->dotdsf, sstate->dotdsf, DOT_COUNT(state) * sizeof(int));
289     memcpy(ret->looplen, sstate->looplen, DOT_COUNT(state) * sizeof(int));
290
291     return ret;
292 }
293
294 /*
295  * Merge two dots due to the existence of an edge between them.
296  * Updates the dsf tracking equivalence classes, and keeps track of
297  * the length of path each dot is currently a part of.
298  */
299 static void merge_dots(solver_state *sstate, int x1, int y1, int x2, int y2)
300 {
301     int i, j, len;
302
303     i = y1 * (sstate->state->w + 1) + x1;
304     j = y2 * (sstate->state->w + 1) + x2;
305
306     i = dsf_canonify(sstate->dotdsf, i);
307     j = dsf_canonify(sstate->dotdsf, j);
308
309     if (i != j) {
310         len = sstate->looplen[i] + sstate->looplen[j];
311         dsf_merge(sstate->dotdsf, i, j);
312         i = dsf_canonify(sstate->dotdsf, i);
313         sstate->looplen[i] = len;
314     }
315 }
316
317 /* Count the number of lines of a particular type currently going into the
318  * given dot.  Lines going off the edge of the board are assumed fixed no. */
319 static int dot_order(const game_state* state, int i, int j, char line_type)
320 {
321     int n = 0;
322
323     if (i > 0) {
324         if (LEFTOF_DOT(state, i, j) == line_type)
325             ++n;
326     } else {
327         if (line_type == LINE_NO)
328             ++n;
329     }
330     if (i < state->w) {
331         if (RIGHTOF_DOT(state, i, j) == line_type)
332             ++n;
333     } else {
334         if (line_type == LINE_NO)
335             ++n;
336     }
337     if (j > 0) {
338         if (ABOVE_DOT(state, i, j) == line_type)
339             ++n;
340     } else {
341         if (line_type == LINE_NO)
342             ++n;
343     }
344     if (j < state->h) {
345         if (BELOW_DOT(state, i, j) == line_type)
346             ++n;
347     } else {
348         if (line_type == LINE_NO)
349             ++n;
350     }
351
352     return n;
353 }
354 /* Count the number of lines of a particular type currently surrounding the
355  * given square */
356 static int square_order(const game_state* state, int i, int j, char line_type)
357 {
358     int n = 0;
359
360     if (ABOVE_SQUARE(state, i, j) == line_type)
361         ++n;
362     if (BELOW_SQUARE(state, i, j) == line_type)
363         ++n;
364     if (LEFTOF_SQUARE(state, i, j) == line_type)
365         ++n;
366     if (RIGHTOF_SQUARE(state, i, j) == line_type)
367         ++n;
368
369     return n;
370 }
371
372 /* Set all lines bordering a dot of type old_type to type new_type */
373 static void dot_setall(game_state *state, int i, int j,
374                        char old_type, char new_type)
375 {
376 /*    printf("dot_setall([%d,%d], %d, %d)\n", i, j, old_type, new_type); */
377     if (i > 0        && LEFTOF_DOT(state, i, j) == old_type)
378         LV_LEFTOF_DOT(state, i, j) = new_type;
379     if (i < state->w && RIGHTOF_DOT(state, i, j) == old_type)
380         LV_RIGHTOF_DOT(state, i, j) = new_type;
381     if (j > 0        && ABOVE_DOT(state, i, j) == old_type)
382         LV_ABOVE_DOT(state, i, j) = new_type;
383     if (j < state->h && BELOW_DOT(state, i, j) == old_type)
384         LV_BELOW_DOT(state, i, j) = new_type;
385 }
386 /* Set all lines bordering a square of type old_type to type new_type */
387 static void square_setall(game_state *state, int i, int j,
388                           char old_type, char new_type)
389 {
390     if (ABOVE_SQUARE(state, i, j) == old_type)
391         ABOVE_SQUARE(state, i, j) = new_type;
392     if (BELOW_SQUARE(state, i, j) == old_type)
393         BELOW_SQUARE(state, i, j) = new_type;
394     if (LEFTOF_SQUARE(state, i, j) == old_type)
395         LEFTOF_SQUARE(state, i, j) = new_type;
396     if (RIGHTOF_SQUARE(state, i, j) == old_type)
397         RIGHTOF_SQUARE(state, i, j) = new_type;
398 }
399
400 static game_params *default_params(void)
401 {
402     game_params *ret = snew(game_params);
403
404 #ifdef SLOW_SYSTEM
405     ret->h = 4;
406     ret->w = 4;
407 #else
408     ret->h = 10;
409     ret->w = 10;
410 #endif
411     ret->diff = DIFF_EASY;
412     ret->rec = 0;
413
414     return ret;
415 }
416
417 static game_params *dup_params(game_params *params)
418 {
419     game_params *ret = snew(game_params);
420     *ret = *params;                       /* structure copy */
421     return ret;
422 }
423
424 static const struct {
425     char *desc;
426     game_params params;
427 } loopy_presets[] = {
428     { "4x4 Easy",     {  4,  4, DIFF_EASY, 0 } },
429     { "4x4 Normal",   {  4,  4, DIFF_NORMAL, 0 } },
430     { "7x7 Easy",     {  7,  7, DIFF_EASY, 0 } },
431     { "7x7 Normal",   {  7,  7, DIFF_NORMAL, 0 } },
432     { "10x10 Easy",   { 10, 10, DIFF_EASY, 0 } },
433     { "10x10 Normal", { 10, 10, DIFF_NORMAL, 0 } },
434 #ifndef SLOW_SYSTEM
435     { "15x15 Easy",   { 15, 15, DIFF_EASY, 0 } },
436     { "15x15 Normal", { 15, 15, DIFF_NORMAL, 0 } },
437     { "30x20 Easy",   { 30, 20, DIFF_EASY, 0 } },
438     { "30x20 Normal", { 30, 20, DIFF_NORMAL, 0 } }
439 #endif
440 };
441
442 static int game_fetch_preset(int i, char **name, game_params **params)
443 {
444     game_params tmppar;
445
446     if (i < 0 || i >= lenof(loopy_presets))
447         return FALSE;
448
449     tmppar = loopy_presets[i].params;
450     *params = dup_params(&tmppar);
451     *name = dupstr(loopy_presets[i].desc);
452
453     return TRUE;
454 }
455
456 static void free_params(game_params *params)
457 {
458     sfree(params);
459 }
460
461 static void decode_params(game_params *params, char const *string)
462 {
463     params->h = params->w = atoi(string);
464     params->rec = 0;
465     params->diff = DIFF_EASY;
466     while (*string && isdigit((unsigned char)*string)) string++;
467     if (*string == 'x') {
468         string++;
469         params->h = atoi(string);
470         while (*string && isdigit((unsigned char)*string)) string++;
471     }
472     if (*string == 'r') {
473         string++;
474         params->rec = atoi(string);
475         while (*string && isdigit((unsigned char)*string)) string++;
476     }
477     if (*string == 'd') {
478         int i;
479
480         string++;
481         for (i = 0; i < DIFFCOUNT; i++)
482             if (*string == loopy_diffchars[i])
483                 params->diff = i;
484         if (*string) string++;
485     }
486 }
487
488 static char *encode_params(game_params *params, int full)
489 {
490     char str[80];
491     sprintf(str, "%dx%d", params->w, params->h);
492     if (full)
493         sprintf(str + strlen(str), "r%dd%c", params->rec,
494                 loopy_diffchars[params->diff]);
495     return dupstr(str);
496 }
497
498 static config_item *game_configure(game_params *params)
499 {
500     config_item *ret;
501     char buf[80];
502
503     ret = snewn(4, config_item);
504
505     ret[0].name = "Width";
506     ret[0].type = C_STRING;
507     sprintf(buf, "%d", params->w);
508     ret[0].sval = dupstr(buf);
509     ret[0].ival = 0;
510
511     ret[1].name = "Height";
512     ret[1].type = C_STRING;
513     sprintf(buf, "%d", params->h);
514     ret[1].sval = dupstr(buf);
515     ret[1].ival = 0;
516
517     ret[2].name = "Difficulty";
518     ret[2].type = C_CHOICES;
519     ret[2].sval = DIFFCONFIG;
520     ret[2].ival = params->diff;
521
522     ret[3].name = NULL;
523     ret[3].type = C_END;
524     ret[3].sval = NULL;
525     ret[3].ival = 0;
526
527     return ret;
528 }
529
530 static game_params *custom_params(config_item *cfg)
531 {
532     game_params *ret = snew(game_params);
533
534     ret->w = atoi(cfg[0].sval);
535     ret->h = atoi(cfg[1].sval);
536     ret->rec = 0;
537     ret->diff = cfg[2].ival;
538
539     return ret;
540 }
541
542 static char *validate_params(game_params *params, int full)
543 {
544     if (params->w < 4 || params->h < 4)
545         return "Width and height must both be at least 4";
546     if (params->rec < 0)
547         return "Recursion depth can't be negative";
548
549     /*
550      * This shouldn't be able to happen at all, since decode_params
551      * and custom_params will never generate anything that isn't
552      * within range.
553      */
554     assert(params->diff >= 0 && params->diff < DIFFCOUNT);
555
556     return NULL;
557 }
558
559 /* We're going to store a list of current candidate squares for lighting.
560  * Each square gets a 'score', which tells us how adding that square right
561  * now would affect the length of the solution loop.  We're trying to
562  * maximise that quantity so will bias our random selection of squares to
563  * light towards those with high scores */
564 struct square { 
565     int score;
566     unsigned long random;
567     int x, y;
568 };
569
570 static int get_square_cmpfn(void *v1, void *v2) 
571 {
572     struct square *s1 = (struct square *)v1;
573     struct square *s2 = (struct square *)v2;
574     int r;
575     
576     r = s1->x - s2->x;
577     if (r)
578         return r;
579
580     r = s1->y - s2->y;
581     if (r)
582         return r;
583
584     return 0;
585 }
586
587 static int square_sort_cmpfn(void *v1, void *v2)
588 {
589     struct square *s1 = (struct square *)v1;
590     struct square *s2 = (struct square *)v2;
591     int r;
592
593     r = s2->score - s1->score;
594     if (r) {
595         return r;
596     }
597
598     if (s1->random < s2->random)
599         return -1;
600     else if (s1->random > s2->random)
601         return 1;
602
603     /*
604      * It's _just_ possible that two squares might have been given
605      * the same random value. In that situation, fall back to
606      * comparing based on the coordinates. This introduces a tiny
607      * directional bias, but not a significant one.
608      */
609     return get_square_cmpfn(v1, v2);
610 }
611
612 static void print_tree(tree234 *tree)
613 {
614 #if 0
615     int i = 0;
616     struct square *s;
617     printf("Print tree:\n");
618     while (i < count234(tree)) {
619         s = (struct square *)index234(tree, i);
620         assert(s);
621         printf("  [%d,%d], %d, %d\n", s->x, s->y, s->score, s->random);
622         ++i;
623     }
624 #endif
625 }
626
627 enum { SQUARE_LIT, SQUARE_UNLIT };
628
629 #define SQUARE_STATE(i, j)                 \
630     (((i) < 0 || (i) >= params->w ||       \
631       (j) < 0 || (j) >= params->h) ?       \
632      SQUARE_UNLIT :  LV_SQUARE_STATE(i,j))
633
634 #define LV_SQUARE_STATE(i, j) board[(i) + params->w * (j)]
635
636 static void print_board(const game_params *params, const char *board)
637 {
638 #if 0
639     int i,j;
640
641     printf(" ");
642     for (i = 0; i < params->w; i++) {
643         printf("%d", i%10);
644     }
645     printf("\n");
646     for (j = 0; j < params->h; j++) {
647         printf("%d", j%10);
648         for (i = 0; i < params->w; i++) {
649             printf("%c", SQUARE_STATE(i, j) ? ' ' : 'O');
650         }
651         printf("\n");
652     }
653 #endif
654 }
655
656 static char *new_fullyclued_board(game_params *params, random_state *rs)
657 {
658     char *clues;
659     char *board;
660     int i, j, a, b, c;
661     game_state s;
662     game_state *state = &s;
663     int board_area = SQUARE_COUNT(params);
664     int t;
665
666     struct square *square, *tmpsquare, *sq;
667     struct square square_pos;
668
669     /* These will contain exactly the same information, sorted into different
670      * orders */
671     tree234 *lightable_squares_sorted, *lightable_squares_gettable;
672
673 #define SQUARE_REACHABLE(i,j)                      \
674      (t = (SQUARE_STATE(i-1, j) == SQUARE_LIT ||      \
675            SQUARE_STATE(i+1, j) == SQUARE_LIT ||      \
676            SQUARE_STATE(i, j-1) == SQUARE_LIT ||      \
677            SQUARE_STATE(i, j+1) == SQUARE_LIT),       \
678 /*      printf("SQUARE_REACHABLE(%d,%d) = %d\n", i, j, t), */ \
679       t)
680
681
682     /* One situation in which we may not light a square is if that'll leave one
683      * square above/below and one left/right of us unlit, separated by a lit
684      * square diagnonal from us */
685 #define SQUARE_DIAGONAL_VIOLATION(i, j, h, v)           \
686     (t = (SQUARE_STATE((i)+(h), (j))     == SQUARE_UNLIT && \
687           SQUARE_STATE((i),     (j)+(v)) == SQUARE_UNLIT && \
688           SQUARE_STATE((i)+(h), (j)+(v)) == SQUARE_LIT),    \
689 /*     t ? printf("SQUARE_DIAGONAL_VIOLATION(%d, %d, %d, %d)\n",
690                   i, j, h, v) : 0,*/ \
691      t)
692
693     /* We also may not light a square if it will form a loop of lit squares
694      * around some unlit squares, as then the game soln won't have a single
695      * loop */
696 #define SQUARE_LOOP_VIOLATION(i, j, lit1, lit2) \
697     (SQUARE_STATE((i)+1, (j)) == lit1    &&     \
698      SQUARE_STATE((i)-1, (j)) == lit1    &&     \
699      SQUARE_STATE((i), (j)+1) == lit2    &&     \
700      SQUARE_STATE((i), (j)-1) == lit2)
701
702 #define CAN_LIGHT_SQUARE(i, j)                                 \
703     (SQUARE_REACHABLE(i, j)                                 && \
704      !SQUARE_DIAGONAL_VIOLATION(i, j, -1, -1)               && \
705      !SQUARE_DIAGONAL_VIOLATION(i, j, +1, -1)               && \
706      !SQUARE_DIAGONAL_VIOLATION(i, j, -1, +1)               && \
707      !SQUARE_DIAGONAL_VIOLATION(i, j, +1, +1)               && \
708      !SQUARE_LOOP_VIOLATION(i, j, SQUARE_LIT, SQUARE_UNLIT) && \
709      !SQUARE_LOOP_VIOLATION(i, j, SQUARE_UNLIT, SQUARE_LIT))
710
711 #define IS_LIGHTING_CANDIDATE(i, j)        \
712     (SQUARE_STATE(i, j) == SQUARE_UNLIT && \
713      CAN_LIGHT_SQUARE(i,j))
714
715     /* The 'score' of a square reflects its current desirability for selection
716      * as the next square to light.  We want to encourage moving into uncharted
717      * areas so we give scores according to how many of the square's neighbours
718      * are currently unlit. */
719
720    /* UNLIT    SCORE
721     *   3        2
722     *   2        0
723     *   1       -2
724     */
725 #define SQUARE_SCORE(i,j)                  \
726     (2*((SQUARE_STATE(i-1, j) == SQUARE_UNLIT)  +   \
727         (SQUARE_STATE(i+1, j) == SQUARE_UNLIT)  +   \
728         (SQUARE_STATE(i, j-1) == SQUARE_UNLIT)  +   \
729         (SQUARE_STATE(i, j+1) == SQUARE_UNLIT)) - 4)
730
731     /* When a square gets lit, this defines how far away from that square we
732      * need to go recomputing scores */
733 #define SCORE_DISTANCE 1
734
735     board = snewn(board_area, char);
736     clues = snewn(board_area, char);
737
738     state->h = params->h;
739     state->w = params->w;
740     state->clues = clues;
741
742     /* Make a board */
743     memset(board, SQUARE_UNLIT, board_area);
744     
745     /* Seed the board with a single lit square near the middle */
746     i = params->w / 2;
747     j = params->h / 2;
748     if (params->w & 1 && random_bits(rs, 1))
749         ++i;
750     if (params->h & 1 && random_bits(rs, 1))
751         ++j;
752
753     LV_SQUARE_STATE(i, j) = SQUARE_LIT;
754
755     /* We need a way of favouring squares that will increase our loopiness.
756      * We do this by maintaining a list of all candidate squares sorted by
757      * their score and choose randomly from that with appropriate skew. 
758      * In order to avoid consistently biasing towards particular squares, we
759      * need the sort order _within_ each group of scores to be completely
760      * random.  But it would be abusing the hospitality of the tree234 data
761      * structure if our comparison function were nondeterministic :-).  So with
762      * each square we associate a random number that does not change during a
763      * particular run of the generator, and use that as a secondary sort key.
764      * Yes, this means we will be biased towards particular random squares in
765      * any one run but that doesn't actually matter. */
766     
767     lightable_squares_sorted   = newtree234(square_sort_cmpfn);
768     lightable_squares_gettable = newtree234(get_square_cmpfn);
769 #define ADD_SQUARE(s)                                          \
770     do {                                                       \
771 /*      printf("ADD SQUARE: [%d,%d], %d, %d\n",
772                s->x, s->y, s->score, s->random);*/ \
773         sq = add234(lightable_squares_sorted, s);              \
774         assert(sq == s);                                       \
775         sq = add234(lightable_squares_gettable, s);            \
776         assert(sq == s);                                       \
777     } while (0)
778
779 #define REMOVE_SQUARE(s)                                       \
780     do {                                                       \
781 /*      printf("DELETE SQUARE: [%d,%d], %d, %d\n",
782                s->x, s->y, s->score, s->random);*/ \
783         sq = del234(lightable_squares_sorted, s);              \
784         assert(sq);                                            \
785         sq = del234(lightable_squares_gettable, s);            \
786         assert(sq);                                            \
787     } while (0)
788         
789 #define HANDLE_DIR(a, b)                                       \
790     square = snew(struct square);                              \
791     square->x = (i)+(a);                                       \
792     square->y = (j)+(b);                                       \
793     square->score = 2;                                         \
794     square->random = random_bits(rs, 31);                      \
795     ADD_SQUARE(square);
796     HANDLE_DIR(-1, 0);
797     HANDLE_DIR( 1, 0);
798     HANDLE_DIR( 0,-1);
799     HANDLE_DIR( 0, 1);
800 #undef HANDLE_DIR
801     
802     /* Light squares one at a time until the board is interesting enough */
803     while (TRUE)
804     {
805         /* We have count234(lightable_squares) possibilities, and in
806          * lightable_squares_sorted they are sorted with the most desirable
807          * first.  */
808         c = count234(lightable_squares_sorted);
809         if (c == 0)
810             break;
811         assert(c == count234(lightable_squares_gettable));
812
813         /* Check that the best square available is any good */
814         square = (struct square *)index234(lightable_squares_sorted, 0);
815         assert(square);
816
817         /*
818          * We never want to _decrease_ the loop's perimeter. Making
819          * moves that leave the perimeter the same is occasionally
820          * useful: if it were _never_ done then the user would be
821          * able to deduce illicitly that any degree-zero vertex was
822          * on the outside of the loop. So we do it sometimes but
823          * not always.
824          */
825         if (square->score < 0 || (square->score == 0 &&
826                                   random_upto(rs, 2) == 0))
827             break;
828
829         print_tree(lightable_squares_sorted);
830         assert(square->score == SQUARE_SCORE(square->x, square->y));
831         assert(SQUARE_STATE(square->x, square->y) == SQUARE_UNLIT);
832         assert(square->x >= 0 && square->x < params->w);
833         assert(square->y >= 0 && square->y < params->h);
834 /*        printf("LIGHT SQUARE: [%d,%d], score = %d\n", square->x, square->y, square->score); */
835
836         /* Update data structures */
837         LV_SQUARE_STATE(square->x, square->y) = SQUARE_LIT;
838         REMOVE_SQUARE(square);
839
840         print_board(params, board);
841
842         /* We might have changed the score of any squares up to 2 units away in
843          * any direction */
844         for (b = -SCORE_DISTANCE; b <= SCORE_DISTANCE; b++) {
845             for (a = -SCORE_DISTANCE; a <= SCORE_DISTANCE; a++) {
846                 if (!a && !b) 
847                     continue;
848                 square_pos.x = square->x + a;
849                 square_pos.y = square->y + b;
850 /*                printf("Refreshing score for [%d,%d]:\n", square_pos.x, square_pos.y); */
851                 if (square_pos.x < 0 || square_pos.x >= params->w ||
852                     square_pos.y < 0 || square_pos.y >= params->h) {
853 /*                    printf("  Out of bounds\n"); */
854                    continue; 
855                 }
856                 tmpsquare = find234(lightable_squares_gettable, &square_pos,
857                                     NULL);
858                 if (tmpsquare) {
859 /*                    printf(" Removing\n"); */
860                     assert(tmpsquare->x == square_pos.x);
861                     assert(tmpsquare->y == square_pos.y);
862                     assert(SQUARE_STATE(tmpsquare->x, tmpsquare->y) == 
863                            SQUARE_UNLIT);
864                     REMOVE_SQUARE(tmpsquare);
865                 } else {
866 /*                    printf(" Creating\n"); */
867                     tmpsquare = snew(struct square);
868                     tmpsquare->x = square_pos.x;
869                     tmpsquare->y = square_pos.y;
870                     tmpsquare->random = random_bits(rs, 31);
871                 }
872                 tmpsquare->score = SQUARE_SCORE(tmpsquare->x, tmpsquare->y);
873
874                 if (IS_LIGHTING_CANDIDATE(tmpsquare->x, tmpsquare->y)) {
875 /*                    printf(" Adding\n"); */
876                     ADD_SQUARE(tmpsquare);
877                 } else {
878 /*                    printf(" Destroying\n"); */
879                     sfree(tmpsquare);
880                 }
881             }
882         }
883         sfree(square);
884 /*        printf("\n\n"); */
885     }
886
887     while ((square = delpos234(lightable_squares_gettable, 0)) != NULL)
888         sfree(square);
889     freetree234(lightable_squares_gettable);
890     freetree234(lightable_squares_sorted);
891
892     /* Copy out all the clues */
893     for (j = 0; j < params->h; ++j) {
894         for (i = 0; i < params->w; ++i) {
895             c = SQUARE_STATE(i, j);
896             LV_CLUE_AT(state, i, j) = '0';
897             if (SQUARE_STATE(i-1, j) != c) ++LV_CLUE_AT(state, i, j);
898             if (SQUARE_STATE(i+1, j) != c) ++LV_CLUE_AT(state, i, j);
899             if (SQUARE_STATE(i, j-1) != c) ++LV_CLUE_AT(state, i, j);
900             if (SQUARE_STATE(i, j+1) != c) ++LV_CLUE_AT(state, i, j);
901         }
902     }
903
904     sfree(board);
905     return clues;
906 }
907
908 static solver_state *solve_game_rec(const solver_state *sstate, int diff);
909
910 static int game_has_unique_soln(const game_state *state, int diff)
911 {
912     int ret;
913     solver_state *sstate_new;
914     solver_state *sstate = new_solver_state((game_state *)state);
915     
916     sstate_new = solve_game_rec(sstate, diff);
917
918     ret = (sstate_new->solver_status == SOLVER_SOLVED);
919
920     free_solver_state(sstate_new);
921     free_solver_state(sstate);
922
923     return ret;
924 }
925
926 /* Remove clues one at a time at random. */
927 static game_state *remove_clues(game_state *state, random_state *rs, int diff)
928 {
929     int *square_list, squares;
930     game_state *ret = dup_game(state), *saved_ret;
931     int n;
932
933     /* We need to remove some clues.  We'll do this by forming a list of all
934      * available equivalence classes, shuffling it, then going along one at a
935      * time clearing every member of each equivalence class, where removing a
936      * class doesn't render the board unsolvable. */
937     squares = state->w * state->h;
938     square_list = snewn(squares, int);
939     for (n = 0; n < squares; ++n) {
940         square_list[n] = n;
941     }
942
943     shuffle(square_list, squares, sizeof(int), rs);
944     
945     for (n = 0; n < squares; ++n) {
946         saved_ret = dup_game(ret);
947         LV_CLUE_AT(ret, square_list[n] % state->w,
948                    square_list[n] / state->w) = ' ';
949         if (game_has_unique_soln(ret, diff)) {
950             free_game(saved_ret);
951         } else {
952             free_game(ret);
953             ret = saved_ret;
954         }
955     }
956     sfree(square_list);
957
958     return ret;
959 }
960
961 static char *validate_desc(game_params *params, char *desc);
962
963 static char *new_game_desc(game_params *params, random_state *rs,
964                            char **aux, int interactive)
965 {
966     /* solution and description both use run-length encoding in obvious ways */
967     char *retval;
968     char *description = snewn(SQUARE_COUNT(params) + 1, char);
969     char *dp = description;
970     int i, j;
971     int empty_count;
972     game_state *state = snew(game_state), *state_new;
973
974     state->h = params->h;
975     state->w = params->w;
976
977     state->hl = snewn(HL_COUNT(params), char);
978     state->vl = snewn(VL_COUNT(params), char);
979
980 newboard_please:
981     memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
982     memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
983
984     state->solved = state->cheated = FALSE;
985     state->recursion_depth = params->rec;
986
987     /* Get a new random solvable board with all its clues filled in.  Yes, this
988      * can loop for ever if the params are suitably unfavourable, but
989      * preventing games smaller than 4x4 seems to stop this happening */
990
991     do {
992         state->clues = new_fullyclued_board(params, rs);
993     } while (!game_has_unique_soln(state, params->diff));
994
995     state_new = remove_clues(state, rs, params->diff);
996     free_game(state);
997     state = state_new;
998
999     if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1000         /* Board is too easy */
1001         goto newboard_please;
1002     }
1003
1004     empty_count = 0;
1005     for (j = 0; j < params->h; ++j) {
1006         for (i = 0; i < params->w; ++i) {
1007             if (CLUE_AT(state, i, j) == ' ') {
1008                 if (empty_count > 25) {
1009                     dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1010                     empty_count = 0;
1011                 }
1012                 empty_count++;
1013             } else {
1014                 if (empty_count) {
1015                     dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1016                     empty_count = 0;
1017                 }
1018                 dp += sprintf(dp, "%c", (int)(CLUE_AT(state, i, j)));
1019             }
1020         }
1021     }
1022     if (empty_count)
1023         dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1024
1025     free_game(state);
1026     retval = dupstr(description);
1027     sfree(description);
1028     
1029     assert(!validate_desc(params, retval));
1030
1031     return retval;
1032 }
1033
1034 /* We require that the params pass the test in validate_params and that the
1035  * description fills the entire game area */
1036 static char *validate_desc(game_params *params, char *desc)
1037 {
1038     int count = 0;
1039
1040     for (; *desc; ++desc) {
1041         if (*desc >= '0' && *desc <= '9') {
1042             count++;
1043             continue;
1044         }
1045         if (*desc >= 'a') {
1046             count += *desc - 'a' + 1;
1047             continue;
1048         }
1049         return "Unknown character in description";
1050     }
1051
1052     if (count < SQUARE_COUNT(params))
1053         return "Description too short for board size";
1054     if (count > SQUARE_COUNT(params))
1055         return "Description too long for board size";
1056
1057     return NULL;
1058 }
1059
1060 static game_state *new_game(midend *me, game_params *params, char *desc)
1061 {
1062     int i,j;
1063     game_state *state = snew(game_state);
1064     int empties_to_make = 0;
1065     int n;
1066     const char *dp = desc;
1067
1068     state->recursion_depth = 0; /* XXX pending removal, probably */
1069     
1070     state->h = params->h;
1071     state->w = params->w;
1072
1073     state->clues = snewn(SQUARE_COUNT(params), char);
1074     state->hl    = snewn(HL_COUNT(params), char);
1075     state->vl    = snewn(VL_COUNT(params), char);
1076
1077     state->solved = state->cheated = FALSE;
1078
1079     for (j = 0 ; j < params->h; ++j) {
1080         for (i = 0 ; i < params->w; ++i) {
1081             if (empties_to_make) {
1082                 empties_to_make--;
1083                 LV_CLUE_AT(state, i, j) = ' ';
1084                 continue;
1085             }
1086
1087             assert(*dp);
1088             n = *dp - '0';
1089             if (n >=0 && n < 10) {
1090                 LV_CLUE_AT(state, i, j) = *dp;
1091             } else {
1092                 n = *dp - 'a' + 1;
1093                 assert(n > 0);
1094                 LV_CLUE_AT(state, i, j) = ' ';
1095                 empties_to_make = n - 1;
1096             }
1097             ++dp;
1098         }
1099     }
1100
1101     memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1102     memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1103
1104     return state;
1105 }
1106
1107 enum { LOOP_NONE=0, LOOP_SOLN, LOOP_NOT_SOLN };
1108
1109 /* Starting at dot [i,j] moves around 'state' removing lines until it's clear
1110  * whether or not the starting dot was on a loop.  Returns boolean specifying
1111  * whether a loop was found.  loop_status calls this and assumes that if state
1112  * has any lines set, this function will always remove at least one.  */
1113 static int destructively_find_loop(game_state *state)
1114 {
1115     int a, b, i, j, new_i, new_j, n;
1116     char *lp;
1117
1118     lp = (char *)memchr(state->hl, LINE_YES, HL_COUNT(state));
1119     if (!lp) {
1120         /* We know we're going to return false but we have to fulfil our
1121          * contract */
1122         lp = (char *)memchr(state->vl, LINE_YES, VL_COUNT(state));
1123         if (lp)
1124             *lp = LINE_NO;
1125         
1126         return FALSE;
1127     }
1128
1129     n = lp - state->hl;
1130
1131     i = n % state->w;
1132     j = n / state->w;
1133
1134     assert(i + j * state->w == n); /* because I'm feeling stupid */
1135     /* Save start position */
1136     a = i;
1137     b = j;
1138
1139     /* Delete one line from the potential loop */
1140     if (LEFTOF_DOT(state, i, j) == LINE_YES) {
1141         LV_LEFTOF_DOT(state, i, j) = LINE_NO;
1142         i--;
1143     } else if (ABOVE_DOT(state, i, j) == LINE_YES) {
1144         LV_ABOVE_DOT(state, i, j) = LINE_NO;
1145         j--;
1146     } else if (RIGHTOF_DOT(state, i, j) == LINE_YES) {
1147         LV_RIGHTOF_DOT(state, i, j) = LINE_NO;
1148         i++;
1149     } else if (BELOW_DOT(state, i, j) == LINE_YES) {
1150         LV_BELOW_DOT(state, i, j) = LINE_NO;
1151         j++;
1152     } else {
1153         return FALSE;
1154     }
1155
1156     do {
1157         /* From the current position of [i,j] there needs to be exactly one
1158          * line */
1159         new_i = new_j = -1;
1160
1161 #define HANDLE_DIR(dir_dot, x, y)                    \
1162         if (dir_dot(state, i, j) == LINE_YES) {      \
1163             if (new_i != -1 || new_j != -1)          \
1164                 return FALSE;                        \
1165             new_i = (i)+(x);                         \
1166             new_j = (j)+(y);                         \
1167             LV_##dir_dot(state, i, j) = LINE_NO;     \
1168         }
1169         HANDLE_DIR(ABOVE_DOT,    0, -1);
1170         HANDLE_DIR(BELOW_DOT,    0, +1);
1171         HANDLE_DIR(LEFTOF_DOT,  -1,  0);
1172         HANDLE_DIR(RIGHTOF_DOT, +1,  0);
1173 #undef HANDLE_DIR
1174         if (new_i == -1 || new_j == -1) {
1175             return FALSE;
1176         }
1177
1178         i = new_i;
1179         j = new_j;
1180     } while (i != a || j != b);
1181
1182     return TRUE;
1183 }
1184
1185 static int loop_status(game_state *state)
1186 {
1187     int i, j, n;
1188     game_state *tmpstate;
1189     int loop_found = FALSE, non_loop_found = FALSE, any_lines_found = FALSE;
1190
1191 #define BAD_LOOP_FOUND \
1192     do { free_game(tmpstate); return LOOP_NOT_SOLN; } while(0)
1193
1194     /* Repeatedly look for loops until we either run out of lines to consider
1195      * or discover for sure that the board fails on the grounds of having no
1196      * loop */
1197     tmpstate = dup_game(state);
1198
1199     while (TRUE) {
1200         if (!memchr(tmpstate->hl, LINE_YES, HL_COUNT(tmpstate)) &&
1201             !memchr(tmpstate->vl, LINE_YES, VL_COUNT(tmpstate))) {
1202             break;
1203         }
1204         any_lines_found = TRUE;
1205
1206         if (loop_found) 
1207             BAD_LOOP_FOUND;
1208         if (destructively_find_loop(tmpstate)) {
1209             loop_found = TRUE;
1210             if (non_loop_found)
1211                 BAD_LOOP_FOUND;
1212         } else {
1213             non_loop_found = TRUE;
1214         }
1215     }
1216
1217     free_game(tmpstate);
1218
1219     if (!any_lines_found)
1220         return LOOP_NONE;
1221     
1222     if (non_loop_found) {
1223         assert(!loop_found); /* should have dealt with this already */
1224         return LOOP_NONE;
1225     }
1226
1227     /* Check that every clue is satisfied */
1228     for (j = 0; j < state->h; ++j) {
1229         for (i = 0; i < state->w; ++i) {
1230             n = CLUE_AT(state, i, j);
1231             if (n != ' ') {
1232                 if (square_order(state, i, j, LINE_YES) != n - '0') {
1233                     return LOOP_NOT_SOLN;
1234                 }
1235             }
1236         }
1237     }
1238
1239     return LOOP_SOLN;
1240 }
1241
1242 /* Sums the lengths of the numbers in range [0,n) */
1243 /* See equivalent function in solo.c for justification of this. */
1244 static int len_0_to_n(int n)
1245 {
1246     int len = 1; /* Counting 0 as a bit of a special case */
1247     int i;
1248
1249     for (i = 1; i < n; i *= 10) {
1250         len += max(n - i, 0);
1251     }
1252
1253     return len;
1254 }
1255
1256 static char *encode_solve_move(const game_state *state)
1257 {
1258     int len, i, j;
1259     char *ret, *p;
1260     /* This is going to return a string representing the moves needed to set
1261      * every line in a grid to be the same as the ones in 'state'.  The exact
1262      * length of this string is predictable. */
1263
1264     len = 1;  /* Count the 'S' prefix */
1265     /* Numbers in horizontal lines */
1266     /* Horizontal lines, x position */
1267     len += len_0_to_n(state->w) * (state->h + 1);
1268     /* Horizontal lines, y position */
1269     len += len_0_to_n(state->h + 1) * (state->w);
1270     /* Vertical lines, y position */
1271     len += len_0_to_n(state->h) * (state->w + 1);
1272     /* Vertical lines, x position */
1273     len += len_0_to_n(state->w + 1) * (state->h);
1274     /* For each line we also have two letters and a comma */
1275     len += 3 * (HL_COUNT(state) + VL_COUNT(state));
1276
1277     ret = snewn(len + 1, char);
1278     p = ret;
1279
1280     p += sprintf(p, "S");
1281
1282     for (j = 0; j < state->h + 1; ++j) {
1283         for (i = 0; i < state->w; ++i) {
1284             switch (RIGHTOF_DOT(state, i, j)) {
1285                 case LINE_YES:
1286                     p += sprintf(p, "%d,%dhy", i, j);
1287                     break;
1288                 case LINE_NO:
1289                     p += sprintf(p, "%d,%dhn", i, j);
1290                     break;
1291 /*                default: */
1292                     /* I'm going to forgive this because I think the results
1293                      * are cute. */
1294 /*                    assert(!"Solver produced incomplete solution!"); */
1295             }
1296         }
1297     }
1298
1299     for (j = 0; j < state->h; ++j) {
1300         for (i = 0; i < state->w + 1; ++i) {
1301             switch (BELOW_DOT(state, i, j)) {
1302                 case LINE_YES:
1303                     p += sprintf(p, "%d,%dvy", i, j);
1304                     break;
1305                 case LINE_NO:
1306                     p += sprintf(p, "%d,%dvn", i, j);
1307                     break;
1308 /*                default: */
1309                     /* I'm going to forgive this because I think the results
1310                      * are cute. */
1311 /*                    assert(!"Solver produced incomplete solution!"); */
1312             }
1313         }
1314     }
1315
1316     /* No point in doing sums like that if they're going to be wrong */
1317     assert(strlen(ret) == (size_t)len);
1318     return ret;
1319 }
1320
1321 /* BEGIN SOLVER IMPLEMENTATION */
1322
1323    /* For each pair of lines through each dot we store a bit for whether
1324     * exactly one of those lines is ON, and in separate arrays we store whether
1325     * at least one is on and whether at most 1 is on.  (If we know both or
1326     * neither is on that's already stored more directly.)  That's six bits per
1327     * dot.  Bit number n represents the lines shown in dot_type_dirs[n]. */
1328
1329 enum dline {
1330     DLINE_VERT  = 0,
1331     DLINE_HORIZ = 1,
1332     DLINE_UL    = 2,
1333     DLINE_DR    = 3,
1334     DLINE_UR    = 4,
1335     DLINE_DL    = 5
1336 };
1337
1338 #define OPP_DLINE(dline) (dline ^ 1)
1339    
1340
1341 #define SQUARE_DLINES                                                          \
1342                    HANDLE_DLINE(DLINE_UL, RIGHTOF_SQUARE, BELOW_SQUARE, 1, 1); \
1343                    HANDLE_DLINE(DLINE_UR, LEFTOF_SQUARE,  BELOW_SQUARE, 0, 1); \
1344                    HANDLE_DLINE(DLINE_DL, RIGHTOF_SQUARE, ABOVE_SQUARE, 1, 0); \
1345                    HANDLE_DLINE(DLINE_DR, LEFTOF_SQUARE,  ABOVE_SQUARE, 0, 0); 
1346
1347 #define DOT_DLINES                                                       \
1348                    HANDLE_DLINE(DLINE_VERT,  ABOVE_DOT,  BELOW_DOT);     \
1349                    HANDLE_DLINE(DLINE_HORIZ, LEFTOF_DOT, RIGHTOF_DOT);   \
1350                    HANDLE_DLINE(DLINE_UL,    ABOVE_DOT,  LEFTOF_DOT);    \
1351                    HANDLE_DLINE(DLINE_UR,    ABOVE_DOT,  RIGHTOF_DOT);   \
1352                    HANDLE_DLINE(DLINE_DL,    BELOW_DOT,  LEFTOF_DOT);    \
1353                    HANDLE_DLINE(DLINE_DR,    BELOW_DOT,  RIGHTOF_DOT); 
1354
1355 static void array_setall(char *array, char from, char to, int len)
1356 {
1357     char *p = array, *p_old = p;
1358     int len_remaining = len;
1359
1360     while ((p = memchr(p, from, len_remaining))) {
1361         *p = to;
1362         len_remaining -= p - p_old;
1363         p_old = p;
1364     }
1365 }
1366
1367
1368 static int game_states_equal(const game_state *state1,
1369                              const game_state *state2) 
1370 {
1371     /* This deliberately doesn't check _all_ fields, just the ones that make a
1372      * game state 'interesting' from the POV of the solver */
1373     /* XXX review this */
1374     if (state1 == state2)
1375         return 1;
1376
1377     if (!state1 || !state2)
1378         return 0;
1379
1380     if (state1->w != state2->w || state1->h != state2->h)
1381         return 0;
1382
1383     if (memcmp(state1->hl, state2->hl, HL_COUNT(state1)))
1384         return 0;
1385
1386     if (memcmp(state1->vl, state2->vl, VL_COUNT(state1)))
1387         return 0;
1388
1389     return 1;
1390 }
1391
1392 static int solver_states_equal(const solver_state *sstate1,
1393                                const solver_state *sstate2)
1394 {
1395     if (!sstate1) {
1396         if (!sstate2)
1397             return TRUE;
1398         else
1399             return FALSE;
1400     }
1401     
1402     if (!game_states_equal(sstate1->state, sstate2->state)) {
1403         return 0;
1404     }
1405
1406     /* XXX fields missing, needs review */
1407     /* XXX we're deliberately not looking at solver_state as it's only a cache */
1408
1409     if (memcmp(sstate1->dot_atleastone, sstate2->dot_atleastone,
1410                DOT_COUNT(sstate1->state))) {
1411         return 0;
1412     }
1413
1414     if (memcmp(sstate1->dot_atmostone, sstate2->dot_atmostone,
1415                DOT_COUNT(sstate1->state))) {
1416         return 0;
1417     }
1418
1419     /* handle dline_identical here */
1420
1421     return 1;
1422 }
1423
1424 static void dot_setall_dlines(solver_state *sstate, enum dline dl, int i, int j,
1425                               enum line_state line_old, enum line_state line_new) 
1426 {
1427     game_state *state = sstate->state;
1428
1429     /* First line in dline */
1430     switch (dl) {                                             
1431         case DLINE_UL:                                                  
1432         case DLINE_UR:                                                  
1433         case DLINE_VERT:                                                  
1434             if (j > 0 && ABOVE_DOT(state, i, j) == line_old)            
1435                 LV_ABOVE_DOT(state, i, j) = line_new;                   
1436             break;                                                          
1437         case DLINE_DL:                                                  
1438         case DLINE_DR:                                                  
1439             if (j <= (state)->h && BELOW_DOT(state, i, j) == line_old)  
1440                 LV_BELOW_DOT(state, i, j) = line_new;                   
1441             break;
1442         case DLINE_HORIZ:                                                  
1443             if (i > 0 && LEFTOF_DOT(state, i, j) == line_old)           
1444                 LV_LEFTOF_DOT(state, i, j) = line_new;                  
1445             break;                                                          
1446     }
1447
1448     /* Second line in dline */
1449     switch (dl) {                                             
1450         case DLINE_UL:                                                  
1451         case DLINE_DL:                                                  
1452             if (i > 0 && LEFTOF_DOT(state, i, j) == line_old)           
1453                 LV_LEFTOF_DOT(state, i, j) = line_new;                  
1454             break;                                                          
1455         case DLINE_UR:                                                  
1456         case DLINE_DR:                                                  
1457         case DLINE_HORIZ:                                                  
1458             if (i <= (state)->w && RIGHTOF_DOT(state, i, j) == line_old)
1459                 LV_RIGHTOF_DOT(state, i, j) = line_new;                 
1460             break;                                                          
1461         case DLINE_VERT:                                                  
1462             if (j <= (state)->h && BELOW_DOT(state, i, j) == line_old)  
1463                 LV_BELOW_DOT(state, i, j) = line_new;                   
1464             break;                                                          
1465     }
1466 }
1467
1468 static void update_solver_status(solver_state *sstate)
1469 {
1470     if (sstate->solver_status == SOLVER_INCOMPLETE) {
1471         switch (loop_status(sstate->state)) {
1472             case LOOP_NONE:
1473                 sstate->solver_status = SOLVER_INCOMPLETE;
1474                 break;
1475             case LOOP_SOLN:
1476                 if (sstate->solver_status != SOLVER_AMBIGUOUS)
1477                     sstate->solver_status = SOLVER_SOLVED;
1478                 break;
1479             case LOOP_NOT_SOLN:
1480                 sstate->solver_status = SOLVER_MISTAKE;
1481                 break;
1482         }
1483     }
1484 }
1485
1486 #if 0
1487 /* This will fail an assertion if {dx,dy} are anything other than {-1,0}, {1,0}
1488  * {0,-1} or {0,1} */
1489 static int line_status_from_point(const game_state *state,
1490                                   int x, int y, int dx, int dy)
1491 {
1492     if (dx == -1 && dy ==  0)
1493         return LEFTOF_DOT(state, x, y);
1494     if (dx ==  1 && dy ==  0)
1495         return RIGHTOF_DOT(state, x, y);
1496     if (dx ==  0 && dy == -1)
1497         return ABOVE_DOT(state, x, y);
1498     if (dx ==  0 && dy ==  1)
1499         return BELOW_DOT(state, x, y);
1500
1501     assert(!"Illegal dx or dy in line_status_from_point");
1502     return 0;
1503 }
1504 #endif
1505
1506 /* This will return a dynamically allocated solver_state containing the (more)
1507  * solved grid */
1508 static solver_state *solve_game_rec(const solver_state *sstate_start, int diff)
1509 {
1510    int i, j;
1511    int current_yes, current_no, desired;
1512    solver_state *sstate, *sstate_saved, *sstate_tmp;
1513    int t;
1514 /*   char *text; */
1515    solver_state *sstate_rec_solved;
1516    int recursive_soln_count;
1517
1518 #if 0
1519    printf("solve_game_rec: recursion_remaining = %d\n", 
1520           sstate_start->recursion_remaining);
1521 #endif
1522
1523    sstate = dup_solver_state((solver_state *)sstate_start);
1524
1525 #if 0
1526    text = game_text_format(sstate->state);
1527    printf("%s\n", text);
1528    sfree(text);
1529 #endif
1530    
1531 #define RETURN_IF_SOLVED                                 \
1532    do {                                                  \
1533        update_solver_status(sstate);                     \
1534        if (sstate->solver_status != SOLVER_INCOMPLETE) { \
1535            free_solver_state(sstate_saved);              \
1536            return sstate;                                \
1537        }                                                 \
1538    } while (0)
1539
1540 #define FOUND_MISTAKE                                    \
1541    do {                                                  \
1542        sstate->solver_status = SOLVER_MISTAKE;           \
1543        free_solver_state(sstate_saved);                  \
1544        return sstate;                                    \
1545    } while (0)
1546
1547
1548    sstate_saved = NULL;
1549    RETURN_IF_SOLVED;
1550
1551 nonrecursive_solver:
1552    
1553    while (1) {
1554        sstate_saved = dup_solver_state(sstate);
1555
1556        /* First we do the 'easy' work, that might cause concrete results */
1557
1558        /* Per-square deductions */
1559        for (j = 0; j < sstate->state->h; ++j) {
1560            for (i = 0; i < sstate->state->w; ++i) {
1561                /* Begin rules that look at the clue (if there is one) */
1562                desired = CLUE_AT(sstate->state, i, j);
1563                if (desired == ' ')
1564                    continue;
1565                desired = desired - '0';
1566                current_yes = square_order(sstate->state, i, j, LINE_YES);
1567                current_no  = square_order(sstate->state, i, j, LINE_NO);
1568
1569                if (desired < current_yes) 
1570                    FOUND_MISTAKE;
1571                if (desired == current_yes) {
1572                    square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1573                    continue;
1574                }
1575
1576                if (4 - desired < current_no) 
1577                    FOUND_MISTAKE;
1578                if (4 - desired == current_no) {
1579                    square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES);
1580                }
1581            }
1582        }
1583
1584        RETURN_IF_SOLVED;
1585
1586        /* Per-dot deductions */
1587        for (j = 0; j < sstate->state->h + 1; ++j) {
1588            for (i = 0; i < sstate->state->w + 1; ++i) {
1589                switch (dot_order(sstate->state, i, j, LINE_YES)) {
1590                case 0:
1591                    if (dot_order(sstate->state, i, j, LINE_NO) == 3) {
1592                        dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1593                    }
1594                    break;
1595                case 1:
1596                    switch (dot_order(sstate->state, i, j, LINE_NO)) {
1597 #define H1(dline, dir1_dot, dir2_dot, dot_howmany)                             \
1598                        if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN) {    \
1599                            if (dir2_dot(sstate->state, i, j) == LINE_UNKNOWN){ \
1600                                sstate->dot_howmany                             \
1601                                  [i + (sstate->state->w + 1) * j] |= 1<<dline; \
1602                            }                                                   \
1603                        }
1604                        case 1: 
1605                            if (diff > DIFF_EASY) {
1606 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1607                            H1(dline, dir1_dot, dir2_dot, dot_atleastone)
1608                                /* 1 yes, 1 no, so exactly one of unknowns is
1609                                 * yes */
1610                                DOT_DLINES;
1611 #undef HANDLE_DLINE
1612                            }
1613                            /* fall through */
1614                        case 0: 
1615                            if (diff > DIFF_EASY) {
1616 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1617                            H1(dline, dir1_dot, dir2_dot, dot_atmostone)
1618                                /* 1 yes, fewer than 2 no, so at most one of
1619                                 * unknowns is yes */
1620                                DOT_DLINES;
1621 #undef HANDLE_DLINE
1622                            }
1623 #undef H1
1624                            break;
1625                        case 2: /* 1 yes, 2 no */
1626                            dot_setall(sstate->state, i, j, 
1627                                       LINE_UNKNOWN, LINE_YES);
1628                            break;
1629                    }
1630                    break;
1631                case 2:
1632                    dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1633                    break;
1634                case 3:
1635                    FOUND_MISTAKE;
1636                    break;
1637                }
1638                if (diff > DIFF_EASY) {
1639 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1640                if (sstate->dot_atleastone                                     \
1641                      [i + (sstate->state->w + 1) * j] & 1<<dline) {           \
1642                    sstate->dot_atmostone                                      \
1643                      [i + (sstate->state->w + 1) * j] |= 1<<OPP_DLINE(dline); \
1644                }
1645                    /* If at least one of a dline in a dot is YES, at most one
1646                     * of the opposite dline to that dot must be YES. */
1647                    DOT_DLINES;
1648                }
1649 #undef HANDLE_DLINE
1650            }
1651        }
1652        
1653        /* More obscure per-square operations */
1654        for (j = 0; j < sstate->state->h; ++j) {
1655            for (i = 0; i < sstate->state->w; ++i) {
1656 #define H1(dline, dir1_sq, dir2_sq, a, b, dot_howmany, line_query, line_set)  \
1657                if (sstate->dot_howmany[i+a + (sstate->state->w + 1) * (j+b)] &\
1658                        1<<dline) {                                            \
1659                    t = dir1_sq(sstate->state, i, j);                          \
1660                    if (t == line_query)                                       \
1661                        dir2_sq(sstate->state, i, j) = line_set;               \
1662                    else {                                                     \
1663                        t = dir2_sq(sstate->state, i, j);                      \
1664                        if (t == line_query)                                   \
1665                            dir1_sq(sstate->state, i, j) = line_set;           \
1666                    }                                                          \
1667                }
1668                if (diff > DIFF_EASY) {
1669 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                 \
1670                H1(dline, dir1_sq, dir2_sq, a, b, dot_atmostone,     \
1671                   LINE_YES, LINE_NO)
1672                    /* If at most one of the DLINE is on, and one is definitely
1673                     * on, set the other to definitely off */
1674                    SQUARE_DLINES;
1675 #undef HANDLE_DLINE
1676                }
1677
1678                if (diff > DIFF_EASY) {
1679 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                 \
1680                H1(dline, dir1_sq, dir2_sq, a, b, dot_atleastone,    \
1681                   LINE_NO, LINE_YES)
1682                    /* If at least one of the DLINE is on, and one is definitely
1683                     * off, set the other to definitely on */
1684                    SQUARE_DLINES;
1685 #undef HANDLE_DLINE
1686                }
1687 #undef H1
1688
1689                switch (CLUE_AT(sstate->state, i, j)) {
1690                    case '0':
1691                    case '1':
1692                        if (diff > DIFF_EASY) {
1693 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                          \
1694                        /* At most one of any DLINE can be set */             \
1695                        sstate->dot_atmostone                                 \
1696                          [i+a + (sstate->state->w + 1) * (j+b)] |= 1<<dline; \
1697                        /* This DLINE provides enough YESes to solve the clue */\
1698                        if (sstate->dot_atleastone                            \
1699                              [i+a + (sstate->state->w + 1) * (j+b)] &        \
1700                            1<<dline) {                                       \
1701                            dot_setall_dlines(sstate, OPP_DLINE(dline),       \
1702                                              i+(1-a), j+(1-b),               \
1703                                              LINE_UNKNOWN, LINE_NO);         \
1704                        }
1705                            SQUARE_DLINES;
1706 #undef HANDLE_DLINE
1707                        }
1708                        break;
1709                    case '2':
1710                        if (diff > DIFF_EASY) {
1711 #define H1(dline, dot_at1one, dot_at2one, a, b)                          \
1712                if (sstate->dot_at1one                                    \
1713                      [i+a + (sstate->state->w + 1) * (j+b)] &            \
1714                    1<<dline) {                                           \
1715                    sstate->dot_at2one                                    \
1716                      [i+(1-a) + (sstate->state->w + 1) * (j+(1-b))] |=   \
1717                        1<<OPP_DLINE(dline);                              \
1718                }
1719 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)             \
1720             H1(dline, dot_atleastone, dot_atmostone, a, b);     \
1721             H1(dline, dot_atmostone, dot_atleastone, a, b); 
1722                            /* If at least one of one DLINE is set, at most one
1723                             * of the opposing one is and vice versa */
1724                            SQUARE_DLINES;
1725                        }
1726 #undef HANDLE_DLINE
1727 #undef H1
1728                        break;
1729                    case '3':
1730                    case '4':
1731                        if (diff > DIFF_EASY) {
1732 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                           \
1733                        /* At least one of any DLINE can be set */             \
1734                        sstate->dot_atleastone                                 \
1735                          [i+a + (sstate->state->w + 1) * (j+b)] |= 1<<dline;  \
1736                        /* This DLINE provides enough NOs to solve the clue */ \
1737                        if (sstate->dot_atmostone                              \
1738                              [i+a + (sstate->state->w + 1) * (j+b)] &         \
1739                            1<<dline) {                                        \
1740                            dot_setall_dlines(sstate, OPP_DLINE(dline),        \
1741                                              i+(1-a), j+(1-b),                \
1742                                              LINE_UNKNOWN, LINE_YES);         \
1743                        }
1744                            SQUARE_DLINES;
1745 #undef HANDLE_DLINE
1746                        }
1747                        break;
1748                }
1749            }
1750        }
1751
1752        if (solver_states_equal(sstate, sstate_saved)) {
1753            int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
1754            int d;
1755
1756            /*
1757             * Go through the grid and update for all the new edges.
1758             * Since merge_dots() is idempotent, the simplest way to
1759             * do this is just to update for _all_ the edges.
1760             * 
1761             * Also, while we're here, we count the edges, count the
1762             * clues, count the satisfied clues, and count the
1763             * satisfied-minus-one clues.
1764             */
1765            for (j = 0; j <= sstate->state->h; ++j) {
1766                for (i = 0; i <= sstate->state->w; ++i) {
1767                    if (RIGHTOF_DOT(sstate->state, i, j) == LINE_YES) {
1768                        merge_dots(sstate, i, j, i+1, j);
1769                        edgecount++;
1770                    }
1771                    if (BELOW_DOT(sstate->state, i, j) == LINE_YES) {
1772                        merge_dots(sstate, i, j, i, j+1);
1773                        edgecount++;
1774                    }
1775
1776                    if (CLUE_AT(sstate->state, i, j) != ' ') {
1777                        int c = CLUE_AT(sstate->state, i, j) - '0';
1778                        int o = square_order(sstate->state, i, j, LINE_YES);
1779                        if (o == c)
1780                            satclues++;
1781                        else if (o == c-1)
1782                            sm1clues++;
1783                        clues++;
1784                    }
1785                }
1786            }
1787
1788            /*
1789             * Now go through looking for LINE_UNKNOWN edges which
1790             * connect two dots that are already in the same
1791             * equivalence class. If we find one, test to see if the
1792             * loop it would create is a solution.
1793             */
1794            for (j = 0; j <= sstate->state->h; ++j) {
1795                for (i = 0; i <= sstate->state->w; ++i) {
1796                    for (d = 0; d < 2; d++) {
1797                        int i2, j2, eqclass, val;
1798
1799                        if (d == 0) {
1800                            if (RIGHTOF_DOT(sstate->state, i, j) !=
1801                                LINE_UNKNOWN)
1802                                continue;
1803                            i2 = i+1;
1804                            j2 = j;
1805                        } else {
1806                            if (BELOW_DOT(sstate->state, i, j) !=
1807                                LINE_UNKNOWN)
1808                                continue;
1809                            i2 = i;
1810                            j2 = j+1;
1811                        }
1812
1813                        eqclass = dsf_canonify(sstate->dotdsf,
1814                                               j * (sstate->state->w+1) + i);
1815                        if (eqclass != dsf_canonify(sstate->dotdsf,
1816                                                    j2 * (sstate->state->w+1) +
1817                                                    i2))
1818                            continue;
1819
1820                        val = LINE_NO;  /* loop is bad until proven otherwise */
1821
1822                        /*
1823                         * This edge would form a loop. Next
1824                         * question: how long would the loop be?
1825                         * Would it equal the total number of edges
1826                         * (plus the one we'd be adding if we added
1827                         * it)?
1828                         */
1829                        if (sstate->looplen[eqclass] == edgecount + 1) {
1830                            int sm1_nearby;
1831                            int cx, cy;
1832
1833                            /*
1834                             * This edge would form a loop which
1835                             * took in all the edges in the entire
1836                             * grid. So now we need to work out
1837                             * whether it would be a valid solution
1838                             * to the puzzle, which means we have to
1839                             * check if it satisfies all the clues.
1840                             * This means that every clue must be
1841                             * either satisfied or satisfied-minus-
1842                             * 1, and also that the number of
1843                             * satisfied-minus-1 clues must be at
1844                             * most two and they must lie on either
1845                             * side of this edge.
1846                             */
1847                            sm1_nearby = 0;
1848                            cx = i - (j2-j);
1849                            cy = j - (i2-i);
1850                            if (CLUE_AT(sstate->state, cx,cy) != ' ' &&
1851                                square_order(sstate->state, cx,cy, LINE_YES) ==
1852                                CLUE_AT(sstate->state, cx,cy) - '0' - 1)
1853                                sm1_nearby++;
1854                            if (CLUE_AT(sstate->state, i, j) != ' ' &&
1855                                square_order(sstate->state, i, j, LINE_YES) ==
1856                                CLUE_AT(sstate->state, i, j) - '0' - 1)
1857                                sm1_nearby++;
1858                            if (sm1clues == sm1_nearby &&
1859                                sm1clues + satclues == clues)
1860                                val = LINE_YES;  /* loop is good! */
1861                        }
1862
1863                        /*
1864                         * Right. Now we know that adding this edge
1865                         * would form a loop, and we know whether
1866                         * that loop would be a viable solution or
1867                         * not.
1868                         * 
1869                         * If adding this edge produces a solution,
1870                         * then we know we've found _a_ solution but
1871                         * we don't know that it's _the_ solution -
1872                         * if it were provably the solution then
1873                         * we'd have deduced this edge some time ago
1874                         * without the need to do loop detection. So
1875                         * in this state we return SOLVER_AMBIGUOUS,
1876                         * which has the effect that hitting Solve
1877                         * on a user-provided puzzle will fill in a
1878                         * solution but using the solver to
1879                         * construct new puzzles won't consider this
1880                         * a reasonable deduction for the user to
1881                         * make.
1882                         */
1883                        if (d == 0)
1884                            LV_RIGHTOF_DOT(sstate->state, i, j) = val;
1885                        else
1886                            LV_BELOW_DOT(sstate->state, i, j) = val;
1887                        if (val == LINE_YES) {
1888                            sstate->solver_status = SOLVER_AMBIGUOUS;
1889                            goto finished_loop_checking;
1890                        }
1891                    }
1892                }
1893            }
1894
1895            finished_loop_checking:
1896
1897            RETURN_IF_SOLVED;
1898        }
1899
1900        if (solver_states_equal(sstate, sstate_saved)) {
1901            /* Solver has stopped making progress so we terminate */
1902            free_solver_state(sstate_saved); 
1903            break;
1904        }
1905
1906        free_solver_state(sstate_saved); 
1907    }
1908
1909    if (sstate->solver_status == SOLVER_SOLVED ||
1910        sstate->solver_status == SOLVER_AMBIGUOUS) {
1911        /* s/LINE_UNKNOWN/LINE_NO/g */
1912        array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO, 
1913                HL_COUNT(sstate->state));
1914        array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO, 
1915                VL_COUNT(sstate->state));
1916        return sstate;
1917    }
1918
1919    /* Perform recursive calls */
1920    if (sstate->recursion_remaining) {
1921        sstate_saved = dup_solver_state(sstate);
1922
1923        sstate->recursion_remaining--;
1924
1925        recursive_soln_count = 0;
1926        sstate_rec_solved = NULL;
1927
1928        /* Memory management: 
1929         * sstate_saved won't be modified but needs to be freed when we have
1930         * finished with it.
1931         * sstate is expected to contain our 'best' solution by the time we
1932         * finish this section of code.  It's the thing we'll try adding lines
1933         * to, seeing if they make it more solvable.
1934         * If sstate_rec_solved is non-NULL, it will supersede sstate
1935         * eventually.  sstate_tmp should not hold a value persistently.
1936         */
1937
1938        /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
1939         * of the possibility of additional solutions.  So as soon as we have a
1940         * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
1941         * if we get a SOLVER_SOLVED we want to keep trying in case we find
1942         * further solutions and have to mark it ambiguous.
1943         */
1944
1945 #define DO_RECURSIVE_CALL(dir_dot)                                         \
1946        if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) {                 \
1947            debug(("Trying " #dir_dot " at [%d,%d]\n", i, j));               \
1948            LV_##dir_dot(sstate->state, i, j) = LINE_YES;                   \
1949            sstate_tmp = solve_game_rec(sstate, diff);                      \
1950            switch (sstate_tmp->solver_status) {                            \
1951                case SOLVER_AMBIGUOUS:                                      \
1952                    debug(("Solver ambiguous, returning\n"));                \
1953                    sstate_rec_solved = sstate_tmp;                         \
1954                    goto finished_recursion;                                \
1955                case SOLVER_SOLVED:                                         \
1956                    switch (++recursive_soln_count) {                       \
1957                        case 1:                                             \
1958                            debug(("One solution found\n"));                 \
1959                            sstate_rec_solved = sstate_tmp;                 \
1960                            break;                                          \
1961                        case 2:                                             \
1962                            debug(("Ambiguous solutions found\n"));          \
1963                            free_solver_state(sstate_tmp);                  \
1964                            sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS;\
1965                            goto finished_recursion;                        \
1966                        default:                                            \
1967                            assert(!"recursive_soln_count out of range");   \
1968                            break;                                          \
1969                    }                                                       \
1970                    break;                                                  \
1971                case SOLVER_MISTAKE:                                        \
1972                    debug(("Non-solution found\n"));                         \
1973                    free_solver_state(sstate_tmp);                          \
1974                    free_solver_state(sstate_saved);                        \
1975                    LV_##dir_dot(sstate->state, i, j) = LINE_NO;            \
1976                    goto nonrecursive_solver;                               \
1977                case SOLVER_INCOMPLETE:                                     \
1978                    debug(("Recursive step inconclusive\n"));                \
1979                    free_solver_state(sstate_tmp);                          \
1980                    break;                                                  \
1981            }                                                               \
1982            free_solver_state(sstate);                                      \
1983            sstate = dup_solver_state(sstate_saved);                        \
1984        }
1985        
1986        for (j = 0; j < sstate->state->h + 1; ++j) {
1987            for (i = 0; i < sstate->state->w + 1; ++i) {
1988                /* Only perform recursive calls on 'loose ends' */
1989                if (dot_order(sstate->state, i, j, LINE_YES) == 1) {
1990                    DO_RECURSIVE_CALL(LEFTOF_DOT);
1991                    DO_RECURSIVE_CALL(RIGHTOF_DOT);
1992                    DO_RECURSIVE_CALL(ABOVE_DOT);
1993                    DO_RECURSIVE_CALL(BELOW_DOT);
1994                }
1995            }
1996        }
1997
1998 finished_recursion:
1999
2000        if (sstate_rec_solved) {
2001            free_solver_state(sstate);
2002            sstate = sstate_rec_solved;
2003        } 
2004    }
2005
2006    return sstate;
2007 }
2008
2009 /* XXX bits of solver that may come in handy one day */
2010 #if 0
2011 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                         \
2012                    /* dline from this dot that's entirely unknown must have 
2013                     * both lines identical */                           \
2014                    if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN &&       \
2015                        dir2_dot(sstate->state, i, j) == LINE_UNKNOWN) {       \
2016                        sstate->dline_identical[i + (sstate->state->w + 1) * j] |= \
2017                            1<<dline;                                    \
2018                    } else if (sstate->dline_identical[i +
2019                                                       (sstate->state->w + 1) * j] &\
2020                               1<<dline) {                                   \
2021                        /* If they're identical and one is known do the obvious 
2022                         * thing */                                      \
2023                        t = dir1_dot(sstate->state, i, j);                     \
2024                        if (t != LINE_UNKNOWN)                           \
2025                            dir2_dot(sstate->state, i, j) = t;                 \
2026                        else {                                           \
2027                            t = dir2_dot(sstate->state, i, j);                 \
2028                            if (t != LINE_UNKNOWN)                       \
2029                                dir1_dot(sstate->state, i, j) = t;             \
2030                        }                                                \
2031                    }                                                    \
2032                    DOT_DLINES;
2033 #undef HANDLE_DLINE
2034 #endif
2035
2036 #if 0
2037 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2038                        if (sstate->dline_identical[i+a +                     \
2039                                                    (sstate->state->w + 1) * (j+b)] &\
2040                            1<<dline) {                                       \
2041                            dir1_sq(sstate->state, i, j) = LINE_YES;                \
2042                            dir2_sq(sstate->state, i, j) = LINE_YES;                \
2043                        }
2044                        /* If two lines are the same they must be on */
2045                        SQUARE_DLINES;
2046 #undef HANDLE_DLINE
2047 #endif
2048
2049
2050 #if 0
2051 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2052                if (sstate->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] &  \
2053                    1<<dline) {                                   \
2054                    if (square_order(sstate->state, i, j,  LINE_UNKNOWN) - 1 ==  \
2055                        CLUE_AT(sstate->state, i, j) - '0') {      \
2056                        square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
2057                            /* XXX the following may overwrite known data! */ \
2058                        dir1_sq(sstate->state, i, j) = LINE_UNKNOWN;  \
2059                        dir2_sq(sstate->state, i, j) = LINE_UNKNOWN;  \
2060                    }                                  \
2061                }
2062                SQUARE_DLINES;
2063 #undef HANDLE_DLINE
2064 #endif
2065
2066 #if 0
2067 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2068                        if (sstate->dline_identical[i+a + 
2069                                                    (sstate->state->w + 1) * (j+b)] &\
2070                            1<<dline) {                                       \
2071                            dir1_sq(sstate->state, i, j) = LINE_NO;                 \
2072                            dir2_sq(sstate->state, i, j) = LINE_NO;                 \
2073                        }
2074                        /* If two lines are the same they must be off */
2075                        SQUARE_DLINES;
2076 #undef HANDLE_DLINE
2077 #endif
2078
2079 static char *solve_game(game_state *state, game_state *currstate,
2080                         char *aux, char **error)
2081 {
2082     char *soln = NULL;
2083     solver_state *sstate, *new_sstate;
2084
2085     sstate = new_solver_state(state);
2086     new_sstate = solve_game_rec(sstate, DIFFCOUNT);
2087
2088     if (new_sstate->solver_status == SOLVER_SOLVED) {
2089         soln = encode_solve_move(new_sstate->state);
2090     } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2091         soln = encode_solve_move(new_sstate->state);
2092         /**error = "Solver found ambiguous solutions"; */
2093     } else {
2094         soln = encode_solve_move(new_sstate->state);
2095         /**error = "Solver failed"; */
2096     }
2097
2098     free_solver_state(new_sstate);
2099     free_solver_state(sstate);
2100
2101     return soln;
2102 }
2103
2104 static char *game_text_format(game_state *state)
2105 {
2106     int i, j;
2107     int len;
2108     char *ret, *rp;
2109
2110     len = (2 * state->w + 2) * (2 * state->h + 1);
2111     rp = ret = snewn(len + 1, char);
2112     
2113 #define DRAW_HL                          \
2114     switch (ABOVE_SQUARE(state, i, j)) { \
2115         case LINE_YES:                   \
2116             rp += sprintf(rp, " -");     \
2117             break;                       \
2118         case LINE_NO:                    \
2119             rp += sprintf(rp, " x");     \
2120             break;                       \
2121         case LINE_UNKNOWN:               \
2122             rp += sprintf(rp, "  ");     \
2123             break;                       \
2124         default:                         \
2125             assert(!"Illegal line state for HL");\
2126     }
2127
2128 #define DRAW_VL                          \
2129     switch (LEFTOF_SQUARE(state, i, j)) {\
2130         case LINE_YES:                   \
2131             rp += sprintf(rp, "|");      \
2132             break;                       \
2133         case LINE_NO:                    \
2134             rp += sprintf(rp, "x");      \
2135             break;                       \
2136         case LINE_UNKNOWN:               \
2137             rp += sprintf(rp, " ");      \
2138             break;                       \
2139         default:                         \
2140             assert(!"Illegal line state for VL");\
2141     }
2142     
2143     for (j = 0; j < state->h; ++j) {
2144         for (i = 0; i < state->w; ++i) {
2145             DRAW_HL;
2146         }
2147         rp += sprintf(rp, " \n");
2148         for (i = 0; i < state->w; ++i) {
2149             DRAW_VL;
2150             rp += sprintf(rp, "%c", (int)(CLUE_AT(state, i, j)));
2151         }
2152         DRAW_VL;
2153         rp += sprintf(rp, "\n");
2154     }
2155     for (i = 0; i < state->w; ++i) {
2156         DRAW_HL;
2157     }
2158     rp += sprintf(rp, " \n");
2159     
2160     assert(strlen(ret) == len);
2161     return ret;
2162 }
2163
2164 static game_ui *new_ui(game_state *state)
2165 {
2166     return NULL;
2167 }
2168
2169 static void free_ui(game_ui *ui)
2170 {
2171 }
2172
2173 static char *encode_ui(game_ui *ui)
2174 {
2175     return NULL;
2176 }
2177
2178 static void decode_ui(game_ui *ui, char *encoding)
2179 {
2180 }
2181
2182 static void game_changed_state(game_ui *ui, game_state *oldstate,
2183                                game_state *newstate)
2184 {
2185 }
2186
2187 struct game_drawstate {
2188     int started;
2189     int tilesize;
2190     int flashing;
2191     char *hl, *vl;
2192     char *clue_error;
2193 };
2194
2195 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2196                             int x, int y, int button)
2197 {
2198     int hl_selected;
2199     int i, j, p, q; 
2200     char *ret, buf[80];
2201     char button_char = ' ';
2202     enum line_state old_state;
2203
2204     button &= ~MOD_MASK;
2205
2206     /* Around each line is a diamond-shaped region where points within that
2207      * region are closer to this line than any other.  We assume any click
2208      * within a line's diamond was meant for that line.  It would all be a lot
2209      * simpler if the / and % operators respected modulo arithmetic properly
2210      * for negative numbers. */
2211     
2212     x -= BORDER;
2213     y -= BORDER;
2214
2215     /* Get the coordinates of the square the click was in */
2216     i = (x + TILE_SIZE) / TILE_SIZE - 1; 
2217     j = (y + TILE_SIZE) / TILE_SIZE - 1;
2218
2219     /* Get the precise position inside square [i,j] */
2220     p = (x + TILE_SIZE) % TILE_SIZE;
2221     q = (y + TILE_SIZE) % TILE_SIZE;
2222
2223     /* After this bit of magic [i,j] will correspond to the point either above
2224      * or to the left of the line selected */
2225     if (p > q) { 
2226         if (TILE_SIZE - p > q) {
2227             hl_selected = TRUE;
2228         } else {
2229             hl_selected = FALSE;
2230             ++i;
2231         }
2232     } else {
2233         if (TILE_SIZE - q > p) {
2234             hl_selected = FALSE;
2235         } else {
2236             hl_selected = TRUE;
2237             ++j;
2238         }
2239     }
2240
2241     if (i < 0 || j < 0)
2242         return NULL;
2243
2244     if (hl_selected) {
2245         if (i >= state->w || j >= state->h + 1)
2246             return NULL;
2247     } else { 
2248         if (i >= state->w + 1 || j >= state->h)
2249             return NULL;
2250     }
2251
2252     /* I think it's only possible to play this game with mouse clicks, sorry */
2253     /* Maybe will add mouse drag support some time */
2254     if (hl_selected)
2255         old_state = RIGHTOF_DOT(state, i, j);
2256     else
2257         old_state = BELOW_DOT(state, i, j);
2258
2259     switch (button) {
2260         case LEFT_BUTTON:
2261             switch (old_state) {
2262                 case LINE_UNKNOWN:
2263                     button_char = 'y';
2264                     break;
2265                 case LINE_YES:
2266                 case LINE_NO:
2267                     button_char = 'u';
2268                     break;
2269             }
2270             break;
2271         case MIDDLE_BUTTON:
2272             button_char = 'u';
2273             break;
2274         case RIGHT_BUTTON:
2275             switch (old_state) {
2276                 case LINE_UNKNOWN:
2277                     button_char = 'n';
2278                     break;
2279                 case LINE_NO:
2280                 case LINE_YES:
2281                     button_char = 'u';
2282                     break;
2283             }
2284             break;
2285         default:
2286             return NULL;
2287     }
2288
2289
2290     sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
2291     ret = dupstr(buf);
2292
2293     return ret;
2294 }
2295
2296 static game_state *execute_move(game_state *state, char *move)
2297 {
2298     int i, j;
2299     game_state *newstate = dup_game(state);
2300
2301     if (move[0] == 'S') {
2302         move++;
2303         newstate->cheated = TRUE;
2304     }
2305
2306     while (*move) {
2307         i = atoi(move);
2308         move = strchr(move, ',');
2309         if (!move)
2310             goto fail;
2311         j = atoi(++move);
2312         move += strspn(move, "1234567890");
2313         switch (*(move++)) {
2314             case 'h':
2315                 if (i >= newstate->w || j > newstate->h)
2316                     goto fail;
2317                 switch (*(move++)) {
2318                     case 'y':
2319                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
2320                         break;
2321                     case 'n':
2322                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
2323                         break;
2324                     case 'u':
2325                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
2326                         break;
2327                     default:
2328                         goto fail;
2329                 }
2330                 break;
2331             case 'v':
2332                 if (i > newstate->w || j >= newstate->h)
2333                     goto fail;
2334                 switch (*(move++)) {
2335                     case 'y':
2336                         LV_BELOW_DOT(newstate, i, j) = LINE_YES;
2337                         break;
2338                     case 'n':
2339                         LV_BELOW_DOT(newstate, i, j) = LINE_NO;
2340                         break;
2341                     case 'u':
2342                         LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
2343                         break;
2344                     default:
2345                         goto fail;
2346                 }
2347                 break;
2348             default:
2349                 goto fail;
2350         }
2351     }
2352
2353     /*
2354      * Check for completion.
2355      */
2356     i = 0;                             /* placate optimiser */
2357     for (j = 0; j <= newstate->h; j++) {
2358         for (i = 0; i < newstate->w; i++)
2359             if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
2360                 break;
2361         if (i < newstate->w)
2362             break;
2363     }
2364     if (j <= newstate->h) {
2365         int prevdir = 'R';
2366         int x = i, y = j;
2367         int looplen, count;
2368
2369         /*
2370          * We've found a horizontal edge at (i,j). Follow it round
2371          * to see if it's part of a loop.
2372          */
2373         looplen = 0;
2374         while (1) {
2375             int order = dot_order(newstate, x, y, LINE_YES);
2376             if (order != 2)
2377                 goto completion_check_done;
2378
2379             if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
2380                 x--;
2381                 prevdir = 'R';
2382             } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
2383                        prevdir != 'R') {
2384                 x++;
2385                 prevdir = 'L';
2386             } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
2387                        prevdir != 'U') {
2388                 y--;
2389                 prevdir = 'D';
2390             } else if (BELOW_DOT(newstate, x, y) == LINE_YES &&
2391                        prevdir != 'D') {
2392                 y++;
2393                 prevdir = 'U';
2394             } else {
2395                 assert(!"Can't happen");   /* dot_order guarantees success */
2396             }
2397
2398             looplen++;
2399
2400             if (x == i && y == j)
2401                 break;
2402         }
2403
2404         if (x != i || y != j || looplen == 0)
2405             goto completion_check_done;
2406
2407         /*
2408          * We've traced our way round a loop, and we know how many
2409          * line segments were involved. Count _all_ the line
2410          * segments in the grid, to see if the loop includes them
2411          * all.
2412          */
2413         count = 0;
2414         for (j = 0; j <= newstate->h; j++)
2415             for (i = 0; i <= newstate->w; i++)
2416                 count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
2417                           (BELOW_DOT(newstate, i, j) == LINE_YES));
2418         assert(count >= looplen);
2419         if (count != looplen)
2420             goto completion_check_done;
2421
2422         /*
2423          * The grid contains one closed loop and nothing else.
2424          * Check that all the clues are satisfied.
2425          */
2426         for (j = 0; j < newstate->h; ++j) {
2427             for (i = 0; i < newstate->w; ++i) {
2428                 int n = CLUE_AT(newstate, i, j);
2429                 if (n != ' ') {
2430                     if (square_order(newstate, i, j, LINE_YES) != n - '0') {
2431                         goto completion_check_done;
2432                     }
2433                 }
2434             }
2435         }
2436
2437         /*
2438          * Completed!
2439          */
2440         newstate->solved = TRUE;
2441     }
2442
2443 completion_check_done:
2444     return newstate;
2445
2446 fail:
2447     free_game(newstate);
2448     return NULL;
2449 }
2450
2451 /* ----------------------------------------------------------------------
2452  * Drawing routines.
2453  */
2454
2455 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
2456
2457 static void game_compute_size(game_params *params, int tilesize,
2458                               int *x, int *y)
2459 {
2460     struct { int tilesize; } ads, *ds = &ads;
2461     ads.tilesize = tilesize;
2462
2463     *x = SIZE(params->w);
2464     *y = SIZE(params->h);
2465 }
2466
2467 static void game_set_size(drawing *dr, game_drawstate *ds,
2468                           game_params *params, int tilesize)
2469 {
2470     ds->tilesize = tilesize;
2471 }
2472
2473 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2474 {
2475     float *ret = snewn(4 * NCOLOURS, float);
2476
2477     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2478
2479     ret[COL_FOREGROUND * 3 + 0] = 0.0F;
2480     ret[COL_FOREGROUND * 3 + 1] = 0.0F;
2481     ret[COL_FOREGROUND * 3 + 2] = 0.0F;
2482
2483     ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2484     ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2485     ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2486
2487     ret[COL_MISTAKE * 3 + 0] = 1.0F;
2488     ret[COL_MISTAKE * 3 + 1] = 0.0F;
2489     ret[COL_MISTAKE * 3 + 2] = 0.0F;
2490
2491     *ncolours = NCOLOURS;
2492     return ret;
2493 }
2494
2495 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2496 {
2497     struct game_drawstate *ds = snew(struct game_drawstate);
2498
2499     ds->tilesize = 0;
2500     ds->started = 0;
2501     ds->hl = snewn(HL_COUNT(state), char);
2502     ds->vl = snewn(VL_COUNT(state), char);
2503     ds->clue_error = snewn(SQUARE_COUNT(state), char);
2504     ds->flashing = 0;
2505
2506     memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
2507     memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
2508     memset(ds->clue_error, 0, SQUARE_COUNT(state));
2509
2510     return ds;
2511 }
2512
2513 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2514 {
2515     sfree(ds->clue_error);
2516     sfree(ds->hl);
2517     sfree(ds->vl);
2518     sfree(ds);
2519 }
2520
2521 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2522                         game_state *state, int dir, game_ui *ui,
2523                         float animtime, float flashtime)
2524 {
2525     int i, j, n;
2526     int w = state->w, h = state->h;
2527     char c[2];
2528     int line_colour, flash_changed;
2529     int clue_mistake;
2530
2531     if (!ds->started) {
2532         /*
2533          * The initial contents of the window are not guaranteed and
2534          * can vary with front ends. To be on the safe side, all games
2535          * should start by drawing a big background-colour rectangle
2536          * covering the whole window.
2537          */
2538         draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
2539
2540         /* Draw dots */
2541         for (j = 0; j < h + 1; ++j) {
2542             for (i = 0; i < w + 1; ++i) {
2543                 draw_rect(dr, 
2544                           BORDER + i * TILE_SIZE - LINEWIDTH/2,
2545                           BORDER + j * TILE_SIZE - LINEWIDTH/2,
2546                           LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
2547             }
2548         }
2549
2550         /* Draw clues */
2551         for (j = 0; j < h; ++j) {
2552             for (i = 0; i < w; ++i) {
2553                 c[0] = CLUE_AT(state, i, j);
2554                 c[1] = '\0';
2555                 draw_text(dr, 
2556                           BORDER + i * TILE_SIZE + TILE_SIZE/2,
2557                           BORDER + j * TILE_SIZE + TILE_SIZE/2,
2558                           FONT_VARIABLE, TILE_SIZE/2, 
2559                           ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
2560             }
2561         }
2562         draw_update(dr, 0, 0,
2563                     state->w * TILE_SIZE + 2*BORDER + 1,
2564                     state->h * TILE_SIZE + 2*BORDER + 1);
2565         ds->started = TRUE;
2566     }
2567
2568     if (flashtime > 0 && 
2569         (flashtime <= FLASH_TIME/3 ||
2570          flashtime >= FLASH_TIME*2/3)) {
2571         flash_changed = !ds->flashing;
2572         ds->flashing = TRUE;
2573         line_colour = COL_HIGHLIGHT;
2574     } else {
2575         flash_changed = ds->flashing;
2576         ds->flashing = FALSE;
2577         line_colour = COL_FOREGROUND;
2578     }
2579
2580 #define CROSS_SIZE (3 * LINEWIDTH / 2)
2581     
2582     /* Redraw clue colours if necessary */
2583     for (j = 0; j < h; ++j) {
2584         for (i = 0; i < w; ++i) {
2585             c[0] = CLUE_AT(state, i, j);
2586             c[1] = '\0';
2587             if (c[0] == ' ')
2588                 continue;
2589
2590             n = c[0] - '0';
2591             assert(n >= 0 && n <= 4);
2592
2593             clue_mistake = (square_order(state, i, j, LINE_YES) > n     || 
2594                             square_order(state, i, j, LINE_NO ) > (4-n));
2595
2596             if (clue_mistake != ds->clue_error[j * w + i]) {
2597                 draw_rect(dr, 
2598                           BORDER + i * TILE_SIZE + CROSS_SIZE,
2599                           BORDER + j * TILE_SIZE + CROSS_SIZE,
2600                           TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
2601                           COL_BACKGROUND);
2602                 draw_text(dr, 
2603                           BORDER + i * TILE_SIZE + TILE_SIZE/2,
2604                           BORDER + j * TILE_SIZE + TILE_SIZE/2,
2605                           FONT_VARIABLE, TILE_SIZE/2, 
2606                           ALIGN_VCENTRE | ALIGN_HCENTRE, 
2607                           clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
2608                 draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
2609                             TILE_SIZE, TILE_SIZE);
2610
2611                 ds->clue_error[j * w + i] = clue_mistake;
2612             }
2613         }
2614     }
2615
2616     /* I've also had a request to colour lines red if they make a non-solution
2617      * loop, or if more than two lines go into any point.  I think that would
2618      * be good some time. */
2619
2620 #define CLEAR_VL(i, j) do {                                                \
2621                            draw_rect(dr,                                   \
2622                                  BORDER + i * TILE_SIZE - CROSS_SIZE,      \
2623                                  BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,     \
2624                                  CROSS_SIZE * 2,                           \
2625                                  TILE_SIZE - LINEWIDTH,                    \
2626                                  COL_BACKGROUND);                          \
2627                            draw_update(dr,                                 \
2628                                        BORDER + i * TILE_SIZE - CROSS_SIZE, \
2629                                        BORDER + j * TILE_SIZE - CROSS_SIZE, \
2630                                        CROSS_SIZE*2,                       \
2631                                        TILE_SIZE + CROSS_SIZE*2);          \
2632                         } while (0)
2633
2634 #define CLEAR_HL(i, j) do {                                                \
2635                            draw_rect(dr,                                   \
2636                                  BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,     \
2637                                  BORDER + j * TILE_SIZE - CROSS_SIZE,      \
2638                                  TILE_SIZE - LINEWIDTH,                    \
2639                                  CROSS_SIZE * 2,                           \
2640                                  COL_BACKGROUND);                          \
2641                            draw_update(dr,                                 \
2642                                        BORDER + i * TILE_SIZE - CROSS_SIZE, \
2643                                        BORDER + j * TILE_SIZE - CROSS_SIZE, \
2644                                        TILE_SIZE + CROSS_SIZE*2,           \
2645                                        CROSS_SIZE*2);                      \
2646                         } while (0)
2647
2648     /* Vertical lines */
2649     for (j = 0; j < h; ++j) {
2650         for (i = 0; i < w + 1; ++i) {
2651             switch (BELOW_DOT(state, i, j)) {
2652                 case LINE_UNKNOWN:
2653                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2654                         CLEAR_VL(i, j);
2655                     }
2656                     break;
2657                 case LINE_YES:
2658                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j) ||
2659                         flash_changed) {
2660                         CLEAR_VL(i, j);
2661                         draw_rect(dr,
2662                                   BORDER + i * TILE_SIZE - LINEWIDTH/2,
2663                                   BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2664                                   LINEWIDTH, TILE_SIZE - LINEWIDTH, 
2665                                   line_colour);
2666                     }
2667                     break;
2668                 case LINE_NO:
2669                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2670                         CLEAR_VL(i, j);
2671                         draw_line(dr,
2672                                  BORDER + i * TILE_SIZE - CROSS_SIZE,
2673                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2674                                  BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2675                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2676                                   COL_FOREGROUND);
2677                         draw_line(dr,
2678                                  BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2679                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2680                                  BORDER + i * TILE_SIZE - CROSS_SIZE,
2681                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2682                                   COL_FOREGROUND);
2683                     }
2684                     break;
2685             }
2686             ds->vl[i + (w + 1) * j] = BELOW_DOT(state, i, j);
2687         }
2688     }
2689
2690     /* Horizontal lines */
2691     for (j = 0; j < h + 1; ++j) {
2692         for (i = 0; i < w; ++i) {
2693             switch (RIGHTOF_DOT(state, i, j)) {
2694                 case LINE_UNKNOWN:
2695                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2696                         CLEAR_HL(i, j);
2697                 }
2698                         break;
2699                 case LINE_YES:
2700                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j) ||
2701                         flash_changed) {
2702                         CLEAR_HL(i, j);
2703                         draw_rect(dr,
2704                                   BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2705                                   BORDER + j * TILE_SIZE - LINEWIDTH/2,
2706                                   TILE_SIZE - LINEWIDTH, LINEWIDTH, 
2707                                   line_colour);
2708                         break;
2709                     }
2710                 case LINE_NO:
2711                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2712                         CLEAR_HL(i, j);
2713                         draw_line(dr,
2714                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2715                                  BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2716                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2717                                  BORDER + j * TILE_SIZE - CROSS_SIZE,
2718                                   COL_FOREGROUND);
2719                         draw_line(dr,
2720                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2721                                  BORDER + j * TILE_SIZE - CROSS_SIZE,
2722                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2723                                  BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2724                                   COL_FOREGROUND);
2725                         break;
2726                     }
2727             }
2728             ds->hl[i + w * j] = RIGHTOF_DOT(state, i, j);
2729         }
2730     }
2731 }
2732
2733 static float game_anim_length(game_state *oldstate, game_state *newstate,
2734                               int dir, game_ui *ui)
2735 {
2736     return 0.0F;
2737 }
2738
2739 static float game_flash_length(game_state *oldstate, game_state *newstate,
2740                                int dir, game_ui *ui)
2741 {
2742     if (!oldstate->solved  &&  newstate->solved &&
2743         !oldstate->cheated && !newstate->cheated) {
2744         return FLASH_TIME;
2745     }
2746
2747     return 0.0F;
2748 }
2749
2750 static int game_wants_statusbar(void)
2751 {
2752     return FALSE;
2753 }
2754
2755 static int game_timing_state(game_state *state, game_ui *ui)
2756 {
2757     return TRUE;
2758 }
2759
2760 static void game_print_size(game_params *params, float *x, float *y)
2761 {
2762     int pw, ph;
2763
2764     /*
2765      * I'll use 7mm squares by default.
2766      */
2767     game_compute_size(params, 700, &pw, &ph);
2768     *x = pw / 100.0F;
2769     *y = ph / 100.0F;
2770 }
2771
2772 static void game_print(drawing *dr, game_state *state, int tilesize)
2773 {
2774     int w = state->w, h = state->h;
2775     int ink = print_mono_colour(dr, 0);
2776     int x, y;
2777     game_drawstate ads, *ds = &ads;
2778     ds->tilesize = tilesize;
2779
2780     /*
2781      * Dots. I'll deliberately make the dots a bit wider than the
2782      * lines, so you can still see them. (And also because it's
2783      * annoyingly tricky to make them _exactly_ the same size...)
2784      */
2785     for (y = 0; y <= h; y++)
2786         for (x = 0; x <= w; x++)
2787             draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
2788                         LINEWIDTH, ink, ink);
2789
2790     /*
2791      * Clues.
2792      */
2793     for (y = 0; y < h; y++)
2794         for (x = 0; x < w; x++)
2795             if (CLUE_AT(state, x, y) != ' ') {
2796                 char c[2];
2797
2798                 c[0] = CLUE_AT(state, x, y);
2799                 c[1] = '\0';
2800                 draw_text(dr, 
2801                           BORDER + x * TILE_SIZE + TILE_SIZE/2,
2802                           BORDER + y * TILE_SIZE + TILE_SIZE/2,
2803                           FONT_VARIABLE, TILE_SIZE/2, 
2804                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
2805             }
2806
2807     /*
2808      * Lines. (At the moment, I'm not bothering with crosses.)
2809      */
2810     for (y = 0; y <= h; y++)
2811         for (x = 0; x < w; x++)
2812             if (RIGHTOF_DOT(state, x, y) == LINE_YES)
2813                 draw_rect(dr, BORDER + x * TILE_SIZE,
2814                           BORDER + y * TILE_SIZE - LINEWIDTH/2,
2815                           TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
2816     for (y = 0; y < h; y++)
2817         for (x = 0; x <= w; x++)
2818             if (BELOW_DOT(state, x, y) == LINE_YES)
2819                 draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
2820                           BORDER + y * TILE_SIZE,
2821                           (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
2822 }
2823
2824 #ifdef COMBINED
2825 #define thegame loopy
2826 #endif
2827
2828 const struct game thegame = {
2829     "Loopy", "games.loopy",
2830     default_params,
2831     game_fetch_preset,
2832     decode_params,
2833     encode_params,
2834     free_params,
2835     dup_params,
2836     TRUE, game_configure, custom_params,
2837     validate_params,
2838     new_game_desc,
2839     validate_desc,
2840     new_game,
2841     dup_game,
2842     free_game,
2843     1, solve_game,
2844     TRUE, game_text_format,
2845     new_ui,
2846     free_ui,
2847     encode_ui,
2848     decode_ui,
2849     game_changed_state,
2850     interpret_move,
2851     execute_move,
2852     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2853     game_colours,
2854     game_new_drawstate,
2855     game_free_drawstate,
2856     game_redraw,
2857     game_anim_length,
2858     game_flash_length,
2859     TRUE, FALSE, game_print_size, game_print,
2860     game_wants_statusbar,
2861     FALSE, game_timing_state,
2862     0,                                       /* mouse_priorities */
2863 };