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