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