chiark / gitweb /
Optimisation patch from Mike: remember which squares we've entirely
[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, w, h;
1511    int current_yes, current_no, desired;
1512    solver_state *sstate, *sstate_saved, *sstate_tmp;
1513    int t;
1514    solver_state *sstate_rec_solved;
1515    int recursive_soln_count;
1516    char *square_solved;
1517    char *dot_solved;
1518
1519    h = sstate_start->state->h;
1520    w = sstate_start->state->w;
1521
1522    dot_solved = snewn(DOT_COUNT(sstate_start->state), char);
1523    square_solved = snewn(SQUARE_COUNT(sstate_start->state), char);
1524    memset(dot_solved, FALSE, DOT_COUNT(sstate_start->state));
1525    memset(square_solved, FALSE, SQUARE_COUNT(sstate_start->state));
1526
1527 #if 0
1528    printf("solve_game_rec: recursion_remaining = %d\n", 
1529           sstate_start->recursion_remaining);
1530 #endif
1531
1532    sstate = dup_solver_state((solver_state *)sstate_start);
1533
1534 #define RETURN_IF_SOLVED                                 \
1535    do {                                                  \
1536        update_solver_status(sstate);                     \
1537        if (sstate->solver_status != SOLVER_INCOMPLETE) { \
1538            sfree(dot_solved); sfree(square_solved);      \
1539            free_solver_state(sstate_saved);              \
1540            return sstate;                                \
1541        }                                                 \
1542    } while (0)
1543
1544 #define FOUND_MISTAKE                                    \
1545    do {                                                  \
1546        sstate->solver_status = SOLVER_MISTAKE;           \
1547        sfree(dot_solved); sfree(square_solved);          \
1548        free_solver_state(sstate_saved);                  \
1549        return sstate;                                    \
1550    } while (0)
1551
1552
1553    sstate_saved = NULL;
1554    RETURN_IF_SOLVED;
1555
1556 nonrecursive_solver:
1557    
1558    while (1) {
1559        sstate_saved = dup_solver_state(sstate);
1560
1561        /* First we do the 'easy' work, that might cause concrete results */
1562
1563        /* Per-square deductions */
1564        for (j = 0; j < h; ++j) {
1565            for (i = 0; i < w; ++i) {
1566                /* Begin rules that look at the clue (if there is one) */
1567                if (square_solved[i + j*w])
1568                    continue;
1569
1570                desired = CLUE_AT(sstate->state, i, j);
1571                if (desired == ' ')
1572                    continue;
1573
1574                desired = desired - '0';
1575                current_yes = square_order(sstate->state, i, j, LINE_YES);
1576                current_no  = square_order(sstate->state, i, j, LINE_NO);
1577
1578                if (current_yes + current_no == 4)  {
1579                    square_solved[i + j*w] = TRUE;
1580                    continue;
1581                }
1582
1583                if (desired < current_yes) 
1584                    FOUND_MISTAKE;
1585                if (desired == current_yes) {
1586                    square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1587                    square_solved[i + j*w] = TRUE;
1588                    continue;
1589                }
1590
1591                if (4 - desired < current_no) 
1592                    FOUND_MISTAKE;
1593                if (4 - desired == current_no) {
1594                    square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES);
1595                    square_solved[i + j*w] = TRUE;
1596                }
1597            }
1598        }
1599
1600        RETURN_IF_SOLVED;
1601
1602        /* Per-dot deductions */
1603        for (j = 0; j < h + 1; ++j) {
1604            for (i = 0; i < w + 1; ++i) {
1605                if (dot_solved[i + j*(w+1)])
1606                    continue;
1607
1608                switch (dot_order(sstate->state, i, j, LINE_YES)) {
1609                case 0:
1610                    switch (dot_order(sstate->state, i, j, LINE_NO)) {
1611                        case 3:
1612                            dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1613                            /* fall through */
1614                        case 4:
1615                            dot_solved[i + j*(w+1)] = TRUE;
1616                            break;
1617                    }
1618                    break;
1619                case 1:
1620                    switch (dot_order(sstate->state, i, j, LINE_NO)) {
1621 #define H1(dline, dir1_dot, dir2_dot, dot_howmany)                             \
1622                        if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN) {    \
1623                            if (dir2_dot(sstate->state, i, j) == LINE_UNKNOWN){ \
1624                                sstate->dot_howmany                             \
1625                                  [i + (w + 1) * j] |= 1<<dline;                \
1626                            }                                                   \
1627                        }
1628                        case 1: 
1629                            if (diff > DIFF_EASY) {
1630 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1631                            H1(dline, dir1_dot, dir2_dot, dot_atleastone)
1632                                /* 1 yes, 1 no, so exactly one of unknowns is
1633                                 * yes */
1634                                DOT_DLINES;
1635 #undef HANDLE_DLINE
1636                            }
1637                            /* fall through */
1638                        case 0: 
1639                            if (diff > DIFF_EASY) {
1640 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1641                            H1(dline, dir1_dot, dir2_dot, dot_atmostone)
1642                                /* 1 yes, fewer than 2 no, so at most one of
1643                                 * unknowns is yes */
1644                                DOT_DLINES;
1645 #undef HANDLE_DLINE
1646                            }
1647 #undef H1
1648                            break;
1649                        case 2: /* 1 yes, 2 no */
1650                            dot_setall(sstate->state, i, j, 
1651                                       LINE_UNKNOWN, LINE_YES);
1652                            dot_solved[i + j*(w+1)] = TRUE;
1653                            break;
1654                        case 3: /* 1 yes, 3 no */
1655                            FOUND_MISTAKE;
1656                            break;
1657                    }
1658                    break;
1659                case 2:
1660                    dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1661                    dot_solved[i + j*(w+1)] = TRUE;
1662                    break;
1663                case 3:
1664                case 4:
1665                    FOUND_MISTAKE;
1666                    break;
1667                }
1668                if (diff > DIFF_EASY) {
1669 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                               \
1670                if (sstate->dot_atleastone                                     \
1671                      [i + (w + 1) * j] & 1<<dline) {                          \
1672                    sstate->dot_atmostone                                      \
1673                      [i + (w + 1) * j] |= 1<<OPP_DLINE(dline);                \
1674                }
1675                    /* If at least one of a dline in a dot is YES, at most one
1676                     * of the opposite dline to that dot must be YES. */
1677                    DOT_DLINES;
1678                }
1679 #undef HANDLE_DLINE
1680            }
1681        }
1682        
1683        /* More obscure per-square operations */
1684        for (j = 0; j < h; ++j) {
1685            for (i = 0; i < w; ++i) {
1686                if (square_solved[i + j*w])
1687                    continue;
1688
1689 #define H1(dline, dir1_sq, dir2_sq, a, b, dot_howmany, line_query, line_set)  \
1690                if (sstate->dot_howmany[i+a + (w + 1) * (j+b)] & 1<<dline) {   \
1691                    t = dir1_sq(sstate->state, i, j);                          \
1692                    if (t == line_query)                                       \
1693                        dir2_sq(sstate->state, i, j) = line_set;               \
1694                    else {                                                     \
1695                        t = dir2_sq(sstate->state, i, j);                      \
1696                        if (t == line_query)                                   \
1697                            dir1_sq(sstate->state, i, j) = line_set;           \
1698                    }                                                          \
1699                }
1700                if (diff > DIFF_EASY) {
1701 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                 \
1702                H1(dline, dir1_sq, dir2_sq, a, b, dot_atmostone,     \
1703                   LINE_YES, LINE_NO)
1704                    /* If at most one of the DLINE is on, and one is definitely
1705                     * on, set the other to definitely off */
1706                    SQUARE_DLINES;
1707 #undef HANDLE_DLINE
1708                }
1709
1710                if (diff > DIFF_EASY) {
1711 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                 \
1712                H1(dline, dir1_sq, dir2_sq, a, b, dot_atleastone,    \
1713                   LINE_NO, LINE_YES)
1714                    /* If at least one of the DLINE is on, and one is definitely
1715                     * off, set the other to definitely on */
1716                    SQUARE_DLINES;
1717 #undef HANDLE_DLINE
1718                }
1719 #undef H1
1720
1721                switch (CLUE_AT(sstate->state, i, j)) {
1722                    case '1':
1723                        if (diff > DIFF_EASY) {
1724 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                          \
1725                        /* At most one of any DLINE can be set */             \
1726                        sstate->dot_atmostone                                 \
1727                          [i+a + (w + 1) * (j+b)] |= 1<<dline;                \
1728                        /* This DLINE provides enough YESes to solve the clue */\
1729                        if (sstate->dot_atleastone                            \
1730                              [i+a + (w + 1) * (j+b)] & 1<<dline) {           \
1731                            dot_setall_dlines(sstate, OPP_DLINE(dline),       \
1732                                              i+(1-a), j+(1-b),               \
1733                                              LINE_UNKNOWN, LINE_NO);         \
1734                        }
1735                            SQUARE_DLINES;
1736 #undef HANDLE_DLINE
1737                        }
1738                        break;
1739                    case '2':
1740                        if (diff > DIFF_EASY) {
1741 #define H1(dline, dot_at1one, dot_at2one, a, b)                          \
1742                if (sstate->dot_at1one                                    \
1743                      [i+a + (w + 1) * (j+b)] & 1<<dline) {               \
1744                    sstate->dot_at2one                                    \
1745                      [i+(1-a) + (w + 1) * (j+(1-b))] |= 1<<OPP_DLINE(dline); \
1746                }
1747 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)             \
1748             H1(dline, dot_atleastone, dot_atmostone, a, b);     \
1749             H1(dline, dot_atmostone, dot_atleastone, a, b); 
1750                            /* If at least one of one DLINE is set, at most one
1751                             * of the opposing one is and vice versa */
1752                            SQUARE_DLINES;
1753                        }
1754 #undef HANDLE_DLINE
1755 #undef H1
1756                        break;
1757                    case '3':
1758                        if (diff > DIFF_EASY) {
1759 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b)                           \
1760                        /* At least one of any DLINE can be set */             \
1761                        sstate->dot_atleastone                                 \
1762                          [i+a + (w + 1) * (j+b)] |= 1<<dline;                 \
1763                        /* This DLINE provides enough NOs to solve the clue */ \
1764                        if (sstate->dot_atmostone                              \
1765                              [i+a + (w + 1) * (j+b)] & 1<<dline) {            \
1766                            dot_setall_dlines(sstate, OPP_DLINE(dline),        \
1767                                              i+(1-a), j+(1-b),                \
1768                                              LINE_UNKNOWN, LINE_YES);         \
1769                        }
1770                            SQUARE_DLINES;
1771 #undef HANDLE_DLINE
1772                        }
1773                        break;
1774                }
1775            }
1776        }
1777
1778        if (solver_states_equal(sstate, sstate_saved)) {
1779            int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
1780            int d;
1781
1782            /*
1783             * Go through the grid and update for all the new edges.
1784             * Since merge_dots() is idempotent, the simplest way to
1785             * do this is just to update for _all_ the edges.
1786             * 
1787             * Also, while we're here, we count the edges, count the
1788             * clues, count the satisfied clues, and count the
1789             * satisfied-minus-one clues.
1790             */
1791            for (j = 0; j <= h; ++j) {
1792                for (i = 0; i <= w; ++i) {
1793                    if (RIGHTOF_DOT(sstate->state, i, j) == LINE_YES) {
1794                        merge_dots(sstate, i, j, i+1, j);
1795                        edgecount++;
1796                    }
1797                    if (BELOW_DOT(sstate->state, i, j) == LINE_YES) {
1798                        merge_dots(sstate, i, j, i, j+1);
1799                        edgecount++;
1800                    }
1801
1802                    if (CLUE_AT(sstate->state, i, j) != ' ') {
1803                        int c = CLUE_AT(sstate->state, i, j) - '0';
1804                        int o = square_order(sstate->state, i, j, LINE_YES);
1805                        if (o == c)
1806                            satclues++;
1807                        else if (o == c-1)
1808                            sm1clues++;
1809                        clues++;
1810                    }
1811                }
1812            }
1813
1814            /*
1815             * Now go through looking for LINE_UNKNOWN edges which
1816             * connect two dots that are already in the same
1817             * equivalence class. If we find one, test to see if the
1818             * loop it would create is a solution.
1819             */
1820            for (j = 0; j <= h; ++j) {
1821                for (i = 0; i <= w; ++i) {
1822                    for (d = 0; d < 2; d++) {
1823                        int i2, j2, eqclass, val;
1824
1825                        if (d == 0) {
1826                            if (RIGHTOF_DOT(sstate->state, i, j) !=
1827                                LINE_UNKNOWN)
1828                                continue;
1829                            i2 = i+1;
1830                            j2 = j;
1831                        } else {
1832                            if (BELOW_DOT(sstate->state, i, j) !=
1833                                LINE_UNKNOWN)
1834                                continue;
1835                            i2 = i;
1836                            j2 = j+1;
1837                        }
1838
1839                        eqclass = dsf_canonify(sstate->dotdsf, j * (w+1) + i);
1840                        if (eqclass != dsf_canonify(sstate->dotdsf,
1841                                                    j2 * (w+1) + i2))
1842                            continue;
1843
1844                        val = LINE_NO;  /* loop is bad until proven otherwise */
1845
1846                        /*
1847                         * This edge would form a loop. Next
1848                         * question: how long would the loop be?
1849                         * Would it equal the total number of edges
1850                         * (plus the one we'd be adding if we added
1851                         * it)?
1852                         */
1853                        if (sstate->looplen[eqclass] == edgecount + 1) {
1854                            int sm1_nearby;
1855                            int cx, cy;
1856
1857                            /*
1858                             * This edge would form a loop which
1859                             * took in all the edges in the entire
1860                             * grid. So now we need to work out
1861                             * whether it would be a valid solution
1862                             * to the puzzle, which means we have to
1863                             * check if it satisfies all the clues.
1864                             * This means that every clue must be
1865                             * either satisfied or satisfied-minus-
1866                             * 1, and also that the number of
1867                             * satisfied-minus-1 clues must be at
1868                             * most two and they must lie on either
1869                             * side of this edge.
1870                             */
1871                            sm1_nearby = 0;
1872                            cx = i - (j2-j);
1873                            cy = j - (i2-i);
1874                            if (CLUE_AT(sstate->state, cx,cy) != ' ' &&
1875                                square_order(sstate->state, cx,cy, LINE_YES) ==
1876                                CLUE_AT(sstate->state, cx,cy) - '0' - 1)
1877                                sm1_nearby++;
1878                            if (CLUE_AT(sstate->state, i, j) != ' ' &&
1879                                square_order(sstate->state, i, j, LINE_YES) ==
1880                                CLUE_AT(sstate->state, i, j) - '0' - 1)
1881                                sm1_nearby++;
1882                            if (sm1clues == sm1_nearby &&
1883                                sm1clues + satclues == clues)
1884                                val = LINE_YES;  /* loop is good! */
1885                        }
1886
1887                        /*
1888                         * Right. Now we know that adding this edge
1889                         * would form a loop, and we know whether
1890                         * that loop would be a viable solution or
1891                         * not.
1892                         * 
1893                         * If adding this edge produces a solution,
1894                         * then we know we've found _a_ solution but
1895                         * we don't know that it's _the_ solution -
1896                         * if it were provably the solution then
1897                         * we'd have deduced this edge some time ago
1898                         * without the need to do loop detection. So
1899                         * in this state we return SOLVER_AMBIGUOUS,
1900                         * which has the effect that hitting Solve
1901                         * on a user-provided puzzle will fill in a
1902                         * solution but using the solver to
1903                         * construct new puzzles won't consider this
1904                         * a reasonable deduction for the user to
1905                         * make.
1906                         */
1907                        if (d == 0)
1908                            LV_RIGHTOF_DOT(sstate->state, i, j) = val;
1909                        else
1910                            LV_BELOW_DOT(sstate->state, i, j) = val;
1911                        if (val == LINE_YES) {
1912                            sstate->solver_status = SOLVER_AMBIGUOUS;
1913                            goto finished_loop_checking;
1914                        }
1915                    }
1916                }
1917            }
1918
1919            finished_loop_checking:
1920
1921            RETURN_IF_SOLVED;
1922        }
1923
1924        if (solver_states_equal(sstate, sstate_saved)) {
1925            /* Solver has stopped making progress so we terminate */
1926            free_solver_state(sstate_saved); 
1927            break;
1928        }
1929
1930        free_solver_state(sstate_saved); 
1931    }
1932
1933    sfree(dot_solved); sfree(square_solved);
1934
1935    if (sstate->solver_status == SOLVER_SOLVED ||
1936        sstate->solver_status == SOLVER_AMBIGUOUS) {
1937        /* s/LINE_UNKNOWN/LINE_NO/g */
1938        array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO, 
1939                HL_COUNT(sstate->state));
1940        array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO, 
1941                VL_COUNT(sstate->state));
1942        return sstate;
1943    }
1944
1945    /* Perform recursive calls */
1946    if (sstate->recursion_remaining) {
1947        sstate_saved = dup_solver_state(sstate);
1948
1949        sstate->recursion_remaining--;
1950
1951        recursive_soln_count = 0;
1952        sstate_rec_solved = NULL;
1953
1954        /* Memory management: 
1955         * sstate_saved won't be modified but needs to be freed when we have
1956         * finished with it.
1957         * sstate is expected to contain our 'best' solution by the time we
1958         * finish this section of code.  It's the thing we'll try adding lines
1959         * to, seeing if they make it more solvable.
1960         * If sstate_rec_solved is non-NULL, it will supersede sstate
1961         * eventually.  sstate_tmp should not hold a value persistently.
1962         */
1963
1964        /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
1965         * of the possibility of additional solutions.  So as soon as we have a
1966         * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
1967         * if we get a SOLVER_SOLVED we want to keep trying in case we find
1968         * further solutions and have to mark it ambiguous.
1969         */
1970
1971 #define DO_RECURSIVE_CALL(dir_dot)                                         \
1972        if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) {                 \
1973            debug(("Trying " #dir_dot " at [%d,%d]\n", i, j));               \
1974            LV_##dir_dot(sstate->state, i, j) = LINE_YES;                   \
1975            sstate_tmp = solve_game_rec(sstate, diff);                      \
1976            switch (sstate_tmp->solver_status) {                            \
1977                case SOLVER_AMBIGUOUS:                                      \
1978                    debug(("Solver ambiguous, returning\n"));                \
1979                    sstate_rec_solved = sstate_tmp;                         \
1980                    goto finished_recursion;                                \
1981                case SOLVER_SOLVED:                                         \
1982                    switch (++recursive_soln_count) {                       \
1983                        case 1:                                             \
1984                            debug(("One solution found\n"));                 \
1985                            sstate_rec_solved = sstate_tmp;                 \
1986                            break;                                          \
1987                        case 2:                                             \
1988                            debug(("Ambiguous solutions found\n"));          \
1989                            free_solver_state(sstate_tmp);                  \
1990                            sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS;\
1991                            goto finished_recursion;                        \
1992                        default:                                            \
1993                            assert(!"recursive_soln_count out of range");   \
1994                            break;                                          \
1995                    }                                                       \
1996                    break;                                                  \
1997                case SOLVER_MISTAKE:                                        \
1998                    debug(("Non-solution found\n"));                         \
1999                    free_solver_state(sstate_tmp);                          \
2000                    free_solver_state(sstate_saved);                        \
2001                    LV_##dir_dot(sstate->state, i, j) = LINE_NO;            \
2002                    goto nonrecursive_solver;                               \
2003                case SOLVER_INCOMPLETE:                                     \
2004                    debug(("Recursive step inconclusive\n"));                \
2005                    free_solver_state(sstate_tmp);                          \
2006                    break;                                                  \
2007            }                                                               \
2008            free_solver_state(sstate);                                      \
2009            sstate = dup_solver_state(sstate_saved);                        \
2010        }
2011        
2012        for (j = 0; j < h + 1; ++j) {
2013            for (i = 0; i < w + 1; ++i) {
2014                /* Only perform recursive calls on 'loose ends' */
2015                if (dot_order(sstate->state, i, j, LINE_YES) == 1) {
2016                    DO_RECURSIVE_CALL(LEFTOF_DOT);
2017                    DO_RECURSIVE_CALL(RIGHTOF_DOT);
2018                    DO_RECURSIVE_CALL(ABOVE_DOT);
2019                    DO_RECURSIVE_CALL(BELOW_DOT);
2020                }
2021            }
2022        }
2023
2024 finished_recursion:
2025
2026        if (sstate_rec_solved) {
2027            free_solver_state(sstate);
2028            sstate = sstate_rec_solved;
2029        } 
2030    }
2031
2032    return sstate;
2033 }
2034
2035 /* XXX bits of solver that may come in handy one day */
2036 #if 0
2037 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot)                         \
2038                    /* dline from this dot that's entirely unknown must have 
2039                     * both lines identical */                           \
2040                    if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN &&       \
2041                        dir2_dot(sstate->state, i, j) == LINE_UNKNOWN) {       \
2042                        sstate->dline_identical[i + (sstate->state->w + 1) * j] |= \
2043                            1<<dline;                                    \
2044                    } else if (sstate->dline_identical[i +
2045                                                       (sstate->state->w + 1) * j] &\
2046                               1<<dline) {                                   \
2047                        /* If they're identical and one is known do the obvious 
2048                         * thing */                                      \
2049                        t = dir1_dot(sstate->state, i, j);                     \
2050                        if (t != LINE_UNKNOWN)                           \
2051                            dir2_dot(sstate->state, i, j) = t;                 \
2052                        else {                                           \
2053                            t = dir2_dot(sstate->state, i, j);                 \
2054                            if (t != LINE_UNKNOWN)                       \
2055                                dir1_dot(sstate->state, i, j) = t;             \
2056                        }                                                \
2057                    }                                                    \
2058                    DOT_DLINES;
2059 #undef HANDLE_DLINE
2060 #endif
2061
2062 #if 0
2063 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2064                        if (sstate->dline_identical[i+a +                     \
2065                                                    (sstate->state->w + 1) * (j+b)] &\
2066                            1<<dline) {                                       \
2067                            dir1_sq(sstate->state, i, j) = LINE_YES;                \
2068                            dir2_sq(sstate->state, i, j) = LINE_YES;                \
2069                        }
2070                        /* If two lines are the same they must be on */
2071                        SQUARE_DLINES;
2072 #undef HANDLE_DLINE
2073 #endif
2074
2075
2076 #if 0
2077 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2078                if (sstate->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] &  \
2079                    1<<dline) {                                   \
2080                    if (square_order(sstate->state, i, j,  LINE_UNKNOWN) - 1 ==  \
2081                        CLUE_AT(sstate->state, i, j) - '0') {      \
2082                        square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
2083                            /* XXX the following may overwrite known data! */ \
2084                        dir1_sq(sstate->state, i, j) = LINE_UNKNOWN;  \
2085                        dir2_sq(sstate->state, i, j) = LINE_UNKNOWN;  \
2086                    }                                  \
2087                }
2088                SQUARE_DLINES;
2089 #undef HANDLE_DLINE
2090 #endif
2091
2092 #if 0
2093 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
2094                        if (sstate->dline_identical[i+a + 
2095                                                    (sstate->state->w + 1) * (j+b)] &\
2096                            1<<dline) {                                       \
2097                            dir1_sq(sstate->state, i, j) = LINE_NO;                 \
2098                            dir2_sq(sstate->state, i, j) = LINE_NO;                 \
2099                        }
2100                        /* If two lines are the same they must be off */
2101                        SQUARE_DLINES;
2102 #undef HANDLE_DLINE
2103 #endif
2104
2105 static char *solve_game(game_state *state, game_state *currstate,
2106                         char *aux, char **error)
2107 {
2108     char *soln = NULL;
2109     solver_state *sstate, *new_sstate;
2110
2111     sstate = new_solver_state(state);
2112     new_sstate = solve_game_rec(sstate, DIFFCOUNT);
2113
2114     if (new_sstate->solver_status == SOLVER_SOLVED) {
2115         soln = encode_solve_move(new_sstate->state);
2116     } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2117         soln = encode_solve_move(new_sstate->state);
2118         /**error = "Solver found ambiguous solutions"; */
2119     } else {
2120         soln = encode_solve_move(new_sstate->state);
2121         /**error = "Solver failed"; */
2122     }
2123
2124     free_solver_state(new_sstate);
2125     free_solver_state(sstate);
2126
2127     return soln;
2128 }
2129
2130 static char *game_text_format(game_state *state)
2131 {
2132     int i, j;
2133     int len;
2134     char *ret, *rp;
2135
2136     len = (2 * state->w + 2) * (2 * state->h + 1);
2137     rp = ret = snewn(len + 1, char);
2138     
2139 #define DRAW_HL                          \
2140     switch (ABOVE_SQUARE(state, i, j)) { \
2141         case LINE_YES:                   \
2142             rp += sprintf(rp, " -");     \
2143             break;                       \
2144         case LINE_NO:                    \
2145             rp += sprintf(rp, " x");     \
2146             break;                       \
2147         case LINE_UNKNOWN:               \
2148             rp += sprintf(rp, "  ");     \
2149             break;                       \
2150         default:                         \
2151             assert(!"Illegal line state for HL");\
2152     }
2153
2154 #define DRAW_VL                          \
2155     switch (LEFTOF_SQUARE(state, i, j)) {\
2156         case LINE_YES:                   \
2157             rp += sprintf(rp, "|");      \
2158             break;                       \
2159         case LINE_NO:                    \
2160             rp += sprintf(rp, "x");      \
2161             break;                       \
2162         case LINE_UNKNOWN:               \
2163             rp += sprintf(rp, " ");      \
2164             break;                       \
2165         default:                         \
2166             assert(!"Illegal line state for VL");\
2167     }
2168     
2169     for (j = 0; j < state->h; ++j) {
2170         for (i = 0; i < state->w; ++i) {
2171             DRAW_HL;
2172         }
2173         rp += sprintf(rp, " \n");
2174         for (i = 0; i < state->w; ++i) {
2175             DRAW_VL;
2176             rp += sprintf(rp, "%c", (int)(CLUE_AT(state, i, j)));
2177         }
2178         DRAW_VL;
2179         rp += sprintf(rp, "\n");
2180     }
2181     for (i = 0; i < state->w; ++i) {
2182         DRAW_HL;
2183     }
2184     rp += sprintf(rp, " \n");
2185     
2186     assert(strlen(ret) == len);
2187     return ret;
2188 }
2189
2190 static game_ui *new_ui(game_state *state)
2191 {
2192     return NULL;
2193 }
2194
2195 static void free_ui(game_ui *ui)
2196 {
2197 }
2198
2199 static char *encode_ui(game_ui *ui)
2200 {
2201     return NULL;
2202 }
2203
2204 static void decode_ui(game_ui *ui, char *encoding)
2205 {
2206 }
2207
2208 static void game_changed_state(game_ui *ui, game_state *oldstate,
2209                                game_state *newstate)
2210 {
2211 }
2212
2213 struct game_drawstate {
2214     int started;
2215     int tilesize;
2216     int flashing;
2217     char *hl, *vl;
2218     char *clue_error;
2219 };
2220
2221 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2222                             int x, int y, int button)
2223 {
2224     int hl_selected;
2225     int i, j, p, q; 
2226     char *ret, buf[80];
2227     char button_char = ' ';
2228     enum line_state old_state;
2229
2230     button &= ~MOD_MASK;
2231
2232     /* Around each line is a diamond-shaped region where points within that
2233      * region are closer to this line than any other.  We assume any click
2234      * within a line's diamond was meant for that line.  It would all be a lot
2235      * simpler if the / and % operators respected modulo arithmetic properly
2236      * for negative numbers. */
2237     
2238     x -= BORDER;
2239     y -= BORDER;
2240
2241     /* Get the coordinates of the square the click was in */
2242     i = (x + TILE_SIZE) / TILE_SIZE - 1; 
2243     j = (y + TILE_SIZE) / TILE_SIZE - 1;
2244
2245     /* Get the precise position inside square [i,j] */
2246     p = (x + TILE_SIZE) % TILE_SIZE;
2247     q = (y + TILE_SIZE) % TILE_SIZE;
2248
2249     /* After this bit of magic [i,j] will correspond to the point either above
2250      * or to the left of the line selected */
2251     if (p > q) { 
2252         if (TILE_SIZE - p > q) {
2253             hl_selected = TRUE;
2254         } else {
2255             hl_selected = FALSE;
2256             ++i;
2257         }
2258     } else {
2259         if (TILE_SIZE - q > p) {
2260             hl_selected = FALSE;
2261         } else {
2262             hl_selected = TRUE;
2263             ++j;
2264         }
2265     }
2266
2267     if (i < 0 || j < 0)
2268         return NULL;
2269
2270     if (hl_selected) {
2271         if (i >= state->w || j >= state->h + 1)
2272             return NULL;
2273     } else { 
2274         if (i >= state->w + 1 || j >= state->h)
2275             return NULL;
2276     }
2277
2278     /* I think it's only possible to play this game with mouse clicks, sorry */
2279     /* Maybe will add mouse drag support some time */
2280     if (hl_selected)
2281         old_state = RIGHTOF_DOT(state, i, j);
2282     else
2283         old_state = BELOW_DOT(state, i, j);
2284
2285     switch (button) {
2286         case LEFT_BUTTON:
2287             switch (old_state) {
2288                 case LINE_UNKNOWN:
2289                     button_char = 'y';
2290                     break;
2291                 case LINE_YES:
2292                 case LINE_NO:
2293                     button_char = 'u';
2294                     break;
2295             }
2296             break;
2297         case MIDDLE_BUTTON:
2298             button_char = 'u';
2299             break;
2300         case RIGHT_BUTTON:
2301             switch (old_state) {
2302                 case LINE_UNKNOWN:
2303                     button_char = 'n';
2304                     break;
2305                 case LINE_NO:
2306                 case LINE_YES:
2307                     button_char = 'u';
2308                     break;
2309             }
2310             break;
2311         default:
2312             return NULL;
2313     }
2314
2315
2316     sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
2317     ret = dupstr(buf);
2318
2319     return ret;
2320 }
2321
2322 static game_state *execute_move(game_state *state, char *move)
2323 {
2324     int i, j;
2325     game_state *newstate = dup_game(state);
2326
2327     if (move[0] == 'S') {
2328         move++;
2329         newstate->cheated = TRUE;
2330     }
2331
2332     while (*move) {
2333         i = atoi(move);
2334         move = strchr(move, ',');
2335         if (!move)
2336             goto fail;
2337         j = atoi(++move);
2338         move += strspn(move, "1234567890");
2339         switch (*(move++)) {
2340             case 'h':
2341                 if (i >= newstate->w || j > newstate->h)
2342                     goto fail;
2343                 switch (*(move++)) {
2344                     case 'y':
2345                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
2346                         break;
2347                     case 'n':
2348                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
2349                         break;
2350                     case 'u':
2351                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
2352                         break;
2353                     default:
2354                         goto fail;
2355                 }
2356                 break;
2357             case 'v':
2358                 if (i > newstate->w || j >= newstate->h)
2359                     goto fail;
2360                 switch (*(move++)) {
2361                     case 'y':
2362                         LV_BELOW_DOT(newstate, i, j) = LINE_YES;
2363                         break;
2364                     case 'n':
2365                         LV_BELOW_DOT(newstate, i, j) = LINE_NO;
2366                         break;
2367                     case 'u':
2368                         LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
2369                         break;
2370                     default:
2371                         goto fail;
2372                 }
2373                 break;
2374             default:
2375                 goto fail;
2376         }
2377     }
2378
2379     /*
2380      * Check for completion.
2381      */
2382     i = 0;                             /* placate optimiser */
2383     for (j = 0; j <= newstate->h; j++) {
2384         for (i = 0; i < newstate->w; i++)
2385             if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
2386                 break;
2387         if (i < newstate->w)
2388             break;
2389     }
2390     if (j <= newstate->h) {
2391         int prevdir = 'R';
2392         int x = i, y = j;
2393         int looplen, count;
2394
2395         /*
2396          * We've found a horizontal edge at (i,j). Follow it round
2397          * to see if it's part of a loop.
2398          */
2399         looplen = 0;
2400         while (1) {
2401             int order = dot_order(newstate, x, y, LINE_YES);
2402             if (order != 2)
2403                 goto completion_check_done;
2404
2405             if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
2406                 x--;
2407                 prevdir = 'R';
2408             } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
2409                        prevdir != 'R') {
2410                 x++;
2411                 prevdir = 'L';
2412             } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
2413                        prevdir != 'U') {
2414                 y--;
2415                 prevdir = 'D';
2416             } else if (BELOW_DOT(newstate, x, y) == LINE_YES &&
2417                        prevdir != 'D') {
2418                 y++;
2419                 prevdir = 'U';
2420             } else {
2421                 assert(!"Can't happen");   /* dot_order guarantees success */
2422             }
2423
2424             looplen++;
2425
2426             if (x == i && y == j)
2427                 break;
2428         }
2429
2430         if (x != i || y != j || looplen == 0)
2431             goto completion_check_done;
2432
2433         /*
2434          * We've traced our way round a loop, and we know how many
2435          * line segments were involved. Count _all_ the line
2436          * segments in the grid, to see if the loop includes them
2437          * all.
2438          */
2439         count = 0;
2440         for (j = 0; j <= newstate->h; j++)
2441             for (i = 0; i <= newstate->w; i++)
2442                 count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
2443                           (BELOW_DOT(newstate, i, j) == LINE_YES));
2444         assert(count >= looplen);
2445         if (count != looplen)
2446             goto completion_check_done;
2447
2448         /*
2449          * The grid contains one closed loop and nothing else.
2450          * Check that all the clues are satisfied.
2451          */
2452         for (j = 0; j < newstate->h; ++j) {
2453             for (i = 0; i < newstate->w; ++i) {
2454                 int n = CLUE_AT(newstate, i, j);
2455                 if (n != ' ') {
2456                     if (square_order(newstate, i, j, LINE_YES) != n - '0') {
2457                         goto completion_check_done;
2458                     }
2459                 }
2460             }
2461         }
2462
2463         /*
2464          * Completed!
2465          */
2466         newstate->solved = TRUE;
2467     }
2468
2469 completion_check_done:
2470     return newstate;
2471
2472 fail:
2473     free_game(newstate);
2474     return NULL;
2475 }
2476
2477 /* ----------------------------------------------------------------------
2478  * Drawing routines.
2479  */
2480
2481 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
2482
2483 static void game_compute_size(game_params *params, int tilesize,
2484                               int *x, int *y)
2485 {
2486     struct { int tilesize; } ads, *ds = &ads;
2487     ads.tilesize = tilesize;
2488
2489     *x = SIZE(params->w);
2490     *y = SIZE(params->h);
2491 }
2492
2493 static void game_set_size(drawing *dr, game_drawstate *ds,
2494                           game_params *params, int tilesize)
2495 {
2496     ds->tilesize = tilesize;
2497 }
2498
2499 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2500 {
2501     float *ret = snewn(4 * NCOLOURS, float);
2502
2503     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2504
2505     ret[COL_FOREGROUND * 3 + 0] = 0.0F;
2506     ret[COL_FOREGROUND * 3 + 1] = 0.0F;
2507     ret[COL_FOREGROUND * 3 + 2] = 0.0F;
2508
2509     ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2510     ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2511     ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2512
2513     ret[COL_MISTAKE * 3 + 0] = 1.0F;
2514     ret[COL_MISTAKE * 3 + 1] = 0.0F;
2515     ret[COL_MISTAKE * 3 + 2] = 0.0F;
2516
2517     *ncolours = NCOLOURS;
2518     return ret;
2519 }
2520
2521 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2522 {
2523     struct game_drawstate *ds = snew(struct game_drawstate);
2524
2525     ds->tilesize = 0;
2526     ds->started = 0;
2527     ds->hl = snewn(HL_COUNT(state), char);
2528     ds->vl = snewn(VL_COUNT(state), char);
2529     ds->clue_error = snewn(SQUARE_COUNT(state), char);
2530     ds->flashing = 0;
2531
2532     memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
2533     memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
2534     memset(ds->clue_error, 0, SQUARE_COUNT(state));
2535
2536     return ds;
2537 }
2538
2539 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2540 {
2541     sfree(ds->clue_error);
2542     sfree(ds->hl);
2543     sfree(ds->vl);
2544     sfree(ds);
2545 }
2546
2547 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2548                         game_state *state, int dir, game_ui *ui,
2549                         float animtime, float flashtime)
2550 {
2551     int i, j, n;
2552     int w = state->w, h = state->h;
2553     char c[2];
2554     int line_colour, flash_changed;
2555     int clue_mistake;
2556
2557     if (!ds->started) {
2558         /*
2559          * The initial contents of the window are not guaranteed and
2560          * can vary with front ends. To be on the safe side, all games
2561          * should start by drawing a big background-colour rectangle
2562          * covering the whole window.
2563          */
2564         draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
2565
2566         /* Draw dots */
2567         for (j = 0; j < h + 1; ++j) {
2568             for (i = 0; i < w + 1; ++i) {
2569                 draw_rect(dr, 
2570                           BORDER + i * TILE_SIZE - LINEWIDTH/2,
2571                           BORDER + j * TILE_SIZE - LINEWIDTH/2,
2572                           LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
2573             }
2574         }
2575
2576         /* Draw clues */
2577         for (j = 0; j < h; ++j) {
2578             for (i = 0; i < w; ++i) {
2579                 c[0] = CLUE_AT(state, i, j);
2580                 c[1] = '\0';
2581                 draw_text(dr, 
2582                           BORDER + i * TILE_SIZE + TILE_SIZE/2,
2583                           BORDER + j * TILE_SIZE + TILE_SIZE/2,
2584                           FONT_VARIABLE, TILE_SIZE/2, 
2585                           ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
2586             }
2587         }
2588         draw_update(dr, 0, 0,
2589                     state->w * TILE_SIZE + 2*BORDER + 1,
2590                     state->h * TILE_SIZE + 2*BORDER + 1);
2591         ds->started = TRUE;
2592     }
2593
2594     if (flashtime > 0 && 
2595         (flashtime <= FLASH_TIME/3 ||
2596          flashtime >= FLASH_TIME*2/3)) {
2597         flash_changed = !ds->flashing;
2598         ds->flashing = TRUE;
2599         line_colour = COL_HIGHLIGHT;
2600     } else {
2601         flash_changed = ds->flashing;
2602         ds->flashing = FALSE;
2603         line_colour = COL_FOREGROUND;
2604     }
2605
2606 #define CROSS_SIZE (3 * LINEWIDTH / 2)
2607     
2608     /* Redraw clue colours if necessary */
2609     for (j = 0; j < h; ++j) {
2610         for (i = 0; i < w; ++i) {
2611             c[0] = CLUE_AT(state, i, j);
2612             c[1] = '\0';
2613             if (c[0] == ' ')
2614                 continue;
2615
2616             n = c[0] - '0';
2617             assert(n >= 0 && n <= 4);
2618
2619             clue_mistake = (square_order(state, i, j, LINE_YES) > n     || 
2620                             square_order(state, i, j, LINE_NO ) > (4-n));
2621
2622             if (clue_mistake != ds->clue_error[j * w + i]) {
2623                 draw_rect(dr, 
2624                           BORDER + i * TILE_SIZE + CROSS_SIZE,
2625                           BORDER + j * TILE_SIZE + CROSS_SIZE,
2626                           TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
2627                           COL_BACKGROUND);
2628                 draw_text(dr, 
2629                           BORDER + i * TILE_SIZE + TILE_SIZE/2,
2630                           BORDER + j * TILE_SIZE + TILE_SIZE/2,
2631                           FONT_VARIABLE, TILE_SIZE/2, 
2632                           ALIGN_VCENTRE | ALIGN_HCENTRE, 
2633                           clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
2634                 draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
2635                             TILE_SIZE, TILE_SIZE);
2636
2637                 ds->clue_error[j * w + i] = clue_mistake;
2638             }
2639         }
2640     }
2641
2642     /* I've also had a request to colour lines red if they make a non-solution
2643      * loop, or if more than two lines go into any point.  I think that would
2644      * be good some time. */
2645
2646 #define CLEAR_VL(i, j) do {                                                \
2647                            draw_rect(dr,                                   \
2648                                  BORDER + i * TILE_SIZE - CROSS_SIZE,      \
2649                                  BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,     \
2650                                  CROSS_SIZE * 2,                           \
2651                                  TILE_SIZE - LINEWIDTH,                    \
2652                                  COL_BACKGROUND);                          \
2653                            draw_update(dr,                                 \
2654                                        BORDER + i * TILE_SIZE - CROSS_SIZE, \
2655                                        BORDER + j * TILE_SIZE - CROSS_SIZE, \
2656                                        CROSS_SIZE*2,                       \
2657                                        TILE_SIZE + CROSS_SIZE*2);          \
2658                         } while (0)
2659
2660 #define CLEAR_HL(i, j) do {                                                \
2661                            draw_rect(dr,                                   \
2662                                  BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,     \
2663                                  BORDER + j * TILE_SIZE - CROSS_SIZE,      \
2664                                  TILE_SIZE - LINEWIDTH,                    \
2665                                  CROSS_SIZE * 2,                           \
2666                                  COL_BACKGROUND);                          \
2667                            draw_update(dr,                                 \
2668                                        BORDER + i * TILE_SIZE - CROSS_SIZE, \
2669                                        BORDER + j * TILE_SIZE - CROSS_SIZE, \
2670                                        TILE_SIZE + CROSS_SIZE*2,           \
2671                                        CROSS_SIZE*2);                      \
2672                         } while (0)
2673
2674     /* Vertical lines */
2675     for (j = 0; j < h; ++j) {
2676         for (i = 0; i < w + 1; ++i) {
2677             switch (BELOW_DOT(state, i, j)) {
2678                 case LINE_UNKNOWN:
2679                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2680                         CLEAR_VL(i, j);
2681                     }
2682                     break;
2683                 case LINE_YES:
2684                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j) ||
2685                         flash_changed) {
2686                         CLEAR_VL(i, j);
2687                         draw_rect(dr,
2688                                   BORDER + i * TILE_SIZE - LINEWIDTH/2,
2689                                   BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2690                                   LINEWIDTH, TILE_SIZE - LINEWIDTH, 
2691                                   line_colour);
2692                     }
2693                     break;
2694                 case LINE_NO:
2695                     if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2696                         CLEAR_VL(i, j);
2697                         draw_line(dr,
2698                                  BORDER + i * TILE_SIZE - CROSS_SIZE,
2699                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2700                                  BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2701                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2702                                   COL_FOREGROUND);
2703                         draw_line(dr,
2704                                  BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2705                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2706                                  BORDER + i * TILE_SIZE - CROSS_SIZE,
2707                                  BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2708                                   COL_FOREGROUND);
2709                     }
2710                     break;
2711             }
2712             ds->vl[i + (w + 1) * j] = BELOW_DOT(state, i, j);
2713         }
2714     }
2715
2716     /* Horizontal lines */
2717     for (j = 0; j < h + 1; ++j) {
2718         for (i = 0; i < w; ++i) {
2719             switch (RIGHTOF_DOT(state, i, j)) {
2720                 case LINE_UNKNOWN:
2721                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2722                         CLEAR_HL(i, j);
2723                 }
2724                         break;
2725                 case LINE_YES:
2726                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j) ||
2727                         flash_changed) {
2728                         CLEAR_HL(i, j);
2729                         draw_rect(dr,
2730                                   BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2731                                   BORDER + j * TILE_SIZE - LINEWIDTH/2,
2732                                   TILE_SIZE - LINEWIDTH, LINEWIDTH, 
2733                                   line_colour);
2734                         break;
2735                     }
2736                 case LINE_NO:
2737                     if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2738                         CLEAR_HL(i, j);
2739                         draw_line(dr,
2740                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2741                                  BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2742                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2743                                  BORDER + j * TILE_SIZE - CROSS_SIZE,
2744                                   COL_FOREGROUND);
2745                         draw_line(dr,
2746                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2747                                  BORDER + j * TILE_SIZE - CROSS_SIZE,
2748                                  BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2749                                  BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2750                                   COL_FOREGROUND);
2751                         break;
2752                     }
2753             }
2754             ds->hl[i + w * j] = RIGHTOF_DOT(state, i, j);
2755         }
2756     }
2757 }
2758
2759 static float game_anim_length(game_state *oldstate, game_state *newstate,
2760                               int dir, game_ui *ui)
2761 {
2762     return 0.0F;
2763 }
2764
2765 static float game_flash_length(game_state *oldstate, game_state *newstate,
2766                                int dir, game_ui *ui)
2767 {
2768     if (!oldstate->solved  &&  newstate->solved &&
2769         !oldstate->cheated && !newstate->cheated) {
2770         return FLASH_TIME;
2771     }
2772
2773     return 0.0F;
2774 }
2775
2776 static int game_wants_statusbar(void)
2777 {
2778     return FALSE;
2779 }
2780
2781 static int game_timing_state(game_state *state, game_ui *ui)
2782 {
2783     return TRUE;
2784 }
2785
2786 static void game_print_size(game_params *params, float *x, float *y)
2787 {
2788     int pw, ph;
2789
2790     /*
2791      * I'll use 7mm squares by default.
2792      */
2793     game_compute_size(params, 700, &pw, &ph);
2794     *x = pw / 100.0F;
2795     *y = ph / 100.0F;
2796 }
2797
2798 static void game_print(drawing *dr, game_state *state, int tilesize)
2799 {
2800     int w = state->w, h = state->h;
2801     int ink = print_mono_colour(dr, 0);
2802     int x, y;
2803     game_drawstate ads, *ds = &ads;
2804     ds->tilesize = tilesize;
2805
2806     /*
2807      * Dots. I'll deliberately make the dots a bit wider than the
2808      * lines, so you can still see them. (And also because it's
2809      * annoyingly tricky to make them _exactly_ the same size...)
2810      */
2811     for (y = 0; y <= h; y++)
2812         for (x = 0; x <= w; x++)
2813             draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
2814                         LINEWIDTH, ink, ink);
2815
2816     /*
2817      * Clues.
2818      */
2819     for (y = 0; y < h; y++)
2820         for (x = 0; x < w; x++)
2821             if (CLUE_AT(state, x, y) != ' ') {
2822                 char c[2];
2823
2824                 c[0] = CLUE_AT(state, x, y);
2825                 c[1] = '\0';
2826                 draw_text(dr, 
2827                           BORDER + x * TILE_SIZE + TILE_SIZE/2,
2828                           BORDER + y * TILE_SIZE + TILE_SIZE/2,
2829                           FONT_VARIABLE, TILE_SIZE/2, 
2830                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
2831             }
2832
2833     /*
2834      * Lines. (At the moment, I'm not bothering with crosses.)
2835      */
2836     for (y = 0; y <= h; y++)
2837         for (x = 0; x < w; x++)
2838             if (RIGHTOF_DOT(state, x, y) == LINE_YES)
2839                 draw_rect(dr, BORDER + x * TILE_SIZE,
2840                           BORDER + y * TILE_SIZE - LINEWIDTH/2,
2841                           TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
2842     for (y = 0; y < h; y++)
2843         for (x = 0; x <= w; x++)
2844             if (BELOW_DOT(state, x, y) == LINE_YES)
2845                 draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
2846                           BORDER + y * TILE_SIZE,
2847                           (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
2848 }
2849
2850 #ifdef COMBINED
2851 #define thegame loopy
2852 #endif
2853
2854 const struct game thegame = {
2855     "Loopy", "games.loopy",
2856     default_params,
2857     game_fetch_preset,
2858     decode_params,
2859     encode_params,
2860     free_params,
2861     dup_params,
2862     TRUE, game_configure, custom_params,
2863     validate_params,
2864     new_game_desc,
2865     validate_desc,
2866     new_game,
2867     dup_game,
2868     free_game,
2869     1, solve_game,
2870     TRUE, game_text_format,
2871     new_ui,
2872     free_ui,
2873     encode_ui,
2874     decode_ui,
2875     game_changed_state,
2876     interpret_move,
2877     execute_move,
2878     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2879     game_colours,
2880     game_new_drawstate,
2881     game_free_drawstate,
2882     game_redraw,
2883     game_anim_length,
2884     game_flash_length,
2885     TRUE, FALSE, game_print_size, game_print,
2886     game_wants_statusbar,
2887     FALSE, game_timing_state,
2888     0,                                       /* mouse_priorities */
2889 };