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