chiark / gitweb /
A user points out that Loopy's solver relies on elements of the
[sgt-puzzles.git] / loopy.c
1 /*
2  * loopy.c: An implementation of the Nikoli game 'Loop the loop'.
3  * (c) Mike Pinna, 2005, 2006
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 munching: are we
12  *    recursing before checking completion, by any chance?
13  *
14  *  - There's an interesting deductive technique which makes use of topology
15  *    rather than just graph theory. Each _square_ in the grid is either inside
16  *    or outside the loop; you can tell that two squares are on the same side
17  *    of the loop if they're separated by an x (or, more generally, by a path
18  *    crossing no LINE_UNKNOWNs and an even number of LINE_YESes), and on the
19  *    opposite side of the loop if they're separated by a line (or an odd
20  *    number of LINE_YESes and no LINE_UNKNOWNs). Oh, and any square separated
21  *    from the outside of the grid by a LINE_YES or a LINE_NO is on the inside
22  *    or outside respectively. So if you can track this for all squares, you
23  *    figure out the state of the line between a pair once their relative
24  *    insideness is known.
25  *
26  *  - (Just a speed optimisation.)  Consider some todo list queue where every
27  *    time we modify something we mark it for consideration by other bits of
28  *    the solver, to save iteration over things that have already been done.
29  */
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <assert.h>
35 #include <ctype.h>
36 #include <math.h>
37
38 #include "puzzles.h"
39 #include "tree234.h"
40
41 /* Debugging options */
42 /*#define DEBUG_CACHES*/
43 /*#define SHOW_WORKING*/
44
45 /* ----------------------------------------------------------------------
46  * Struct, enum and function declarations
47  */
48
49 enum {
50     COL_BACKGROUND,
51     COL_FOREGROUND,
52     COL_HIGHLIGHT,
53     COL_MISTAKE,
54     NCOLOURS
55 };
56
57 struct game_state {
58     int w, h;
59     
60     /* Put -1 in a square that doesn't get a clue */
61     signed char *clues;
62     
63     /* Arrays of line states, stored left-to-right, top-to-bottom */
64     char *hl, *vl;
65
66     int solved;
67     int cheated;
68
69     int recursion_depth;
70 };
71
72 enum solver_status {
73     SOLVER_SOLVED,    /* This is the only solution the solver could find */
74     SOLVER_MISTAKE,   /* This is definitely not a solution */
75     SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
76     SOLVER_INCOMPLETE /* This may be a partial solution */
77 };
78
79 typedef struct normal {
80     char *dot_atleastone;
81     char *dot_atmostone;
82 } normal_mode_state;
83
84 typedef struct hard {
85     int *linedsf;
86 } hard_mode_state;
87
88 typedef struct solver_state {
89     game_state *state;
90     int recursion_remaining;
91     enum solver_status solver_status;
92     /* NB looplen is the number of dots that are joined together at a point, ie a
93      * looplen of 1 means there are no lines to a particular dot */
94     int *looplen;
95
96     /* caches */
97     char *dot_yescount;
98     char *dot_nocount;
99     char *square_yescount;
100     char *square_nocount;
101     char *dot_solved, *square_solved;
102     int *dotdsf;
103
104     normal_mode_state *normal;
105     hard_mode_state *hard;
106 } solver_state;
107
108 /*
109  * Difficulty levels. I do some macro ickery here to ensure that my
110  * enum and the various forms of my name list always match up.
111  */
112
113 #define DIFFLIST(A) \
114     A(EASY,Easy,e,easy_mode_deductions) \
115     A(NORMAL,Normal,n,normal_mode_deductions) \
116     A(HARD,Hard,h,hard_mode_deductions)
117 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
118 #define TITLE(upper,title,lower,fn) #title,
119 #define ENCODE(upper,title,lower,fn) #lower
120 #define CONFIG(upper,title,lower,fn) ":" #title
121 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
122 #define SOLVER_FN(upper,title,lower,fn) &fn,
123 enum { DIFFLIST(ENUM) DIFF_MAX };
124 static char const *const diffnames[] = { DIFFLIST(TITLE) };
125 static char const diffchars[] = DIFFLIST(ENCODE);
126 #define DIFFCONFIG DIFFLIST(CONFIG)
127 DIFFLIST(SOLVER_FN_DECL);
128 static int (*(solver_fns[]))(solver_state *) = { DIFFLIST(SOLVER_FN) };
129
130 struct game_params {
131     int w, h;
132     int diff;
133     int rec;
134 };
135
136 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
137
138 #define OPP(state) \
139     (2 - state)
140
141 enum direction { UP, LEFT, RIGHT, DOWN };
142
143 #define OPP_DIR(dir) \
144     (3 - dir) 
145
146 struct game_drawstate {
147     int started;
148     int tilesize, linewidth;
149     int flashing;
150     char *hl, *vl;
151     char *clue_error;
152 };
153
154 static char *game_text_format(game_state *state);
155 static char *state_to_text(const game_state *state);
156 static char *validate_desc(game_params *params, char *desc);
157 static int get_line_status_from_point(const game_state *state,
158                                       int x, int y, enum direction d);
159 static int dot_order(const game_state* state, int i, int j, char line_type);
160 static int square_order(const game_state* state, int i, int j, char line_type);
161 static solver_state *solve_game_rec(const solver_state *sstate,
162                                     int diff);
163
164 #ifdef DEBUG_CACHES
165 static void check_caches(const solver_state* sstate);
166 #else
167 #define check_caches(s)
168 #endif
169
170 /* ----------------------------------------------------------------------
171  * Preprocessor magic 
172  */
173
174 /* General constants */
175 #define PREFERRED_TILE_SIZE 32
176 #define TILE_SIZE (ds->tilesize)
177 #define LINEWIDTH (ds->linewidth)
178 #define BORDER (TILE_SIZE / 2)
179 #define FLASH_TIME 0.5F
180
181 /* Counts of various things that we're interested in */
182 #define HL_COUNT(state) ((state)->w * ((state)->h + 1))
183 #define VL_COUNT(state) (((state)->w + 1) * (state)->h)
184 #define LINE_COUNT(state) (HL_COUNT(state) + VL_COUNT(state))
185 #define DOT_COUNT(state) (((state)->w + 1) * ((state)->h + 1))
186 #define SQUARE_COUNT(state) ((state)->w * (state)->h)
187
188 /* For indexing into arrays */
189 #define DOT_INDEX(state, x, y) ((x) + ((state)->w + 1) * (y))
190 #define SQUARE_INDEX(state, x, y) ((x) + ((state)->w) * (y))
191 #define HL_INDEX(state, x, y) SQUARE_INDEX(state, x, y)
192 #define VL_INDEX(state, x, y) DOT_INDEX(state, x, y)
193
194 /* Useful utility functions */
195 #define LEGAL_DOT(state, i, j) ((i) >= 0 && (j) >= 0 && \
196                                 (i) <= (state)->w && (j) <= (state)->h)
197 #define LEGAL_SQUARE(state, i, j) ((i) >= 0 && (j) >= 0 && \
198                                    (i) < (state)->w && (j) < (state)->h)
199
200 #define CLUE_AT(state, i, j) (LEGAL_SQUARE(state, i, j) ? \
201                               LV_CLUE_AT(state, i, j) : -1)
202                              
203 #define LV_CLUE_AT(state, i, j) ((state)->clues[SQUARE_INDEX(state, i, j)])
204
205 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
206
207 #define SET_BIT(field, bit)  (BIT_SET(field, bit) ? FALSE : \
208                               ((field) |= (1<<(bit)), TRUE))
209
210 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
211                                ((field) &= ~(1<<(bit)), TRUE) : FALSE)
212
213 #define DIR2STR(d) \
214     ((d == UP) ? "up" : \
215      (d == DOWN) ? "down" : \
216      (d == LEFT) ? "left" : \
217      (d == RIGHT) ? "right" : "oops")
218
219 #define CLUE2CHAR(c) \
220     ((c < 0) ? ' ' : c + '0')
221
222 /* Lines that have particular relationships with given dots or squares */
223 #define ABOVE_SQUARE(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
224 #define BELOW_SQUARE(state, i, j) ABOVE_SQUARE(state, i, (j)+1)
225 #define LEFTOF_SQUARE(state, i, j)  ((state)->vl[(i) + ((state)->w + 1) * (j)])
226 #define RIGHTOF_SQUARE(state, i, j) LEFTOF_SQUARE(state, (i)+1, j)
227
228 /*
229  * These macros return rvalues only, but can cope with being passed
230  * out-of-range coordinates.
231  */
232 /* XXX replace these with functions so we can create an array of function
233  * pointers for nicer iteration over them.  This could probably be done with
234  * loads of other things for eliminating many nasty hacks. */
235 #define ABOVE_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j <= 0) ? \
236                                 LINE_NO : LV_ABOVE_DOT(state, i, j))
237 #define BELOW_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j >= (state)->h) ? \
238                                 LINE_NO : LV_BELOW_DOT(state, i, j))
239
240 #define LEFTOF_DOT(state, i, j)  ((!LEGAL_DOT(state, i, j) || i <= 0) ? \
241                                   LINE_NO : LV_LEFTOF_DOT(state, i, j))
242 #define RIGHTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i >= (state)->w)? \
243                                   LINE_NO : LV_RIGHTOF_DOT(state, i, j))
244
245 /*
246  * These macros expect to be passed valid coordinates, and return
247  * lvalues.
248  */
249 #define LV_BELOW_DOT(state, i, j) ((state)->vl[VL_INDEX(state, i, j)])
250 #define LV_ABOVE_DOT(state, i, j) LV_BELOW_DOT(state, i, (j)-1)
251
252 #define LV_RIGHTOF_DOT(state, i, j) ((state)->hl[HL_INDEX(state, i, j)])
253 #define LV_LEFTOF_DOT(state, i, j)  LV_RIGHTOF_DOT(state, (i)-1, j)
254
255 /* Counts of interesting things */
256 #define DOT_YES_COUNT(sstate, i, j) \
257     ((sstate)->dot_yescount[DOT_INDEX((sstate)->state, i, j)])
258
259 #define DOT_NO_COUNT(sstate, i, j) \
260     ((sstate)->dot_nocount[DOT_INDEX((sstate)->state, i, j)])
261
262 #define SQUARE_YES_COUNT(sstate, i, j) \
263     ((sstate)->square_yescount[SQUARE_INDEX((sstate)->state, i, j)])
264
265 #define SQUARE_NO_COUNT(sstate, i, j) \
266     ((sstate)->square_nocount[SQUARE_INDEX((sstate)->state, i, j)])
267
268 /* Iterators.  NB these iterate over height more slowly than over width so that
269  * the elements come out in 'reading' order */
270 /* XXX considering adding a 'current' element to each of these which gets the
271  * address of the current dot, say.  But expecting we'd need more than that
272  * most of the time.  */
273 #define FORALL(i, j, w, h) \
274     for ((j) = 0; (j) < (h); ++(j)) \
275         for ((i) = 0; (i) < (w); ++(i))
276
277 #define FORALL_DOTS(state, i, j) \
278     FORALL(i, j, (state)->w + 1, (state)->h + 1)
279
280 #define FORALL_SQUARES(state, i, j) \
281     FORALL(i, j, (state)->w, (state)->h)
282
283 #define FORALL_HL(state, i, j) \
284     FORALL(i, j, (state)->w, (state)->h+1)
285
286 #define FORALL_VL(state, i, j) \
287     FORALL(i, j, (state)->w+1, (state)->h)
288
289 /* ----------------------------------------------------------------------
290  * General struct manipulation and other straightforward code
291  */
292
293 static game_state *dup_game(game_state *state)
294 {
295     game_state *ret = snew(game_state);
296
297     ret->h = state->h;
298     ret->w = state->w;
299     ret->solved = state->solved;
300     ret->cheated = state->cheated;
301
302     ret->clues = snewn(SQUARE_COUNT(state), signed char);
303     memcpy(ret->clues, state->clues, SQUARE_COUNT(state));
304
305     ret->hl = snewn(HL_COUNT(state), char);
306     memcpy(ret->hl, state->hl, HL_COUNT(state));
307
308     ret->vl = snewn(VL_COUNT(state), char);
309     memcpy(ret->vl, state->vl, VL_COUNT(state));
310
311     ret->recursion_depth = state->recursion_depth;
312
313     return ret;
314 }
315
316 static void free_game(game_state *state)
317 {
318     if (state) {
319         sfree(state->clues);
320         sfree(state->hl);
321         sfree(state->vl);
322         sfree(state);
323     }
324 }
325
326 static solver_state *new_solver_state(const game_state *state, int diff) {
327     int i, j;
328     solver_state *ret = snew(solver_state);
329
330     ret->state = dup_game((game_state *)state);
331     
332     ret->recursion_remaining = state->recursion_depth;
333     ret->solver_status = SOLVER_INCOMPLETE; 
334
335     ret->dotdsf = snew_dsf(DOT_COUNT(state));
336     ret->looplen = snewn(DOT_COUNT(state), int);
337
338     for (i = 0; i < DOT_COUNT(state); i++) {
339         ret->looplen[i] = 1;
340     }
341
342     ret->dot_solved = snewn(DOT_COUNT(state), char);
343     ret->square_solved = snewn(SQUARE_COUNT(state), char);
344     memset(ret->dot_solved, FALSE, DOT_COUNT(state));
345     memset(ret->square_solved, FALSE, SQUARE_COUNT(state));
346
347     ret->dot_yescount = snewn(DOT_COUNT(state), char);
348     memset(ret->dot_yescount, 0, DOT_COUNT(state));
349     ret->dot_nocount = snewn(DOT_COUNT(state), char);
350     memset(ret->dot_nocount, 0, DOT_COUNT(state));
351     ret->square_yescount = snewn(SQUARE_COUNT(state), char);
352     memset(ret->square_yescount, 0, SQUARE_COUNT(state));
353     ret->square_nocount = snewn(SQUARE_COUNT(state), char);
354     memset(ret->square_nocount, 0, SQUARE_COUNT(state));
355
356     /* dot_nocount needs special initialisation as we define lines coming off
357      * dots on edges as fixed at NO */
358
359     FORALL_DOTS(state, i, j) {
360         if (i == 0 || i == state->w)
361             ++ret->dot_nocount[DOT_INDEX(state, i, j)];
362         if (j == 0 || j == state->h)
363             ++ret->dot_nocount[DOT_INDEX(state, i, j)];
364     }
365
366     if (diff < DIFF_NORMAL) {
367         ret->normal = NULL;
368     } else {
369         ret->normal = snew(normal_mode_state);
370
371         ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
372         memset(ret->normal->dot_atmostone, 0, DOT_COUNT(state));
373         ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
374         memset(ret->normal->dot_atleastone, 0, DOT_COUNT(state));
375     }
376
377     if (diff < DIFF_HARD) {
378         ret->hard = NULL;
379     } else {
380         ret->hard = snew(hard_mode_state);
381         ret->hard->linedsf = snew_dsf(LINE_COUNT(state));
382     }
383
384     return ret;
385 }
386
387 static void free_solver_state(solver_state *sstate) {
388     if (sstate) {
389         free_game(sstate->state);
390         sfree(sstate->dotdsf);
391         sfree(sstate->looplen);
392         sfree(sstate->dot_solved);
393         sfree(sstate->square_solved);
394         sfree(sstate->dot_yescount);
395         sfree(sstate->dot_nocount);
396         sfree(sstate->square_yescount);
397         sfree(sstate->square_nocount);
398
399         if (sstate->normal) {
400             sfree(sstate->normal->dot_atleastone);
401             sfree(sstate->normal->dot_atmostone);
402             sfree(sstate->normal);
403         }
404
405         if (sstate->hard) {
406             sfree(sstate->hard->linedsf);
407             sfree(sstate->hard);
408         }
409
410         sfree(sstate);
411     }
412 }
413
414 static solver_state *dup_solver_state(const solver_state *sstate) {
415     game_state *state;
416
417     solver_state *ret = snew(solver_state);
418
419     ret->state = state = dup_game(sstate->state);
420
421     ret->recursion_remaining = sstate->recursion_remaining;
422     ret->solver_status = sstate->solver_status;
423
424     ret->dotdsf = snewn(DOT_COUNT(state), int);
425     ret->looplen = snewn(DOT_COUNT(state), int);
426     memcpy(ret->dotdsf, sstate->dotdsf, 
427            DOT_COUNT(state) * sizeof(int));
428     memcpy(ret->looplen, sstate->looplen, 
429            DOT_COUNT(state) * sizeof(int));
430
431     ret->dot_solved = snewn(DOT_COUNT(state), char);
432     ret->square_solved = snewn(SQUARE_COUNT(state), char);
433     memcpy(ret->dot_solved, sstate->dot_solved, 
434            DOT_COUNT(state));
435     memcpy(ret->square_solved, sstate->square_solved, 
436            SQUARE_COUNT(state));
437
438     ret->dot_yescount = snewn(DOT_COUNT(state), char);
439     memcpy(ret->dot_yescount, sstate->dot_yescount,
440            DOT_COUNT(state));
441     ret->dot_nocount = snewn(DOT_COUNT(state), char);
442     memcpy(ret->dot_nocount, sstate->dot_nocount,
443            DOT_COUNT(state));
444
445     ret->square_yescount = snewn(SQUARE_COUNT(state), char);
446     memcpy(ret->square_yescount, sstate->square_yescount,
447            SQUARE_COUNT(state));
448     ret->square_nocount = snewn(SQUARE_COUNT(state), char);
449     memcpy(ret->square_nocount, sstate->square_nocount,
450            SQUARE_COUNT(state));
451
452     if (sstate->normal) {
453         ret->normal = snew(normal_mode_state);
454         ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
455         memcpy(ret->normal->dot_atmostone, sstate->normal->dot_atmostone,
456                DOT_COUNT(state));
457
458         ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
459         memcpy(ret->normal->dot_atleastone, sstate->normal->dot_atleastone,
460                DOT_COUNT(state));
461     } else {
462         ret->normal = NULL;
463     }
464
465     if (sstate->hard) {
466         ret->hard = snew(hard_mode_state);
467         ret->hard->linedsf = snewn(LINE_COUNT(state), int);
468         memcpy(ret->hard->linedsf, sstate->hard->linedsf, 
469                LINE_COUNT(state) * sizeof(int));
470     } else {
471         ret->hard = NULL;
472     }
473
474     return ret;
475 }
476
477 static game_params *default_params(void)
478 {
479     game_params *ret = snew(game_params);
480
481 #ifdef SLOW_SYSTEM
482     ret->h = 4;
483     ret->w = 4;
484 #else
485     ret->h = 10;
486     ret->w = 10;
487 #endif
488     ret->diff = DIFF_EASY;
489     ret->rec = 0;
490
491     return ret;
492 }
493
494 static game_params *dup_params(game_params *params)
495 {
496     game_params *ret = snew(game_params);
497     *ret = *params;                       /* structure copy */
498     return ret;
499 }
500
501 static const game_params presets[] = {
502     {  4,  4, DIFF_EASY, 0 },
503     {  4,  4, DIFF_NORMAL, 0 },
504     {  4,  4, DIFF_HARD, 0 },
505     {  7,  7, DIFF_EASY, 0 },
506     {  7,  7, DIFF_NORMAL, 0 },
507     {  7,  7, DIFF_HARD, 0 },
508     { 10, 10, DIFF_EASY, 0 },
509     { 10, 10, DIFF_NORMAL, 0 },
510     { 10, 10, DIFF_HARD, 0 },
511 #ifndef SLOW_SYSTEM
512     { 15, 15, DIFF_EASY, 0 },
513     { 15, 15, DIFF_NORMAL, 0 },
514     { 15, 15, DIFF_HARD, 0 },
515 #ifndef SMALL_SCREEN
516     { 30, 20, DIFF_EASY, 0 },
517     { 30, 20, DIFF_NORMAL, 0 },
518     { 30, 20, DIFF_HARD, 0 }
519 #endif
520 #endif
521 };
522
523 static int game_fetch_preset(int i, char **name, game_params **params)
524 {
525     game_params *tmppar;
526     char buf[80];
527
528     if (i < 0 || i >= lenof(presets))
529         return FALSE;
530
531     tmppar = snew(game_params);
532     *tmppar = presets[i];
533     *params = tmppar;
534     sprintf(buf, "%dx%d %s", tmppar->h, tmppar->w, diffnames[tmppar->diff]);
535     *name = dupstr(buf);
536
537     return TRUE;
538 }
539
540 static void free_params(game_params *params)
541 {
542     sfree(params);
543 }
544
545 static void decode_params(game_params *params, char const *string)
546 {
547     params->h = params->w = atoi(string);
548     params->rec = 0;
549     params->diff = DIFF_EASY;
550     while (*string && isdigit((unsigned char)*string)) string++;
551     if (*string == 'x') {
552         string++;
553         params->h = atoi(string);
554         while (*string && isdigit((unsigned char)*string)) string++;
555     }
556     if (*string == 'r') {
557         string++;
558         params->rec = atoi(string);
559         while (*string && isdigit((unsigned char)*string)) string++;
560     }
561     if (*string == 'd') {
562         int i;
563         string++;
564         for (i = 0; i < DIFF_MAX; i++)
565             if (*string == diffchars[i])
566                 params->diff = i;
567         if (*string) string++;
568     }
569 }
570
571 static char *encode_params(game_params *params, int full)
572 {
573     char str[80];
574     sprintf(str, "%dx%d", params->w, params->h);
575     if (full)
576     sprintf(str + strlen(str), "r%dd%c", params->rec, diffchars[params->diff]);
577     return dupstr(str);
578 }
579
580 static config_item *game_configure(game_params *params)
581 {
582     config_item *ret;
583     char buf[80];
584
585     ret = snewn(4, config_item);
586
587     ret[0].name = "Width";
588     ret[0].type = C_STRING;
589     sprintf(buf, "%d", params->w);
590     ret[0].sval = dupstr(buf);
591     ret[0].ival = 0;
592
593     ret[1].name = "Height";
594     ret[1].type = C_STRING;
595     sprintf(buf, "%d", params->h);
596     ret[1].sval = dupstr(buf);
597     ret[1].ival = 0;
598
599     ret[2].name = "Difficulty";
600     ret[2].type = C_CHOICES;
601     ret[2].sval = DIFFCONFIG;
602     ret[2].ival = params->diff;
603
604     ret[3].name = NULL;
605     ret[3].type = C_END;
606     ret[3].sval = NULL;
607     ret[3].ival = 0;
608
609     return ret;
610 }
611
612 static game_params *custom_params(config_item *cfg)
613 {
614     game_params *ret = snew(game_params);
615
616     ret->w = atoi(cfg[0].sval);
617     ret->h = atoi(cfg[1].sval);
618     ret->rec = 0;
619     ret->diff = cfg[2].ival;
620
621     return ret;
622 }
623
624 static char *validate_params(game_params *params, int full)
625 {
626     if (params->w < 4 || params->h < 4)
627         return "Width and height must both be at least 4";
628     if (params->rec < 0)
629         return "Recursion depth can't be negative";
630
631     /*
632      * This shouldn't be able to happen at all, since decode_params
633      * and custom_params will never generate anything that isn't
634      * within range.
635      */
636     assert(params->diff < DIFF_MAX);
637
638     return NULL;
639 }
640
641 /* Returns a newly allocated string describing the current puzzle */
642 static char *state_to_text(const game_state *state)
643 {
644     char *retval;
645     char *description = snewn(SQUARE_COUNT(state) + 1, char);
646     char *dp = description;
647     int empty_count = 0;
648     int i, j;
649
650     FORALL_SQUARES(state, i, j) {
651         if (CLUE_AT(state, i, j) < 0) {
652             if (empty_count > 25) {
653                 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
654                 empty_count = 0;
655             }
656             empty_count++;
657         } else {
658             if (empty_count) {
659                 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
660                 empty_count = 0;
661             }
662             dp += sprintf(dp, "%c", (int)CLUE2CHAR(CLUE_AT(state, i, j)));
663         }
664     }
665
666     if (empty_count)
667         dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
668
669     retval = dupstr(description);
670     sfree(description);
671
672     return retval;
673 }
674
675 /* We require that the params pass the test in validate_params and that the
676  * description fills the entire game area */
677 static char *validate_desc(game_params *params, char *desc)
678 {
679     int count = 0;
680
681     for (; *desc; ++desc) {
682         if (*desc >= '0' && *desc <= '9') {
683             count++;
684             continue;
685         }
686         if (*desc >= 'a') {
687             count += *desc - 'a' + 1;
688             continue;
689         }
690         return "Unknown character in description";
691     }
692
693     if (count < SQUARE_COUNT(params))
694         return "Description too short for board size";
695     if (count > SQUARE_COUNT(params))
696         return "Description too long for board size";
697
698     return NULL;
699 }
700
701 /* Sums the lengths of the numbers in range [0,n) */
702 /* See equivalent function in solo.c for justification of this. */
703 static int len_0_to_n(int n)
704 {
705     int len = 1; /* Counting 0 as a bit of a special case */
706     int i;
707
708     for (i = 1; i < n; i *= 10) {
709         len += max(n - i, 0);
710     }
711
712     return len;
713 }
714
715 static char *encode_solve_move(const game_state *state)
716 {
717     int len, i, j;
718     char *ret, *p;
719     /* This is going to return a string representing the moves needed to set
720      * every line in a grid to be the same as the ones in 'state'.  The exact
721      * length of this string is predictable. */
722
723     len = 1;  /* Count the 'S' prefix */
724     /* Numbers in horizontal lines */
725     /* Horizontal lines, x position */
726     len += len_0_to_n(state->w) * (state->h + 1);
727     /* Horizontal lines, y position */
728     len += len_0_to_n(state->h + 1) * (state->w);
729     /* Vertical lines, y position */
730     len += len_0_to_n(state->h) * (state->w + 1);
731     /* Vertical lines, x position */
732     len += len_0_to_n(state->w + 1) * (state->h);
733     /* For each line we also have two letters and a comma */
734     len += 3 * (LINE_COUNT(state));
735
736     ret = snewn(len + 1, char);
737     p = ret;
738
739     p += sprintf(p, "S");
740
741     FORALL_HL(state, i, j) {
742         switch (RIGHTOF_DOT(state, i, j)) {
743             case LINE_YES:
744                 p += sprintf(p, "%d,%dhy", i, j);
745                 break;
746             case LINE_NO:
747                 p += sprintf(p, "%d,%dhn", i, j);
748                 break;
749         }
750     }
751
752     FORALL_VL(state, i, j) {
753         switch (BELOW_DOT(state, i, j)) {
754             case LINE_YES:
755                 p += sprintf(p, "%d,%dvy", i, j);
756                 break;
757             case LINE_NO:
758                 p += sprintf(p, "%d,%dvn", i, j);
759                 break;
760         }
761     }
762
763     /* No point in doing sums like that if they're going to be wrong */
764     assert(strlen(ret) <= (size_t)len);
765     return ret;
766 }
767
768 static game_ui *new_ui(game_state *state)
769 {
770     return NULL;
771 }
772
773 static void free_ui(game_ui *ui)
774 {
775 }
776
777 static char *encode_ui(game_ui *ui)
778 {
779     return NULL;
780 }
781
782 static void decode_ui(game_ui *ui, char *encoding)
783 {
784 }
785
786 static void game_changed_state(game_ui *ui, game_state *oldstate,
787                                game_state *newstate)
788 {
789 }
790
791 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
792
793 static void game_compute_size(game_params *params, int tilesize,
794                               int *x, int *y)
795 {
796     struct { int tilesize; } ads, *ds = &ads;
797     ads.tilesize = tilesize;
798
799     *x = SIZE(params->w);
800     *y = SIZE(params->h);
801 }
802
803 static void game_set_size(drawing *dr, game_drawstate *ds,
804               game_params *params, int tilesize)
805 {
806     ds->tilesize = tilesize;
807     ds->linewidth = max(1,tilesize/16);
808 }
809
810 static float *game_colours(frontend *fe, int *ncolours)
811 {
812     float *ret = snewn(4 * NCOLOURS, float);
813
814     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
815
816     ret[COL_FOREGROUND * 3 + 0] = 0.0F;
817     ret[COL_FOREGROUND * 3 + 1] = 0.0F;
818     ret[COL_FOREGROUND * 3 + 2] = 0.0F;
819
820     ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
821     ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
822     ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
823
824     ret[COL_MISTAKE * 3 + 0] = 1.0F;
825     ret[COL_MISTAKE * 3 + 1] = 0.0F;
826     ret[COL_MISTAKE * 3 + 2] = 0.0F;
827
828     *ncolours = NCOLOURS;
829     return ret;
830 }
831
832 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
833 {
834     struct game_drawstate *ds = snew(struct game_drawstate);
835
836     ds->tilesize = ds->linewidth = 0;
837     ds->started = 0;
838     ds->hl = snewn(HL_COUNT(state), char);
839     ds->vl = snewn(VL_COUNT(state), char);
840     ds->clue_error = snewn(SQUARE_COUNT(state), char);
841     ds->flashing = 0;
842
843     memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
844     memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
845     memset(ds->clue_error, 0, SQUARE_COUNT(state));
846
847     return ds;
848 }
849
850 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
851 {
852     sfree(ds->clue_error);
853     sfree(ds->hl);
854     sfree(ds->vl);
855     sfree(ds);
856 }
857
858 static int game_timing_state(game_state *state, game_ui *ui)
859 {
860     return TRUE;
861 }
862
863 static float game_anim_length(game_state *oldstate, game_state *newstate,
864                               int dir, game_ui *ui)
865 {
866     return 0.0F;
867 }
868
869 static char *game_text_format(game_state *state)
870 {
871     int i, j;
872     int len;
873     char *ret, *rp;
874
875     len = (2 * state->w + 2) * (2 * state->h + 1);
876     rp = ret = snewn(len + 1, char);
877     
878 #define DRAW_HL \
879     switch (ABOVE_SQUARE(state, i, j)) { \
880         case LINE_YES: \
881             rp += sprintf(rp, " -"); \
882             break; \
883         case LINE_NO: \
884             rp += sprintf(rp, " x"); \
885             break; \
886         case LINE_UNKNOWN: \
887             rp += sprintf(rp, "  "); \
888             break; \
889         default: \
890             assert(!"Illegal line state for HL"); \
891     }
892
893 #define DRAW_VL \
894     switch (LEFTOF_SQUARE(state, i, j)) { \
895         case LINE_YES: \
896             rp += sprintf(rp, "|"); \
897             break; \
898         case LINE_NO: \
899             rp += sprintf(rp, "x"); \
900             break; \
901         case LINE_UNKNOWN: \
902             rp += sprintf(rp, " "); \
903             break; \
904         default: \
905             assert(!"Illegal line state for VL"); \
906     }
907     
908     for (j = 0; j < state->h; ++j) {
909         for (i = 0; i < state->w; ++i) {
910             DRAW_HL;
911         }
912         rp += sprintf(rp, " \n");
913         for (i = 0; i < state->w; ++i) {
914             DRAW_VL;
915             rp += sprintf(rp, "%c", (int)CLUE2CHAR(CLUE_AT(state, i, j)));
916         }
917         DRAW_VL;
918         rp += sprintf(rp, "\n");
919     }
920     for (i = 0; i < state->w; ++i) {
921         DRAW_HL;
922     }
923     rp += sprintf(rp, " \n");
924     
925     assert(strlen(ret) == len);
926     return ret;
927 }
928
929 /* ----------------------------------------------------------------------
930  * Debug code
931  */
932
933 #ifdef DEBUG_CACHES
934 static void check_caches(const solver_state* sstate)
935 {
936     int i, j;
937     const game_state *state = sstate->state;
938
939     FORALL_DOTS(state, i, j) {
940 #if 0
941         fprintf(stderr, "dot [%d,%d] y: %d %d n: %d %d\n", i, j,
942                dot_order(state, i, j, LINE_YES),
943                sstate->dot_yescount[i + (state->w + 1) * j],
944                dot_order(state, i, j, LINE_NO),
945                sstate->dot_nocount[i + (state->w + 1) * j]);
946 #endif
947                     
948         assert(dot_order(state, i, j, LINE_YES) ==
949                DOT_YES_COUNT(sstate, i, j));
950         assert(dot_order(state, i, j, LINE_NO) ==
951                DOT_NO_COUNT(sstate, i, j));
952     }
953
954     FORALL_SQUARES(state, i, j) {
955 #if 0
956         fprintf(stderr, "square [%d,%d] y: %d %d n: %d %d\n", i, j,
957                square_order(state, i, j, LINE_YES),
958                sstate->square_yescount[i + state->w * j],
959                square_order(state, i, j, LINE_NO),
960                sstate->square_nocount[i + state->w * j]);
961 #endif
962                     
963         assert(square_order(state, i, j, LINE_YES) ==
964                SQUARE_YES_COUNT(sstate, i, j));
965         assert(square_order(state, i, j, LINE_NO) ==
966                SQUARE_NO_COUNT(sstate, i, j));
967     }
968 }
969
970 #if 0
971 #define check_caches(s) \
972     do { \
973         fprintf(stderr, "check_caches at line %d\n", __LINE__); \
974         check_caches(s); \
975     } while (0)
976 #endif
977 #endif /* DEBUG_CACHES */
978
979 /* ----------------------------------------------------------------------
980  * Solver utility functions
981  */
982
983 static int set_line_bydot(solver_state *sstate, int x, int y, enum direction d,
984                           enum line_state line_new
985 #ifdef SHOW_WORKING
986                           , const char *reason
987 #endif
988                           ) 
989 {
990     game_state *state = sstate->state;
991
992     /* This line borders at most two squares in our board.  We figure out the
993      * x and y positions of those squares so we can record that their yes or no
994      * counts have been changed */
995     int sq1_x=-1, sq1_y=-1, sq2_x=-1, sq2_y=-1;
996     int otherdot_x=-1, otherdot_y=-1;
997
998     int progress = FALSE;
999
1000 #if 0
1001     fprintf(stderr, "set_line_bydot [%d,%d], %s, %d\n",
1002             x, y, DIR2STR(d), line_new);
1003 #endif
1004
1005     assert(line_new != LINE_UNKNOWN);
1006
1007     check_caches(sstate);
1008
1009     switch (d) {
1010         case LEFT:
1011             assert(x > 0);
1012
1013             if (LEFTOF_DOT(state, x, y) != line_new) {
1014                 LV_LEFTOF_DOT(state, x, y) = line_new;
1015
1016                 otherdot_x = x-1;
1017                 otherdot_y = y;
1018
1019                 sq1_x = x-1;
1020                 sq1_y = y-1;
1021                 sq2_x = x-1;
1022                 sq2_y = y;
1023
1024                 progress = TRUE;
1025             }
1026             break;
1027         case RIGHT:
1028             assert(x < state->w);
1029             if (RIGHTOF_DOT(state, x, y) != line_new) {
1030                 LV_RIGHTOF_DOT(state, x, y) = line_new;
1031
1032                 otherdot_x = x+1;
1033                 otherdot_y = y;
1034
1035                 sq1_x = x;
1036                 sq1_y = y-1;
1037                 sq2_x = x;
1038                 sq2_y = y;
1039
1040                 progress = TRUE;
1041             }
1042             break;
1043         case UP:
1044             assert(y > 0);
1045             if (ABOVE_DOT(state, x, y) != line_new) {
1046                 LV_ABOVE_DOT(state, x, y) = line_new;
1047
1048                 otherdot_x = x;
1049                 otherdot_y = y-1;
1050
1051                 sq1_x = x-1;
1052                 sq1_y = y-1;
1053                 sq2_x = x;
1054                 sq2_y = y-1;
1055
1056                 progress = TRUE;
1057             }
1058             break;
1059         case DOWN:
1060             assert(y < state->h);
1061             if (BELOW_DOT(state, x, y) != line_new) {
1062                 LV_BELOW_DOT(state, x, y) = line_new;
1063
1064                 otherdot_x = x;
1065                 otherdot_y = y+1;
1066
1067                 sq1_x = x-1;
1068                 sq1_y = y;
1069                 sq2_x = x;
1070                 sq2_y = y;
1071
1072                 progress = TRUE;
1073             }
1074             break;
1075     }
1076
1077     if (!progress)
1078         return progress;
1079
1080 #ifdef SHOW_WORKING
1081     fprintf(stderr, "set line [%d,%d] -> [%d,%d] to %s (%s)\n",
1082             x, y, otherdot_x, otherdot_y, line_new == LINE_YES ? "YES" : "NO",
1083             reason);
1084 #endif
1085
1086     /* Above we updated the cache for the dot that the line in question reaches
1087      * from the dot we've been told about.  Here we update that for the dot
1088      * named in our arguments. */
1089     if (line_new == LINE_YES) {
1090         if (sq1_x >= 0 && sq1_y >= 0)
1091             ++SQUARE_YES_COUNT(sstate, sq1_x, sq1_y);
1092         if (sq2_x < state->w && sq2_y < state->h)
1093             ++SQUARE_YES_COUNT(sstate, sq2_x, sq2_y);
1094         ++DOT_YES_COUNT(sstate, x, y);
1095         ++DOT_YES_COUNT(sstate, otherdot_x, otherdot_y);
1096     } else {
1097         if (sq1_x >= 0 && sq1_y >= 0)
1098             ++SQUARE_NO_COUNT(sstate, sq1_x, sq1_y);
1099         if (sq2_x < state->w && sq2_y < state->h)
1100             ++SQUARE_NO_COUNT(sstate, sq2_x, sq2_y);
1101         ++DOT_NO_COUNT(sstate, x, y);
1102         ++DOT_NO_COUNT(sstate, otherdot_x, otherdot_y);
1103     }
1104     
1105     check_caches(sstate);
1106     return progress;
1107 }
1108
1109 #ifdef SHOW_WORKING
1110 #define set_line_bydot(a, b, c, d, e) \
1111     set_line_bydot(a, b, c, d, e, __FUNCTION__)
1112 #endif
1113
1114 /*
1115  * Merge two dots due to the existence of an edge between them.
1116  * Updates the dsf tracking equivalence classes, and keeps track of
1117  * the length of path each dot is currently a part of.
1118  * Returns TRUE if the dots were already linked, ie if they are part of a
1119  * closed loop, and false otherwise.
1120  */
1121 static int merge_dots(solver_state *sstate, int x1, int y1, int x2, int y2)
1122 {
1123     int i, j, len;
1124
1125     i = y1 * (sstate->state->w + 1) + x1;
1126     j = y2 * (sstate->state->w + 1) + x2;
1127
1128     i = dsf_canonify(sstate->dotdsf, i);
1129     j = dsf_canonify(sstate->dotdsf, j);
1130
1131     if (i == j) {
1132         return TRUE;
1133     } else {
1134         len = sstate->looplen[i] + sstate->looplen[j];
1135         dsf_merge(sstate->dotdsf, i, j);
1136         i = dsf_canonify(sstate->dotdsf, i);
1137         sstate->looplen[i] = len;
1138         return FALSE;
1139     }
1140 }
1141
1142 /* Seriously, these should be functions */
1143
1144 #define LINEDSF_INDEX(state, x, y, d) \
1145    ((d == UP)    ? ((y-1) * (state->w + 1) + x) : \
1146     (d == DOWN)  ? ((y)   * (state->w + 1) + x) : \
1147     (d == LEFT)  ? ((y) * (state->w) + x-1 + VL_COUNT(state)) : \
1148     (d == RIGHT) ? ((y) * (state->w) + x   + VL_COUNT(state)) : \
1149     (assert(!"bad direction value"), 0))
1150
1151 static void linedsf_deindex(const game_state *state, int i, 
1152                             int *px, int *py, enum direction *pd)
1153 {
1154     int i_mod;
1155     if (i < VL_COUNT(state)) {
1156         *(pd) = DOWN;
1157         *(px) = (i) % (state->w+1);
1158         *(py) = (i) / (state->w+1);
1159     } else {
1160         i_mod = i - VL_COUNT(state);
1161         *(pd) = RIGHT;
1162         *(px) = (i_mod) % (state->w);
1163         *(py) = (i_mod) / (state->w);
1164     }
1165 }
1166
1167 /* Merge two lines because the solver has deduced that they must be either
1168  * identical or opposite.   Returns TRUE if this is new information, otherwise
1169  * FALSE. */
1170 static int merge_lines(solver_state *sstate, 
1171                        int x1, int y1, enum direction d1,
1172                        int x2, int y2, enum direction d2,
1173                        int inverse
1174 #ifdef SHOW_WORKING
1175                        , const char *reason
1176 #endif
1177                       )
1178 {
1179     int i, j, inv_tmp;
1180
1181     i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1182     j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1183
1184     assert(i < LINE_COUNT(sstate->state));
1185     assert(j < LINE_COUNT(sstate->state));
1186     
1187     i = edsf_canonify(sstate->hard->linedsf, i, &inv_tmp);
1188     inverse ^= inv_tmp;
1189     j = edsf_canonify(sstate->hard->linedsf, j, &inv_tmp);
1190     inverse ^= inv_tmp;
1191
1192     edsf_merge(sstate->hard->linedsf, i, j, inverse);
1193
1194 #ifdef SHOW_WORKING
1195     if (i != j) {
1196         fprintf(stderr, "%s [%d,%d,%s] [%d,%d,%s] %s(%s)\n",
1197                 __FUNCTION__, 
1198                 x1, y1, DIR2STR(d1),
1199                 x2, y2, DIR2STR(d2),
1200                 inverse ? "inverse " : "", reason);
1201     }
1202 #endif
1203     return (i != j);
1204 }
1205
1206 #ifdef SHOW_WORKING
1207 #define merge_lines(a, b, c, d, e, f, g, h) \
1208     merge_lines(a, b, c, d, e, f, g, h, __FUNCTION__)
1209 #endif
1210
1211 /* Return 0 if the given lines are not in the same equivalence class, 1 if they
1212  * are known identical, or 2 if they are known opposite */
1213 #if 0
1214 static int lines_related(solver_state *sstate,
1215                          int x1, int y1, enum direction d1, 
1216                          int x2, int y2, enum direction d2)
1217 {
1218     int i, j, inv1, inv2;
1219
1220     i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1221     j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1222   
1223     i = edsf_canonify(sstate->hard->linedsf, i, &inv1);
1224     j = edsf_canonify(sstate->hard->linedsf, j, &inv2);
1225
1226     if (i == j)
1227         return (inv1 == inv2) ? 1 : 2;
1228     else
1229         return 0;
1230 }
1231 #endif
1232
1233 /* Count the number of lines of a particular type currently going into the
1234  * given dot.  Lines going off the edge of the board are assumed fixed no. */
1235 static int dot_order(const game_state* state, int i, int j, char line_type)
1236 {
1237     int n = 0;
1238
1239     if (i > 0) {
1240         if (line_type == LV_LEFTOF_DOT(state, i, j))
1241             ++n;
1242     } else {
1243         if (line_type == LINE_NO)
1244             ++n;
1245     }
1246     if (i < state->w) {
1247         if (line_type == LV_RIGHTOF_DOT(state, i, j))
1248             ++n;
1249     } else {
1250         if (line_type == LINE_NO)
1251             ++n;
1252     }
1253     if (j > 0) {
1254         if (line_type == LV_ABOVE_DOT(state, i, j))
1255             ++n;
1256     } else {
1257         if (line_type == LINE_NO)
1258             ++n;
1259     }
1260     if (j < state->h) {
1261         if (line_type == LV_BELOW_DOT(state, i, j))
1262             ++n;
1263     } else {
1264         if (line_type == LINE_NO)
1265             ++n;
1266     }
1267
1268     return n;
1269 }
1270
1271 /* Count the number of lines of a particular type currently surrounding the
1272  * given square */
1273 static int square_order(const game_state* state, int i, int j, char line_type)
1274 {
1275     int n = 0;
1276
1277     if (ABOVE_SQUARE(state, i, j) == line_type)
1278         ++n;
1279     if (BELOW_SQUARE(state, i, j) == line_type)
1280         ++n;
1281     if (LEFTOF_SQUARE(state, i, j) == line_type)
1282         ++n;
1283     if (RIGHTOF_SQUARE(state, i, j) == line_type)
1284         ++n;
1285
1286     return n;
1287 }
1288
1289 /* Set all lines bordering a dot of type old_type to type new_type 
1290  * Return value tells caller whether this function actually did anything */
1291 static int dot_setall(solver_state *sstate, int i, int j,
1292                        char old_type, char new_type)
1293 {
1294     int retval = FALSE, r;
1295     game_state *state = sstate->state;
1296     
1297     if (old_type == new_type)
1298         return FALSE;
1299
1300     if (i > 0        && LEFTOF_DOT(state, i, j) == old_type) {
1301         r = set_line_bydot(sstate, i, j, LEFT, new_type);
1302         assert(r == TRUE);
1303         retval = TRUE;
1304     }
1305
1306     if (i < state->w && RIGHTOF_DOT(state, i, j) == old_type) {
1307         r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1308         assert(r == TRUE);
1309         retval = TRUE;
1310     }
1311
1312     if (j > 0        && ABOVE_DOT(state, i, j) == old_type) {
1313         r = set_line_bydot(sstate, i, j, UP, new_type);
1314         assert(r == TRUE);
1315         retval = TRUE;
1316     }
1317
1318     if (j < state->h && BELOW_DOT(state, i, j) == old_type) {
1319         r = set_line_bydot(sstate, i, j, DOWN, new_type);
1320         assert(r == TRUE);
1321         retval = TRUE;
1322     }
1323
1324     return retval;
1325 }
1326
1327 /* Set all lines bordering a square of type old_type to type new_type */
1328 static int square_setall(solver_state *sstate, int i, int j,
1329                          char old_type, char new_type)
1330 {
1331     int r = FALSE;
1332     game_state *state = sstate->state;
1333
1334 #if 0
1335     fprintf(stderr, "square_setall [%d,%d] from %d to %d\n", i, j,
1336                     old_type, new_type);
1337 #endif
1338     if (ABOVE_SQUARE(state, i, j) == old_type) {
1339         r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1340         assert(r == TRUE);
1341     }
1342     if (BELOW_SQUARE(state, i, j) == old_type) {
1343         r = set_line_bydot(sstate, i, j+1, RIGHT, new_type);
1344         assert(r == TRUE);
1345     }
1346     if (LEFTOF_SQUARE(state, i, j) == old_type) {
1347         r = set_line_bydot(sstate, i, j, DOWN, new_type);
1348         assert(r == TRUE);
1349     }
1350     if (RIGHTOF_SQUARE(state, i, j) == old_type) {
1351         r = set_line_bydot(sstate, i+1, j, DOWN, new_type);
1352         assert(r == TRUE);
1353     }
1354
1355     return r;
1356 }
1357
1358 /* ----------------------------------------------------------------------
1359  * Loop generation and clue removal
1360  */
1361
1362 /* We're going to store a list of current candidate squares for lighting.
1363  * Each square gets a 'score', which tells us how adding that square right
1364  * now would affect the length of the solution loop.  We're trying to
1365  * maximise that quantity so will bias our random selection of squares to
1366  * light towards those with high scores */
1367 struct square { 
1368     int score;
1369     unsigned long random;
1370     int x, y;
1371 };
1372
1373 static int get_square_cmpfn(void *v1, void *v2) 
1374 {
1375     struct square *s1 = v1;
1376     struct square *s2 = v2;
1377     int r;
1378     
1379     r = s1->x - s2->x;
1380     if (r)
1381         return r;
1382
1383     r = s1->y - s2->y;
1384     if (r)
1385         return r;
1386
1387     return 0;
1388 }
1389
1390 static int square_sort_cmpfn(void *v1, void *v2)
1391 {
1392     struct square *s1 = v1;
1393     struct square *s2 = v2;
1394     int r;
1395
1396     r = s2->score - s1->score;
1397     if (r) {
1398         return r;
1399     }
1400
1401     if (s1->random < s2->random)
1402         return -1;
1403     else if (s1->random > s2->random)
1404         return 1;
1405
1406     /*
1407      * It's _just_ possible that two squares might have been given
1408      * the same random value. In that situation, fall back to
1409      * comparing based on the coordinates. This introduces a tiny
1410      * directional bias, but not a significant one.
1411      */
1412     return get_square_cmpfn(v1, v2);
1413 }
1414
1415 enum { SQUARE_LIT, SQUARE_UNLIT };
1416
1417 #define SQUARE_STATE(i, j) \
1418     ( LEGAL_SQUARE(state, i, j) ? \
1419         LV_SQUARE_STATE(i,j) : \
1420         SQUARE_UNLIT )
1421
1422 #define LV_SQUARE_STATE(i, j) board[SQUARE_INDEX(state, i, j)]
1423
1424 /* Generate a new complete set of clues for the given game_state (respecting
1425  * the dimensions provided by said game_state) */
1426 static void add_full_clues(game_state *state, random_state *rs)
1427 {
1428     signed char *clues;
1429     char *board;
1430     int i, j, a, b, c;
1431     int board_area = SQUARE_COUNT(state);
1432     int t;
1433
1434     struct square *square, *tmpsquare, *sq;
1435     struct square square_pos;
1436
1437     /* These will contain exactly the same information, sorted into different
1438      * orders */
1439     tree234 *lightable_squares_sorted, *lightable_squares_gettable;
1440
1441 #define SQUARE_REACHABLE(i,j) \
1442      (t = (SQUARE_STATE(i-1, j) == SQUARE_LIT || \
1443            SQUARE_STATE(i+1, j) == SQUARE_LIT || \
1444            SQUARE_STATE(i, j-1) == SQUARE_LIT || \
1445            SQUARE_STATE(i, j+1) == SQUARE_LIT), \
1446       t)
1447
1448     /* One situation in which we may not light a square is if that'll leave one
1449      * square above/below and one left/right of us unlit, separated by a lit
1450      * square diagnonal from us */
1451 #define SQUARE_DIAGONAL_VIOLATION(i, j, h, v) \
1452     (t = (SQUARE_STATE((i)+(h), (j))     == SQUARE_UNLIT && \
1453           SQUARE_STATE((i),     (j)+(v)) == SQUARE_UNLIT && \
1454           SQUARE_STATE((i)+(h), (j)+(v)) == SQUARE_LIT), \
1455      t)
1456
1457     /* We also may not light a square if it will form a loop of lit squares
1458      * around some unlit squares, as then the game soln won't have a single
1459      * loop */
1460 #define SQUARE_LOOP_VIOLATION(i, j, lit1, lit2) \
1461     (SQUARE_STATE((i)+1, (j)) == lit1    && \
1462      SQUARE_STATE((i)-1, (j)) == lit1    && \
1463      SQUARE_STATE((i), (j)+1) == lit2    && \
1464      SQUARE_STATE((i), (j)-1) == lit2)
1465
1466 #define CAN_LIGHT_SQUARE(i, j) \
1467     (SQUARE_REACHABLE(i, j)                                 && \
1468      !SQUARE_DIAGONAL_VIOLATION(i, j, -1, -1)               && \
1469      !SQUARE_DIAGONAL_VIOLATION(i, j, +1, -1)               && \
1470      !SQUARE_DIAGONAL_VIOLATION(i, j, -1, +1)               && \
1471      !SQUARE_DIAGONAL_VIOLATION(i, j, +1, +1)               && \
1472      !SQUARE_LOOP_VIOLATION(i, j, SQUARE_LIT, SQUARE_UNLIT) && \
1473      !SQUARE_LOOP_VIOLATION(i, j, SQUARE_UNLIT, SQUARE_LIT))
1474
1475 #define IS_LIGHTING_CANDIDATE(i, j) \
1476     (SQUARE_STATE(i, j) == SQUARE_UNLIT && \
1477      CAN_LIGHT_SQUARE(i,j))
1478
1479     /* The 'score' of a square reflects its current desirability for selection
1480      * as the next square to light.  We want to encourage moving into uncharted
1481      * areas so we give scores according to how many of the square's neighbours
1482      * are currently unlit. */
1483
1484    /* UNLIT    SCORE
1485     *   3        2
1486     *   2        0
1487     *   1       -2
1488     */
1489 #define SQUARE_SCORE(i,j) \
1490     (2*((SQUARE_STATE(i-1, j) == SQUARE_UNLIT)  + \
1491         (SQUARE_STATE(i+1, j) == SQUARE_UNLIT)  + \
1492         (SQUARE_STATE(i, j-1) == SQUARE_UNLIT)  + \
1493         (SQUARE_STATE(i, j+1) == SQUARE_UNLIT)) - 4)
1494
1495     /* When a square gets lit, this defines how far away from that square we
1496      * need to go recomputing scores */
1497 #define SCORE_DISTANCE 1
1498
1499     board = snewn(board_area, char);
1500     clues = state->clues;
1501
1502     /* Make a board */
1503     memset(board, SQUARE_UNLIT, board_area);
1504     
1505     /* Seed the board with a single lit square near the middle */
1506     i = state->w / 2;
1507     j = state->h / 2;
1508     if (state->w & 1 && random_bits(rs, 1))
1509         ++i;
1510     if (state->h & 1 && random_bits(rs, 1))
1511         ++j;
1512
1513     LV_SQUARE_STATE(i, j) = SQUARE_LIT;
1514
1515     /* We need a way of favouring squares that will increase our loopiness.
1516      * We do this by maintaining a list of all candidate squares sorted by
1517      * their score and choose randomly from that with appropriate skew. 
1518      * In order to avoid consistently biasing towards particular squares, we
1519      * need the sort order _within_ each group of scores to be completely
1520      * random.  But it would be abusing the hospitality of the tree234 data
1521      * structure if our comparison function were nondeterministic :-).  So with
1522      * each square we associate a random number that does not change during a
1523      * particular run of the generator, and use that as a secondary sort key.
1524      * Yes, this means we will be biased towards particular random squares in
1525      * any one run but that doesn't actually matter. */
1526     
1527     lightable_squares_sorted   = newtree234(square_sort_cmpfn);
1528     lightable_squares_gettable = newtree234(get_square_cmpfn);
1529 #define ADD_SQUARE(s) \
1530     do { \
1531         sq = add234(lightable_squares_sorted, s); \
1532         assert(sq == s); \
1533         sq = add234(lightable_squares_gettable, s); \
1534         assert(sq == s); \
1535     } while (0)
1536
1537 #define REMOVE_SQUARE(s) \
1538     do { \
1539         sq = del234(lightable_squares_sorted, s); \
1540         assert(sq); \
1541         sq = del234(lightable_squares_gettable, s); \
1542         assert(sq); \
1543     } while (0)
1544         
1545 #define HANDLE_DIR(a, b) \
1546     square = snew(struct square); \
1547     square->x = (i)+(a); \
1548     square->y = (j)+(b); \
1549     square->score = 2; \
1550     square->random = random_bits(rs, 31); \
1551     ADD_SQUARE(square);
1552     HANDLE_DIR(-1, 0);
1553     HANDLE_DIR( 1, 0);
1554     HANDLE_DIR( 0,-1);
1555     HANDLE_DIR( 0, 1);
1556 #undef HANDLE_DIR
1557     
1558     /* Light squares one at a time until the board is interesting enough */
1559     while (TRUE)
1560     {
1561         /* We have count234(lightable_squares) possibilities, and in
1562          * lightable_squares_sorted they are sorted with the most desirable
1563          * first.  */
1564         c = count234(lightable_squares_sorted);
1565         if (c == 0)
1566             break;
1567         assert(c == count234(lightable_squares_gettable));
1568
1569         /* Check that the best square available is any good */
1570         square = (struct square *)index234(lightable_squares_sorted, 0);
1571         assert(square);
1572
1573         /*
1574          * We never want to _decrease_ the loop's perimeter. Making
1575          * moves that leave the perimeter the same is occasionally
1576          * useful: if it were _never_ done then the user would be
1577          * able to deduce illicitly that any degree-zero vertex was
1578          * on the outside of the loop. So we do it sometimes but
1579          * not always.
1580          */
1581         if (square->score < 0 || (square->score == 0 &&
1582                                   random_upto(rs, 2) == 0)) {
1583             break;
1584         }
1585
1586         assert(square->score == SQUARE_SCORE(square->x, square->y));
1587         assert(SQUARE_STATE(square->x, square->y) == SQUARE_UNLIT);
1588         assert(square->x >= 0 && square->x < state->w);
1589         assert(square->y >= 0 && square->y < state->h);
1590
1591         /* Update data structures */
1592         LV_SQUARE_STATE(square->x, square->y) = SQUARE_LIT;
1593         REMOVE_SQUARE(square);
1594
1595         /* We might have changed the score of any squares up to 2 units away in
1596          * any direction */
1597         for (b = -SCORE_DISTANCE; b <= SCORE_DISTANCE; b++) {
1598             for (a = -SCORE_DISTANCE; a <= SCORE_DISTANCE; a++) {
1599                 if (!a && !b) 
1600                     continue;
1601                 square_pos.x = square->x + a;
1602                 square_pos.y = square->y + b;
1603                 if (square_pos.x < 0 || square_pos.x >= state->w ||
1604                     square_pos.y < 0 || square_pos.y >= state->h) {
1605                    continue; 
1606                 }
1607                 tmpsquare = find234(lightable_squares_gettable, &square_pos,
1608                                     NULL);
1609                 if (tmpsquare) {
1610                     assert(tmpsquare->x == square_pos.x);
1611                     assert(tmpsquare->y == square_pos.y);
1612                     assert(SQUARE_STATE(tmpsquare->x, tmpsquare->y) == 
1613                            SQUARE_UNLIT);
1614                     REMOVE_SQUARE(tmpsquare);
1615                 } else {
1616                     tmpsquare = snew(struct square);
1617                     tmpsquare->x = square_pos.x;
1618                     tmpsquare->y = square_pos.y;
1619                     tmpsquare->random = random_bits(rs, 31);
1620                 }
1621                 tmpsquare->score = SQUARE_SCORE(tmpsquare->x, tmpsquare->y);
1622
1623                 if (IS_LIGHTING_CANDIDATE(tmpsquare->x, tmpsquare->y)) {
1624                     ADD_SQUARE(tmpsquare);
1625                 } else {
1626                     sfree(tmpsquare);
1627                 }
1628             }
1629         }
1630         sfree(square);
1631     }
1632
1633     /* Clean up */
1634     while ((square = delpos234(lightable_squares_gettable, 0)) != NULL)
1635         sfree(square);
1636     freetree234(lightable_squares_gettable);
1637     freetree234(lightable_squares_sorted);
1638
1639     /* Copy out all the clues */
1640     FORALL_SQUARES(state, i, j) {
1641         c = SQUARE_STATE(i, j);
1642         LV_CLUE_AT(state, i, j) = 0;
1643         if (SQUARE_STATE(i-1, j) != c) ++LV_CLUE_AT(state, i, j);
1644         if (SQUARE_STATE(i+1, j) != c) ++LV_CLUE_AT(state, i, j);
1645         if (SQUARE_STATE(i, j-1) != c) ++LV_CLUE_AT(state, i, j);
1646         if (SQUARE_STATE(i, j+1) != c) ++LV_CLUE_AT(state, i, j);
1647     }
1648
1649     sfree(board);
1650 }
1651
1652 static int game_has_unique_soln(const game_state *state, int diff)
1653 {
1654     int ret;
1655     solver_state *sstate_new;
1656     solver_state *sstate = new_solver_state((game_state *)state, diff);
1657     
1658     sstate_new = solve_game_rec(sstate, diff);
1659
1660     assert(sstate_new->solver_status != SOLVER_MISTAKE);
1661     ret = (sstate_new->solver_status == SOLVER_SOLVED);
1662
1663     free_solver_state(sstate_new);
1664     free_solver_state(sstate);
1665
1666     return ret;
1667 }
1668
1669 /* Remove clues one at a time at random. */
1670 static game_state *remove_clues(game_state *state, random_state *rs, 
1671                                 int diff)
1672 {
1673     int *square_list, squares;
1674     game_state *ret = dup_game(state), *saved_ret;
1675     int n;
1676 #ifdef SHOW_WORKING
1677     char *desc;
1678 #endif
1679
1680     /* We need to remove some clues.  We'll do this by forming a list of all
1681      * available clues, shuffling it, then going along one at a
1682      * time clearing each clue in turn for which doing so doesn't render the
1683      * board unsolvable. */
1684     squares = state->w * state->h;
1685     square_list = snewn(squares, int);
1686     for (n = 0; n < squares; ++n) {
1687         square_list[n] = n;
1688     }
1689
1690     shuffle(square_list, squares, sizeof(int), rs);
1691     
1692     for (n = 0; n < squares; ++n) {
1693         saved_ret = dup_game(ret);
1694         LV_CLUE_AT(ret, square_list[n] % state->w,
1695                    square_list[n] / state->w) = -1;
1696
1697 #ifdef SHOW_WORKING
1698         desc = state_to_text(ret);
1699         fprintf(stderr, "%dx%d:%s\n", state->w, state->h, desc);
1700         sfree(desc);
1701 #endif
1702
1703         if (game_has_unique_soln(ret, diff)) {
1704             free_game(saved_ret);
1705         } else {
1706             free_game(ret);
1707             ret = saved_ret;
1708         }
1709     }
1710     sfree(square_list);
1711
1712     return ret;
1713 }
1714
1715 static char *new_game_desc(game_params *params, random_state *rs,
1716                            char **aux, int interactive)
1717 {
1718     /* solution and description both use run-length encoding in obvious ways */
1719     char *retval;
1720     game_state *state = snew(game_state), *state_new;
1721
1722     state->h = params->h;
1723     state->w = params->w;
1724
1725     state->clues = snewn(SQUARE_COUNT(params), signed char);
1726     state->hl = snewn(HL_COUNT(params), char);
1727     state->vl = snewn(VL_COUNT(params), char);
1728
1729 newboard_please:
1730     memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1731     memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1732
1733     state->solved = state->cheated = FALSE;
1734     state->recursion_depth = params->rec;
1735
1736     /* Get a new random solvable board with all its clues filled in.  Yes, this
1737      * can loop for ever if the params are suitably unfavourable, but
1738      * preventing games smaller than 4x4 seems to stop this happening */
1739
1740     do {
1741         add_full_clues(state, rs);
1742     } while (!game_has_unique_soln(state, params->diff));
1743
1744     state_new = remove_clues(state, rs, params->diff);
1745     free_game(state);
1746     state = state_new;
1747
1748     if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1749 #ifdef SHOW_WORKING
1750         fprintf(stderr, "Rejecting board, it is too easy\n");
1751 #endif
1752         goto newboard_please;
1753     }
1754
1755     retval = state_to_text(state);
1756
1757     free_game(state);
1758     
1759     assert(!validate_desc(params, retval));
1760
1761     return retval;
1762 }
1763
1764 static game_state *new_game(midend *me, game_params *params, char *desc)
1765 {
1766     int i,j;
1767     game_state *state = snew(game_state);
1768     int empties_to_make = 0;
1769     int n;
1770     const char *dp = desc;
1771
1772     state->recursion_depth = 0; /* XXX pending removal, probably */
1773     
1774     state->h = params->h;
1775     state->w = params->w;
1776
1777     state->clues = snewn(SQUARE_COUNT(params), signed char);
1778     state->hl = snewn(HL_COUNT(params), char);
1779     state->vl = snewn(VL_COUNT(params), char);
1780
1781     state->solved = state->cheated = FALSE;
1782
1783     FORALL_SQUARES(params, i, j) {
1784         if (empties_to_make) {
1785             empties_to_make--;
1786             LV_CLUE_AT(state, i, j) = -1;
1787             continue;
1788         }
1789
1790         assert(*dp);
1791         n = *dp - '0';
1792         if (n >= 0 && n < 10) {
1793             LV_CLUE_AT(state, i, j) = n;
1794         } else {
1795             n = *dp - 'a' + 1;
1796             assert(n > 0);
1797             LV_CLUE_AT(state, i, j) = -1;
1798             empties_to_make = n - 1;
1799         }
1800         ++dp;
1801     }
1802
1803     memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1804     memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1805
1806     return state;
1807 }
1808
1809 enum { LOOP_NONE=0, LOOP_SOLN, LOOP_NOT_SOLN };
1810
1811 /* ----------------------------------------------------------------------
1812  * Solver logic
1813  *
1814  * Our solver modes operate as follows.  Each mode also uses the modes above it.
1815  *
1816  *   Easy Mode
1817  *   Just implement the rules of the game.
1818  *
1819  *   Normal Mode
1820  *   For each pair of lines through each dot we store a bit for whether
1821  *   at least one of them is on and whether at most one is on.  (If we know
1822  *   both or neither is on that's already stored more directly.)  That's six
1823  *   bits per dot.  Bit number n represents the lines shown in dline_desc.
1824  *
1825  *   Advanced Mode
1826  *   Use edsf data structure to make equivalence classes of lines that are
1827  *   known identical to or opposite to one another.
1828  */
1829
1830 /* The order the following are defined in is very important, see below.
1831  * The last two fields may seem non-obvious: they specify that when talking
1832  * about a square the dx and dy offsets should be added to the square coords to
1833  * get to the right dot.  Where dx and dy are -1 this means that the dline
1834  * doesn't make sense for a square. */
1835 /* XXX can this be done with a struct instead? */
1836 #define DLINES \
1837     DLINE(DLINE_UD, UP,   DOWN,  -1, -1) \
1838     DLINE(DLINE_LR, LEFT, RIGHT, -1, -1) \
1839     DLINE(DLINE_UR, UP,   RIGHT,  0,  1) \
1840     DLINE(DLINE_DL, DOWN, LEFT,   1,  0) \
1841     DLINE(DLINE_UL, UP,   LEFT,   1,  1) \
1842     DLINE(DLINE_DR, DOWN, RIGHT,  0,  0)
1843
1844 #define OPP_DLINE(dline_desc) ((dline_desc) ^ 1)
1845
1846 enum dline_desc {
1847 #define DLINE(desc, dir1, dir2, dx, dy) \
1848     desc,
1849     DLINES
1850 #undef DLINE
1851 };
1852
1853 struct dline {
1854     enum dline_desc desc;
1855     enum direction dir1, dir2;
1856     int dx, dy;
1857 };
1858
1859 const static struct dline dlines[] =  {
1860 #define DLINE(desc, dir1, dir2, dx, dy) \
1861     { desc, dir1, dir2, dx, dy },
1862     DLINES
1863 #undef DLINE
1864 };
1865
1866 #define FORALL_DOT_DLINES(dl_iter) \
1867     for (dl_iter = 0; dl_iter < lenof(dlines); ++dl_iter)
1868
1869 #define FORALL_SQUARE_DLINES(dl_iter) \
1870     for (dl_iter = 2; dl_iter < lenof(dlines); ++dl_iter)
1871
1872 #define DL2STR(d) \
1873     ((d==DLINE_UD) ? "DLINE_UD": \
1874      (d==DLINE_LR) ? "DLINE_LR": \
1875      (d==DLINE_UR) ? "DLINE_UR": \
1876      (d==DLINE_DL) ? "DLINE_DL": \
1877      (d==DLINE_UL) ? "DLINE_UL": \
1878      (d==DLINE_DR) ? "DLINE_DR": \
1879      "oops")
1880
1881 #define CHECK_DLINE_SENSIBLE(d) assert(dlines[(d)].dx != -1 && dlines[(d)].dy != -1)
1882
1883 /* This will fail an assertion if the directions handed to it are the same, as
1884  * no dline corresponds to that */
1885 static enum dline_desc dline_desc_from_dirs(enum direction dir1, 
1886                                             enum direction dir2)
1887 {
1888     int i;
1889
1890     assert (dir1 != dir2);
1891
1892     for (i = 0; i < lenof(dlines); ++i) {
1893         if ((dir1 == dlines[i].dir1 && dir2 == dlines[i].dir2) ||
1894             (dir1 == dlines[i].dir2 && dir2 == dlines[i].dir1)) {
1895             return dlines[i].desc;
1896         }
1897     }
1898
1899     assert(!"dline not found");
1900     return DLINE_UD; /* placate compiler */
1901 }
1902
1903 /* The following functions allow you to get or set info about the selected
1904  * dline corresponding to the dot or square at [i,j].  You'll get an assertion
1905  * failure if you talk about a dline that doesn't exist, ie if you ask about
1906  * non-touching lines around a square. */
1907 static int get_dot_dline(const game_state *state, const char *dline_array,
1908                          int i, int j, enum dline_desc desc)
1909 {
1910 /*    fprintf(stderr, "get_dot_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1911     return BIT_SET(dline_array[i + (state->w + 1) * j], desc);
1912 }
1913
1914 static int set_dot_dline(game_state *state, char *dline_array,
1915                          int i, int j, enum dline_desc desc
1916 #ifdef SHOW_WORKING
1917                          , const char *reason
1918 #endif
1919                          )
1920 {
1921     int ret;
1922     ret = SET_BIT(dline_array[i + (state->w + 1) * j], desc);
1923
1924 #ifdef SHOW_WORKING
1925     if (ret)
1926         fprintf(stderr, "set_dot_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1927 #endif
1928     return ret;
1929 }
1930
1931 static int get_square_dline(game_state *state, char *dline_array,
1932                             int i, int j, enum dline_desc desc)
1933 {
1934     CHECK_DLINE_SENSIBLE(desc);
1935 /*    fprintf(stderr, "get_square_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1936     return BIT_SET(dline_array[(i+dlines[desc].dx) + (state->w + 1) * (j+dlines[desc].dy)], 
1937                    desc);
1938 }
1939
1940 static int set_square_dline(game_state *state, char *dline_array,
1941                             int i, int j, enum dline_desc desc
1942 #ifdef SHOW_WORKING
1943                             , const char *reason
1944 #endif
1945                             )
1946 {
1947     int ret;
1948     CHECK_DLINE_SENSIBLE(desc);
1949     ret = SET_BIT(dline_array[(i+dlines[desc].dx) + (state->w + 1) * (j+dlines[desc].dy)], desc);
1950 #ifdef SHOW_WORKING
1951     if (ret)
1952         fprintf(stderr, "set_square_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1953 #endif
1954     return ret;
1955 }
1956
1957 #ifdef SHOW_WORKING
1958 #define set_dot_dline(a, b, c, d, e) \
1959         set_dot_dline(a, b, c, d, e, __FUNCTION__)
1960 #define set_square_dline(a, b, c, d, e) \
1961         set_square_dline(a, b, c, d, e, __FUNCTION__)
1962 #endif
1963
1964 static int set_dot_opp_dline(game_state *state, char *dline_array,
1965                              int i, int j, enum dline_desc desc)
1966 {
1967     return set_dot_dline(state, dline_array, i, j, OPP_DLINE(desc));
1968 }
1969
1970 static int set_square_opp_dline(game_state *state, char *dline_array,
1971                                 int i, int j, enum dline_desc desc)
1972 {
1973     return set_square_dline(state, dline_array, i, j, OPP_DLINE(desc));
1974 }
1975
1976 /* Find out if both the lines in the given dline are UNKNOWN */
1977 static int dline_both_unknown(const game_state *state, int i, int j,
1978                               enum dline_desc desc)
1979 {
1980     return 
1981         (get_line_status_from_point(state, i, j, dlines[desc].dir1) == LINE_UNKNOWN) &&
1982         (get_line_status_from_point(state, i, j, dlines[desc].dir2) == LINE_UNKNOWN);
1983 }
1984
1985 #define SQUARE_DLINES \
1986                    HANDLE_DLINE(DLINE_UL, RIGHTOF_SQUARE, BELOW_SQUARE, 1, 1); \
1987                    HANDLE_DLINE(DLINE_UR, LEFTOF_SQUARE,  BELOW_SQUARE, 0, 1); \
1988                    HANDLE_DLINE(DLINE_DL, RIGHTOF_SQUARE, ABOVE_SQUARE, 1, 0); \
1989                    HANDLE_DLINE(DLINE_DR, LEFTOF_SQUARE,  ABOVE_SQUARE, 0, 0); 
1990
1991 #define DOT_DLINES \
1992                    HANDLE_DLINE(DLINE_UD,    ABOVE_DOT,  BELOW_DOT); \
1993                    HANDLE_DLINE(DLINE_LR,    LEFTOF_DOT, RIGHTOF_DOT); \
1994                    HANDLE_DLINE(DLINE_UL,    ABOVE_DOT,  LEFTOF_DOT); \
1995                    HANDLE_DLINE(DLINE_UR,    ABOVE_DOT,  RIGHTOF_DOT); \
1996                    HANDLE_DLINE(DLINE_DL,    BELOW_DOT,  LEFTOF_DOT); \
1997                    HANDLE_DLINE(DLINE_DR,    BELOW_DOT,  RIGHTOF_DOT); 
1998
1999 static void array_setall(char *array, char from, char to, int len)
2000 {
2001     char *p = array, *p_old = p;
2002     int len_remaining = len;
2003
2004     while ((p = memchr(p, from, len_remaining))) {
2005         *p = to;
2006         len_remaining -= p - p_old;
2007         p_old = p;
2008     }
2009 }
2010
2011
2012
2013 static int get_line_status_from_point(const game_state *state,
2014                                       int x, int y, enum direction d)
2015 {
2016     switch (d) {
2017         case LEFT:
2018             return LEFTOF_DOT(state, x, y);
2019         case RIGHT:
2020             return RIGHTOF_DOT(state, x, y);
2021         case UP:
2022             return ABOVE_DOT(state, x, y);
2023         case DOWN:
2024             return BELOW_DOT(state, x, y);
2025     }
2026
2027     return 0;
2028 }
2029
2030 /* First and second args are coord offset from top left of square to one end
2031  * of line in question, third and fourth args are the direction from the first
2032  * end of the line to the second.  Fifth arg is the direction of the line from
2033  * the coord offset position.
2034  * How confusing.  
2035  */
2036 #define SQUARE_LINES \
2037     SQUARE_LINE( 0,  0, RIGHT, RIGHTOF_DOT, UP); \
2038     SQUARE_LINE( 0, +1, RIGHT, RIGHTOF_DOT, DOWN); \
2039     SQUARE_LINE( 0,  0, DOWN,  BELOW_DOT,   LEFT); \
2040     SQUARE_LINE(+1,  0, DOWN,  BELOW_DOT,   RIGHT); 
2041
2042 /* Set pairs of lines around this square which are known to be identical to
2043  * the given line_state */
2044 static int square_setall_identical(solver_state *sstate, int x, int y,
2045                                    enum line_state line_new)
2046 {
2047     /* can[dir] contains the canonical line associated with the line in
2048      * direction dir from the square in question.  Similarly inv[dir] is
2049      * whether or not the line in question is inverse to its canonical
2050      * element. */
2051     int can[4], inv[4], i, j;
2052     int retval = FALSE;
2053
2054     i = 0;
2055
2056 #if 0
2057     fprintf(stderr, "Setting all identical unknown lines around square "
2058                     "[%d,%d] to %d:\n", x, y, line_new);                 
2059 #endif
2060
2061 #define SQUARE_LINE(dx, dy, linedir, dir_dot, sqdir) \
2062     can[sqdir] = \
2063         edsf_canonify(sstate->hard->linedsf, \
2064                       LINEDSF_INDEX(sstate->state, x+(dx), y+(dy), linedir), \
2065                       &inv[sqdir]);
2066     
2067     SQUARE_LINES;
2068
2069 #undef SQUARE_LINE
2070
2071     for (j = 0; j < 4; ++j) {
2072         for (i = 0; i < 4; ++i) {
2073             if (i == j)
2074                 continue;
2075
2076             if (can[i] == can[j] && inv[i] == inv[j]) {
2077
2078                 /* Lines in directions i and j are identical.
2079                  * Only do j now, we'll do i when the loop causes us to
2080                  * consider {i,j} in the opposite order. */
2081 #define SQUARE_LINE(dx, dy, dir, c, sqdir) \
2082                 if (j == sqdir) { \
2083                     retval = set_line_bydot(sstate, x+(dx), y+(dy), dir, line_new); \
2084                     if (retval) { \
2085                         break; \
2086                     } \
2087                 }
2088                 
2089                 SQUARE_LINES;
2090
2091 #undef SQUARE_LINE
2092             }
2093         }
2094     }
2095
2096     return retval;
2097 }
2098
2099 #if 0
2100 /* Set all identical lines passing through the current dot to the chosen line
2101  * state.  (implicitly this only looks at UNKNOWN lines) */
2102 static int dot_setall_identical(solver_state *sstate, int x, int y,
2103                                 enum line_state line_new)
2104 {
2105     /* The implementation of this is a little naughty but I can't see how to do
2106      * it elegantly any other way */
2107     int can[4], inv[4], i, j;
2108     enum direction d;
2109     int retval = FALSE;
2110
2111     for (d = 0; d < 4; ++d) {
2112         can[d] = edsf_canonify(sstate->hard->linedsf, 
2113                                LINEDSF_INDEX(sstate->state, x, y, d),
2114                                inv+d);
2115     }
2116     
2117     for (j = 0; j < 4; ++j) {
2118 next_j:
2119         for (i = 0; i < j; ++i) {
2120             if (can[i] == can[j] && inv[i] == inv[j]) {
2121                 /* Lines in directions i and j are identical */
2122                 if (get_line_status_from_point(sstate->state, x, y, j) ==
2123                         LINE_UNKNOWN) {
2124                     set_line_bydot(sstate->state, x, y, j, 
2125                                                line_new);
2126                     retval = TRUE;
2127                     goto next_j;
2128                 }
2129             }
2130
2131         }
2132     }
2133
2134     return retval;
2135 }
2136 #endif
2137
2138 static int square_setboth_in_dline(solver_state *sstate, enum dline_desc dd,
2139                                    int i, int j, enum line_state line_new)
2140 {
2141     int retval = FALSE;
2142     const struct dline dll = dlines[dd], *dl = &dll;
2143     
2144 #if 0
2145     fprintf(stderr, "square_setboth_in_dline %s [%d,%d] to %d\n",
2146                     DL2STR(dd), i, j, line_new);
2147 #endif
2148
2149     CHECK_DLINE_SENSIBLE(dd);
2150     
2151     retval |=
2152         set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir1, line_new);
2153     retval |=
2154         set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir2, line_new);
2155
2156     return retval;
2157 }
2158
2159 /* Call this function to register that the two unknown lines going into the dot
2160  * [x,y] are identical or opposite (depending on the value of 'inverse').  This
2161  * function will cause an assertion failure if anything other than exactly two
2162  * lines into the dot are unknown. 
2163  * As usual returns TRUE if any progress was made, otherwise FALSE. */
2164 static int dot_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2165 {
2166     enum direction d1=DOWN, d2=DOWN; /* Just to keep compiler quiet */
2167     int dirs_set = 0;
2168
2169 #define TRY_DIR(d) \
2170               if (get_line_status_from_point(sstate->state, x, y, d) == \
2171                       LINE_UNKNOWN) { \
2172                   if (dirs_set == 0) \
2173                       d1 = d; \
2174                   else { \
2175                       assert(dirs_set == 1); \
2176                       d2 = d; \
2177                   } \
2178                   dirs_set++; \
2179               } while (0)
2180     
2181     TRY_DIR(UP);
2182     TRY_DIR(DOWN);
2183     TRY_DIR(LEFT);
2184     TRY_DIR(RIGHT);
2185 #undef TRY_DIR
2186
2187     assert(dirs_set == 2);
2188     assert(d1 != d2);
2189
2190 #if 0
2191     fprintf(stderr, "Lines in direction %s and %s from dot [%d,%d] are %s\n",
2192             DIR2STR(d1), DIR2STR(d2), x, y, inverse?"opposite":"the same");
2193 #endif
2194
2195     return merge_lines(sstate, x, y, d1, x, y, d2, inverse);
2196 }
2197
2198 /* Very similar to dot_relate_2_unknowns. */
2199 static int square_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2200 {
2201     enum direction d1=DOWN, d2=DOWN;
2202     int x1=-1, y1=-1, x2=-1, y2=-1;
2203     int dirs_set = 0;
2204
2205 #if 0
2206     fprintf(stderr, "2 unknowns around square [%d,%d] are %s\n",
2207                      x, y, inverse?"opposite":"the same");
2208 #endif
2209
2210 #define TRY_DIR(i, j, d, dir_sq) \
2211           do { \
2212               if (dir_sq(sstate->state, x, y) == LINE_UNKNOWN) { \
2213                   if (dirs_set == 0) { \
2214                       d1 = d; x1 = i; y1 = j; \
2215                   } else { \
2216                       assert(dirs_set == 1); \
2217                       d2 = d; x2 = i; y2 = j; \
2218                   } \
2219                   dirs_set++; \
2220               } \
2221           } while (0)
2222     
2223     TRY_DIR(x,   y,   RIGHT, ABOVE_SQUARE);
2224     TRY_DIR(x,   y,   DOWN, LEFTOF_SQUARE);
2225     TRY_DIR(x+1, y,   DOWN, RIGHTOF_SQUARE);
2226     TRY_DIR(x,   y+1, RIGHT, BELOW_SQUARE);
2227 #undef TRY_DIR
2228
2229     assert(dirs_set == 2);
2230
2231 #if 0
2232     fprintf(stderr, "Line in direction %s from dot [%d,%d] and line in direction %s from dot [%2d,%2d] are %s\n",
2233             DIR2STR(d1), x1, y1, DIR2STR(d2), x2, y2, inverse?"opposite":"the same");
2234 #endif
2235
2236     return merge_lines(sstate, x1, y1, d1, x2, y2, d2, inverse);
2237 }
2238
2239 /* Figure out if any dlines can be 'collapsed' (and do so if they can).  This
2240  * can happen if one of the lines is known and due to the dline status this
2241  * tells us state of the other, or if there's an interaction with the linedsf
2242  * (ie if atmostone is set for a dline and the lines are known identical they
2243  * must both be LINE_NO, etc).  XXX at the moment only the former is
2244  * implemented, and indeed the latter should be implemented in the hard mode
2245  * solver only.
2246  */
2247 static int dot_collapse_dlines(solver_state *sstate, int i, int j)
2248 {
2249     int progress = FALSE;
2250     enum direction dir1, dir2;
2251     int dir1st;
2252     int dlset;
2253     game_state *state = sstate->state;
2254     enum dline_desc dd;
2255
2256     for (dir1 = 0; dir1 < 4; dir1++) {
2257         dir1st = get_line_status_from_point(state, i, j, dir1);
2258         if (dir1st == LINE_UNKNOWN)
2259             continue;
2260         /* dir2 iterates over the whole range rather than starting at dir1+1
2261          * because test below is asymmetric */
2262         for (dir2 = 0; dir2 < 4; dir2++) {
2263             if (dir1 == dir2)
2264                 continue;
2265
2266             if ((i == 0        && (dir1 == LEFT  || dir2 == LEFT))  ||
2267                 (j == 0        && (dir1 == UP    || dir2 == UP))    ||
2268                 (i == state->w && (dir1 == RIGHT || dir2 == RIGHT)) ||
2269                 (j == state->h && (dir1 == DOWN  || dir2 == DOWN))) {
2270                 continue;
2271             }
2272
2273 #if 0
2274         fprintf(stderr, "dot_collapse_dlines [%d,%d], %s %s\n", i, j,
2275                     DIR2STR(dir1), DIR2STR(dir2));
2276 #endif
2277
2278             if (get_line_status_from_point(state, i, j, dir2) == 
2279                 LINE_UNKNOWN) {
2280                 dd = dline_desc_from_dirs(dir1, dir2);
2281
2282                 dlset = get_dot_dline(state, sstate->normal->dot_atmostone, i, j, dd);
2283                 if (dlset && dir1st == LINE_YES) {
2284 /*                    fprintf(stderr, "setting %s to NO\n", DIR2STR(dir2)); */
2285                     progress |= 
2286                         set_line_bydot(sstate, i, j, dir2, LINE_NO);
2287                 }
2288
2289                 dlset = get_dot_dline(state, sstate->normal->dot_atleastone, i, j, dd);
2290                 if (dlset && dir1st == LINE_NO) {
2291 /*                    fprintf(stderr, "setting %s to YES\n", DIR2STR(dir2)); */
2292                     progress |=
2293                         set_line_bydot(sstate, i, j, dir2, LINE_YES);
2294                 }
2295             }
2296         }
2297     }
2298
2299     return progress;
2300 }
2301
2302 /*
2303  * These are the main solver functions.  
2304  *
2305  * Their return values are diff values corresponding to the lowest mode solver
2306  * that would notice the work that they have done.  For example if the normal
2307  * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2308  * easy mode solver might be able to make progress using that.  It doesn't make
2309  * sense for one of them to return a diff value higher than that of the
2310  * function itself.  
2311  *
2312  * Each function returns the lowest value it can, as early as possible, in
2313  * order to try and pass as much work as possible back to the lower level
2314  * solvers which progress more quickly.
2315  */
2316
2317 /* PROPOSED NEW DESIGN:
2318  * We have a work queue consisting of 'events' notifying us that something has
2319  * happened that a particular solver mode might be interested in.  For example
2320  * the hard mode solver might do something that helps the normal mode solver at
2321  * dot [x,y] in which case it will enqueue an event recording this fact.  Then
2322  * we pull events off the work queue, and hand each in turn to the solver that
2323  * is interested in them.  If a solver reports that it failed we pass the same
2324  * event on to progressively more advanced solvers and the loop detector.  Once
2325  * we've exhausted an event, or it has helped us progress, we drop it and
2326  * continue to the next one.  The events are sorted first in order of solver
2327  * complexity (easy first) then order of insertion (oldest first).
2328  * Once we run out of events we loop over each permitted solver in turn
2329  * (easiest first) until either a deduction is made (and an event therefore
2330  * emerges) or no further deductions can be made (in which case we've failed).
2331  *
2332  * QUESTIONS: 
2333  *    * How do we 'loop over' a solver when both dots and squares are concerned.
2334  *      Answer: first all squares then all dots.
2335  */
2336
2337 static int easy_mode_deductions(solver_state *sstate)
2338 {
2339     int i, j, h, w, current_yes, current_no;
2340     game_state *state;
2341     int diff = DIFF_MAX;
2342
2343     state = sstate->state;
2344     h = state->h;
2345     w = state->w;
2346     
2347     /* Per-square deductions */
2348     FORALL_SQUARES(state, i, j) {
2349         if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2350             continue;
2351
2352         current_yes = SQUARE_YES_COUNT(sstate, i, j);
2353         current_no  = SQUARE_NO_COUNT(sstate, i, j);
2354
2355         if (current_yes + current_no == 4)  {
2356             sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2357 /*            diff = min(diff, DIFF_EASY); */
2358             continue;
2359         }
2360
2361         if (CLUE_AT(state, i, j) < 0)
2362             continue;
2363
2364         if (CLUE_AT(state, i, j) < current_yes) {
2365 #if 0
2366             fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2367 #endif
2368             sstate->solver_status = SOLVER_MISTAKE;
2369             return DIFF_EASY;
2370         }
2371         if (CLUE_AT(state, i, j) == current_yes) {
2372             if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO))
2373                 diff = min(diff, DIFF_EASY);
2374             sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2375             continue;
2376         }
2377
2378         if (4 - CLUE_AT(state, i, j) < current_no) {
2379 #if 0
2380             fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2381 #endif
2382             sstate->solver_status = SOLVER_MISTAKE;
2383             return DIFF_EASY;
2384         }
2385         if (4 - CLUE_AT(state, i, j) == current_no) {
2386             if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES))
2387                 diff = min(diff, DIFF_EASY);
2388             sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2389             continue;
2390         }
2391     }
2392
2393     check_caches(sstate);
2394
2395     /* Per-dot deductions */
2396     FORALL_DOTS(state, i, j) {
2397         if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2398             continue;
2399
2400         switch (DOT_YES_COUNT(sstate, i, j)) {
2401             case 0:
2402                 switch (DOT_NO_COUNT(sstate, i, j)) {
2403                     case 3:
2404 #if 0
2405                         fprintf(stderr, "dot [%d,%d]: 0 yes, 3 no\n", i, j);
2406 #endif
2407                         dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2408                         diff = min(diff, DIFF_EASY);
2409                         /* fall through */
2410                     case 4:
2411                         sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2412                         break;
2413                 }
2414                 break;
2415             case 1:
2416                 switch (DOT_NO_COUNT(sstate, i, j)) {
2417                     case 2: /* 1 yes, 2 no */
2418 #if 0
2419                         fprintf(stderr, "dot [%d,%d]: 1 yes, 2 no\n", i, j);
2420 #endif
2421                         dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES);
2422                         diff = min(diff, DIFF_EASY);
2423                         sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2424                         break;
2425                     case 3: /* 1 yes, 3 no */
2426 #if 0
2427                         fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2428 #endif
2429                         sstate->solver_status = SOLVER_MISTAKE;
2430                         return DIFF_EASY;
2431                 }
2432                 break;
2433             case 2:
2434 #if 0
2435                 fprintf(stderr, "dot [%d,%d]: 2 yes\n", i, j);
2436 #endif
2437                 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2438                 diff = min(diff, DIFF_EASY);
2439                 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2440                 break;
2441             case 3:
2442             case 4:
2443 #if 0
2444                 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2445 #endif
2446                 sstate->solver_status = SOLVER_MISTAKE;
2447                 return DIFF_EASY;
2448         }
2449     }
2450
2451     check_caches(sstate);
2452
2453     return diff;
2454 }
2455
2456 static int normal_mode_deductions(solver_state *sstate)
2457 {
2458     int i, j;
2459     game_state *state = sstate->state;
2460     enum dline_desc dd;
2461     int diff = DIFF_MAX;
2462
2463     FORALL_SQUARES(state, i, j) {
2464         if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2465             continue;
2466
2467         if (CLUE_AT(state, i, j) < 0)
2468             continue;
2469
2470         switch (CLUE_AT(state, i, j)) {
2471             case 1:
2472 #if 0
2473                 fprintf(stderr, "clue [%d,%d] is 1, doing dline ops\n",
2474                         i, j);
2475 #endif
2476                 FORALL_SQUARE_DLINES(dd) {
2477                     /* At most one of any DLINE can be set */
2478                     if (set_square_dline(state, 
2479                                          sstate->normal->dot_atmostone, 
2480                                          i, j, dd)) {
2481                         diff = min(diff, DIFF_NORMAL);
2482                     }
2483
2484                     if (get_square_dline(state,
2485                                          sstate->normal->dot_atleastone, 
2486                                          i, j, dd)) {
2487                         /* This DLINE provides enough YESes to solve the clue */
2488                         if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2489                                                      i, j, LINE_NO)) {
2490                             diff = min(diff, DIFF_EASY);
2491                         }
2492                     }
2493                 }
2494
2495                 break;
2496             case 2:
2497                 /* If at least one of one DLINE is set, at most one
2498                  * of the opposing one is and vice versa */
2499 #if 0
2500                 fprintf(stderr, "clue [%d,%d] is 2, doing dline ops\n",
2501                                i, j);
2502 #endif
2503                 FORALL_SQUARE_DLINES(dd) {
2504                     if (get_square_dline(state,
2505                                          sstate->normal->dot_atmostone,
2506                                          i, j, dd)) {
2507                         if (set_square_opp_dline(state,
2508                                                  sstate->normal->dot_atleastone,
2509                                                  i, j, dd)) {
2510                             diff = min(diff, DIFF_NORMAL);
2511                         }
2512                     }
2513                     if (get_square_dline(state,
2514                                          sstate->normal->dot_atleastone,
2515                                          i, j, dd)) {
2516                         if (set_square_opp_dline(state,
2517                                                  sstate->normal->dot_atmostone,
2518                                                  i, j, dd)) {
2519                             diff = min(diff, DIFF_NORMAL);
2520                         }
2521                     }
2522                 }
2523                 break;
2524             case 3:
2525 #if 0
2526                 fprintf(stderr, "clue [%d,%d] is 3, doing dline ops\n",
2527                                 i, j);
2528 #endif
2529                 FORALL_SQUARE_DLINES(dd) {
2530                     /* At least one of any DLINE must be set */
2531                     if (set_square_dline(state, 
2532                                          sstate->normal->dot_atleastone, 
2533                                          i, j, dd)) {
2534                         diff = min(diff, DIFF_NORMAL);
2535                     }
2536
2537                     if (get_square_dline(state,
2538                                          sstate->normal->dot_atmostone, 
2539                                          i, j, dd)) {
2540                         /* This DLINE provides enough NOs to solve the clue */
2541                         if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2542                                                     i, j, LINE_YES)) {
2543                             diff = min(diff, DIFF_EASY);
2544                         }
2545                     }
2546                 }
2547                 break;
2548         }
2549     }
2550
2551     check_caches(sstate);
2552
2553     if (diff < DIFF_NORMAL)
2554         return diff;
2555
2556     FORALL_DOTS(state, i, j) {
2557         if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2558             continue;
2559
2560 #if 0
2561         text = game_text_format(state);
2562         fprintf(stderr, "-----------------\n%s", text);
2563         sfree(text);
2564 #endif
2565
2566         switch (DOT_YES_COUNT(sstate, i, j)) {
2567         case 0:
2568             switch (DOT_NO_COUNT(sstate, i, j)) {
2569                 case 1:
2570                     /* Make note that at most one of each unknown DLINE
2571                      * is YES */
2572                     break;
2573             }
2574             break;
2575
2576         case 1:
2577             switch (DOT_NO_COUNT(sstate, i, j)) {
2578                 case 1: 
2579                     /* 1 yes, 1 no, so exactly one of unknowns is
2580                      * yes */
2581 #if 0
2582                     fprintf(stderr, "dot [%d,%d]: 1 yes, 1 no\n", i, j);
2583 #endif
2584                     FORALL_DOT_DLINES(dd) {
2585                         if (dline_both_unknown(state, 
2586                                                i, j, dd)) {
2587                             if (set_dot_dline(state,
2588                                               sstate->normal->dot_atleastone,
2589                                               i, j, dd)) {
2590                                 diff = min(diff, DIFF_NORMAL); 
2591                             }
2592                         }
2593                     }
2594
2595                     /* fall through */
2596                 case 0: 
2597 #if 0
2598                     fprintf(stderr, "dot [%d,%d]: 1 yes, 0 or 1 no\n", i, j);
2599 #endif
2600                     /* 1 yes, fewer than 2 no, so at most one of
2601                      * unknowns is yes */
2602                     FORALL_DOT_DLINES(dd) {
2603                         if (dline_both_unknown(state, 
2604                                                i, j, dd)) {
2605                             if (set_dot_dline(state,
2606                                               sstate->normal->dot_atmostone,
2607                                               i, j, dd)) {
2608                                 diff = min(diff, DIFF_NORMAL); 
2609                             }
2610                         }
2611                     }
2612                     break;
2613             }
2614             break;
2615         }
2616
2617         /* DLINE deductions that don't depend on the exact number of
2618          * LINE_YESs or LINE_NOs */
2619
2620         /* If at least one of a dline in a dot is YES, at most one
2621          * of the opposite dline to that dot must be YES. */
2622         FORALL_DOT_DLINES(dd) {
2623             if (get_dot_dline(state, 
2624                               sstate->normal->dot_atleastone,
2625                               i, j, dd)) {
2626                 if (set_dot_opp_dline(state,
2627                                       sstate->normal->dot_atmostone,
2628                                       i, j, dd)) {
2629                     diff = min(diff, DIFF_NORMAL); 
2630                 }
2631             }
2632         }
2633
2634         if (dot_collapse_dlines(sstate, i, j))
2635             diff = min(diff, DIFF_EASY);
2636     }
2637     check_caches(sstate);
2638
2639     return diff;
2640 }
2641
2642 static int hard_mode_deductions(solver_state *sstate)
2643 {
2644     int i, j, a, b, s;
2645     game_state *state = sstate->state;
2646     const int h=state->h, w=state->w;
2647     enum direction dir1, dir2;
2648     int can1, can2, inv1, inv2;
2649     int diff = DIFF_MAX;
2650     enum dline_desc dd;
2651
2652     FORALL_SQUARES(state, i, j) {
2653         if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2654             continue;
2655
2656         switch (CLUE_AT(state, i, j)) {
2657             case -1:
2658                 continue;
2659
2660             case 1:
2661                 if (square_setall_identical(sstate, i, j, LINE_NO)) 
2662                     diff = min(diff, DIFF_EASY);
2663                 break;
2664             case 3:
2665                 if (square_setall_identical(sstate, i, j, LINE_YES))
2666                     diff = min(diff, DIFF_EASY);
2667                 break;
2668         }
2669
2670         if (SQUARE_YES_COUNT(sstate, i, j) + 
2671             SQUARE_NO_COUNT(sstate, i, j) == 2) {
2672             /* There are exactly two unknown lines bordering this
2673              * square. */
2674             if (SQUARE_YES_COUNT(sstate, i, j) + 1 == 
2675                 CLUE_AT(state, i, j)) {
2676                 /* They must be different */
2677                 if (square_relate_2_unknowns(sstate, i, j, TRUE))
2678                     diff = min(diff, DIFF_HARD);
2679             }
2680         }
2681     }
2682
2683     check_caches(sstate);
2684
2685     FORALL_DOTS(state, i, j) {
2686         if (DOT_YES_COUNT(sstate, i, j) == 1 &&
2687             DOT_NO_COUNT(sstate, i, j) == 1) {
2688             if (dot_relate_2_unknowns(sstate, i, j, TRUE))
2689                 diff = min(diff, DIFF_HARD);
2690             continue;
2691         }
2692
2693         if (DOT_YES_COUNT(sstate, i, j) == 0 &&
2694             DOT_NO_COUNT(sstate, i, j) == 2) {
2695             if (dot_relate_2_unknowns(sstate, i, j, FALSE))
2696                 diff = min(diff, DIFF_HARD);
2697             continue;
2698         }
2699     }
2700
2701     /* If two lines into a dot are related, the other two lines into that dot
2702      * are related in the same way. */
2703
2704     /* iter over points that aren't on edges */
2705     for (i = 1; i < w; ++i) {
2706         for (j = 1; j < h; ++j) {
2707             if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2708                 continue;
2709
2710             /* iter over directions */
2711             for (dir1 = 0; dir1 < 4; ++dir1) {
2712                 for (dir2 = dir1+1; dir2 < 4; ++dir2) {
2713                     /* canonify both lines */
2714                     can1 = edsf_canonify
2715                         (sstate->hard->linedsf,
2716                          LINEDSF_INDEX(state, i, j, dir1),
2717                          &inv1);
2718                     can2 = edsf_canonify
2719                         (sstate->hard->linedsf,
2720                          LINEDSF_INDEX(state, i, j, dir2),
2721                          &inv2);
2722                     /* merge opposite lines */
2723                     if (can1 == can2) {
2724                         if (merge_lines(sstate, 
2725                                         i, j, OPP_DIR(dir1),
2726                                         i, j, OPP_DIR(dir2),
2727                                         inv1 ^ inv2)) {
2728                             diff = min(diff, DIFF_HARD);
2729                         }
2730                     }
2731                 }
2732             }
2733         }
2734     }
2735
2736     /* If the state of a line is known, deduce the state of its canonical line
2737      * too. */
2738     FORALL_DOTS(state, i, j) {
2739         /* Do this even if the dot we're on is solved */
2740         if (i < w) {
2741             can1 = edsf_canonify(sstate->hard->linedsf, 
2742                                  LINEDSF_INDEX(state, i, j, RIGHT),
2743                                  &inv1);
2744             linedsf_deindex(state, can1, &a, &b, &dir1);
2745             s = RIGHTOF_DOT(state, i, j);
2746             if (s != LINE_UNKNOWN)
2747             {
2748                 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2749                     diff = min(diff, DIFF_EASY);
2750             }
2751         }
2752         if (j < h) {
2753             can1 = edsf_canonify(sstate->hard->linedsf, 
2754                                  LINEDSF_INDEX(state, i, j, DOWN),
2755                                  &inv1);
2756             linedsf_deindex(state, can1, &a, &b, &dir1);
2757             s = BELOW_DOT(state, i, j);
2758             if (s != LINE_UNKNOWN)
2759             {
2760                 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2761                     diff = min(diff, DIFF_EASY);
2762             }
2763         }
2764     }
2765
2766     /* Interactions between dline and linedsf */
2767     FORALL_DOTS(state, i, j) {
2768         if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2769             continue;
2770
2771         FORALL_DOT_DLINES(dd) {
2772             const struct dline dll = dlines[dd], *dl = &dll;
2773             if (i == 0 && (dl->dir1 == LEFT || dl->dir2 == LEFT))
2774                 continue;
2775             if (i == w && (dl->dir1 == RIGHT || dl->dir2 == RIGHT))
2776                 continue;
2777             if (j == 0 && (dl->dir1 == UP || dl->dir2 == UP))
2778                 continue;
2779             if (j == h && (dl->dir1 == DOWN || dl->dir2 == DOWN))
2780                 continue;
2781
2782             if (get_dot_dline(state, sstate->normal->dot_atleastone,
2783                               i, j, dd) &&
2784                 get_dot_dline(state, sstate->normal->dot_atmostone,
2785                               i, j, dd)) {
2786                 /* atleastone && atmostone => inverse */
2787                 if (merge_lines(sstate, i, j, dl->dir1, i, j, dl->dir2, 1)) {
2788                     diff = min(diff, DIFF_HARD);
2789                 }
2790             } else {
2791                 /* don't have atleastone and atmostone for this dline */
2792                 can1 = edsf_canonify(sstate->hard->linedsf,
2793                                      LINEDSF_INDEX(state, i, j, dl->dir1),
2794                                      &inv1);
2795                 can2 = edsf_canonify(sstate->hard->linedsf,
2796                                      LINEDSF_INDEX(state, i, j, dl->dir2),
2797                                      &inv2);
2798                 if (can1 == can2) {
2799                     if (inv1 == inv2) {
2800                         /* identical => collapse dline */
2801                         if (get_dot_dline(state, 
2802                                           sstate->normal->dot_atleastone,
2803                                           i, j, dd)) {
2804                             if (set_line_bydot(sstate, i, j, 
2805                                                dl->dir1, LINE_YES)) {
2806                                 diff = min(diff, DIFF_EASY);
2807                             }
2808                             if (set_line_bydot(sstate, i, j, 
2809                                                dl->dir2, LINE_YES)) {
2810                                 diff = min(diff, DIFF_EASY);
2811                             }
2812                         } else if (get_dot_dline(state, 
2813                                                  sstate->normal->dot_atmostone,
2814                                                  i, j, dd)) {
2815                             if (set_line_bydot(sstate, i, j, 
2816                                                dl->dir1, LINE_NO)) {
2817                                 diff = min(diff, DIFF_EASY);
2818                             }
2819                             if (set_line_bydot(sstate, i, j, 
2820                                                dl->dir2, LINE_NO)) {
2821                                 diff = min(diff, DIFF_EASY);
2822                             }
2823                         }
2824                     } else {
2825                         /* inverse => atleastone && atmostone */
2826                         if (set_dot_dline(state, 
2827                                           sstate->normal->dot_atleastone,
2828                                           i, j, dd)) {
2829                             diff = min(diff, DIFF_NORMAL);
2830                         }
2831                         if (set_dot_dline(state, 
2832                                           sstate->normal->dot_atmostone,
2833                                           i, j, dd)) {
2834                             diff = min(diff, DIFF_NORMAL);
2835                         }
2836                     }
2837                 }
2838             }
2839         }
2840     }
2841     
2842     /* If the state of the canonical line for line 'l' is known, deduce the
2843      * state of 'l' */
2844     FORALL_DOTS(state, i, j) {
2845         if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2846             continue;
2847
2848         if (i < w) {
2849             can1 = edsf_canonify(sstate->hard->linedsf, 
2850                                  LINEDSF_INDEX(state, i, j, RIGHT),
2851                                  &inv1);
2852             linedsf_deindex(state, can1, &a, &b, &dir1);
2853             s = get_line_status_from_point(state, a, b, dir1);
2854             if (s != LINE_UNKNOWN)
2855             {
2856                 if (set_line_bydot(sstate, i, j, RIGHT, inv1 ? OPP(s) : s))
2857                     diff = min(diff, DIFF_EASY);
2858             }
2859         }
2860         if (j < h) {
2861             can1 = edsf_canonify(sstate->hard->linedsf, 
2862                                  LINEDSF_INDEX(state, i, j, DOWN),
2863                                  &inv1);
2864             linedsf_deindex(state, can1, &a, &b, &dir1);
2865             s = get_line_status_from_point(state, a, b, dir1);
2866             if (s != LINE_UNKNOWN)
2867             {
2868                 if (set_line_bydot(sstate, i, j, DOWN, inv1 ? OPP(s) : s))
2869                     diff = min(diff, DIFF_EASY);
2870             }
2871         }
2872     }
2873
2874     return diff;
2875 }
2876
2877 static int loop_deductions(solver_state *sstate)
2878 {
2879     int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2880     game_state *state = sstate->state;
2881     int shortest_chainlen = DOT_COUNT(state);
2882     int loop_found = FALSE;
2883     int d;
2884     int dots_connected;
2885     int progress = FALSE;
2886     int i, j;
2887
2888     /*
2889      * Go through the grid and update for all the new edges.
2890      * Since merge_dots() is idempotent, the simplest way to
2891      * do this is just to update for _all_ the edges.
2892      * 
2893      * Also, while we're here, we count the edges, count the
2894      * clues, count the satisfied clues, and count the
2895      * satisfied-minus-one clues.
2896      */
2897     FORALL_DOTS(state, i, j) {
2898         if (RIGHTOF_DOT(state, i, j) == LINE_YES) {
2899             loop_found |= merge_dots(sstate, i, j, i+1, j);
2900             edgecount++;
2901         }
2902         if (BELOW_DOT(state, i, j) == LINE_YES) {
2903             loop_found |= merge_dots(sstate, i, j, i, j+1);
2904             edgecount++;
2905         }
2906
2907         if (CLUE_AT(state, i, j) >= 0) {
2908             int c = CLUE_AT(state, i, j);
2909             int o = SQUARE_YES_COUNT(sstate, i, j);
2910             if (o == c)
2911                 satclues++;
2912             else if (o == c-1)
2913                 sm1clues++;
2914             clues++;
2915         }
2916     }
2917
2918     for (i = 0; i < DOT_COUNT(state); ++i) {
2919         dots_connected = 
2920             sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2921         if (dots_connected > 1)
2922             shortest_chainlen = min(shortest_chainlen, dots_connected);
2923     }
2924
2925     assert(sstate->solver_status == SOLVER_INCOMPLETE);
2926
2927     if (satclues == clues && shortest_chainlen == edgecount) {
2928         sstate->solver_status = SOLVER_SOLVED;
2929         /* This discovery clearly counts as progress, even if we haven't
2930          * just added any lines or anything */
2931         progress = TRUE; 
2932         goto finished_loop_deductionsing;
2933     }
2934
2935     /*
2936      * Now go through looking for LINE_UNKNOWN edges which
2937      * connect two dots that are already in the same
2938      * equivalence class. If we find one, test to see if the
2939      * loop it would create is a solution.
2940      */
2941     FORALL_DOTS(state, i, j) {
2942         for (d = 0; d < 2; d++) {
2943             int i2, j2, eqclass, val;
2944
2945             if (d == 0) {
2946                 if (RIGHTOF_DOT(state, i, j) !=
2947                         LINE_UNKNOWN)
2948                     continue;
2949                 i2 = i+1;
2950                 j2 = j;
2951             } else {
2952                 if (BELOW_DOT(state, i, j) !=
2953                     LINE_UNKNOWN) {
2954                     continue;
2955                 }
2956                 i2 = i;
2957                 j2 = j+1;
2958             }
2959
2960             eqclass = dsf_canonify(sstate->dotdsf, j * (state->w+1) + i);
2961             if (eqclass != dsf_canonify(sstate->dotdsf,
2962                                         j2 * (state->w+1) + i2)) {
2963                 continue;
2964             }
2965
2966             val = LINE_NO;  /* loop is bad until proven otherwise */
2967
2968             /*
2969              * This edge would form a loop. Next
2970              * question: how long would the loop be?
2971              * Would it equal the total number of edges
2972              * (plus the one we'd be adding if we added
2973              * it)?
2974              */
2975             if (sstate->looplen[eqclass] == edgecount + 1) {
2976                 int sm1_nearby;
2977                 int cx, cy;
2978
2979                 /*
2980                  * This edge would form a loop which
2981                  * took in all the edges in the entire
2982                  * grid. So now we need to work out
2983                  * whether it would be a valid solution
2984                  * to the puzzle, which means we have to
2985                  * check if it satisfies all the clues.
2986                  * This means that every clue must be
2987                  * either satisfied or satisfied-minus-
2988                  * 1, and also that the number of
2989                  * satisfied-minus-1 clues must be at
2990                  * most two and they must lie on either
2991                  * side of this edge.
2992                  */
2993                 sm1_nearby = 0;
2994                 cx = i - (j2-j);
2995                 cy = j - (i2-i);
2996                 if (CLUE_AT(state, cx,cy) >= 0 &&
2997                         square_order(state, cx,cy, LINE_YES) ==
2998                         CLUE_AT(state, cx,cy) - 1) {
2999                     sm1_nearby++;
3000                 }
3001                 if (CLUE_AT(state, i, j) >= 0 &&
3002                         SQUARE_YES_COUNT(sstate, i, j) ==
3003                         CLUE_AT(state, i, j) - 1) {
3004                     sm1_nearby++;
3005                 }
3006                 if (sm1clues == sm1_nearby &&
3007                     sm1clues + satclues == clues) {
3008                     val = LINE_YES;  /* loop is good! */
3009                 }
3010             }
3011
3012             /*
3013              * Right. Now we know that adding this edge
3014              * would form a loop, and we know whether
3015              * that loop would be a viable solution or
3016              * not.
3017              * 
3018              * If adding this edge produces a solution,
3019              * then we know we've found _a_ solution but
3020              * we don't know that it's _the_ solution -
3021              * if it were provably the solution then
3022              * we'd have deduced this edge some time ago
3023              * without the need to do loop detection. So
3024              * in this state we return SOLVER_AMBIGUOUS,
3025              * which has the effect that hitting Solve
3026              * on a user-provided puzzle will fill in a
3027              * solution but using the solver to
3028              * construct new puzzles won't consider this
3029              * a reasonable deduction for the user to
3030              * make.
3031              */
3032             if (d == 0) {
3033                 progress = set_line_bydot(sstate, i, j, RIGHT, val);
3034                 assert(progress == TRUE);
3035             } else {
3036                 progress = set_line_bydot(sstate, i, j, DOWN, val);
3037                 assert(progress == TRUE);
3038             }
3039             if (val == LINE_YES) {
3040                 sstate->solver_status = SOLVER_AMBIGUOUS;
3041                 goto finished_loop_deductionsing;
3042             }
3043         }
3044     }
3045
3046 finished_loop_deductionsing:
3047     return progress ? DIFF_EASY : DIFF_MAX;
3048 }
3049
3050 /* This will return a dynamically allocated solver_state containing the (more)
3051  * solved grid */
3052 static solver_state *solve_game_rec(const solver_state *sstate_start, 
3053                                     int diff)
3054 {
3055     int i, j;
3056     int w, h;
3057     solver_state *sstate, *sstate_saved, *sstate_tmp;
3058     solver_state *sstate_rec_solved;
3059     int recursive_soln_count;
3060     int solver_progress;
3061     game_state *state;
3062
3063     /* Indicates which solver we should call next.  This is a sensible starting
3064      * point */
3065     int current_solver = DIFF_EASY, next_solver;
3066 #ifdef SHOW_WORKING
3067     char *text;
3068 #endif
3069
3070 #if 0
3071     printf("solve_game_rec: recursion_remaining = %d\n", 
3072            sstate_start->recursion_remaining);
3073 #endif
3074
3075     sstate = dup_solver_state(sstate_start);
3076  
3077     /* Cache the values of some variables for readability */
3078     state = sstate->state;
3079     h = state->h;
3080     w = state->w;
3081
3082     sstate_saved = NULL;
3083
3084 nonrecursive_solver:
3085     solver_progress = FALSE;
3086
3087     check_caches(sstate);
3088
3089     do {
3090 #ifdef SHOW_WORKING
3091         text = game_text_format(state);
3092         fprintf(stderr, "-----------------\n%s", text);
3093         sfree(text);
3094 #endif
3095
3096         if (sstate->solver_status == SOLVER_MISTAKE)
3097             return sstate;
3098
3099 /*        fprintf(stderr, "Invoking solver %d\n", current_solver); */
3100         next_solver = solver_fns[current_solver](sstate);
3101
3102         if (next_solver == DIFF_MAX) {
3103 /*            fprintf(stderr, "Current solver failed\n"); */
3104             if (current_solver < diff && current_solver + 1 < DIFF_MAX) {
3105                 /* Try next beefier solver */
3106                 next_solver = current_solver + 1;
3107             } else {
3108 /*                fprintf(stderr, "Doing loop deductions\n"); */
3109                 next_solver = loop_deductions(sstate);
3110             }
3111         }
3112
3113         if (sstate->solver_status == SOLVER_SOLVED || 
3114             sstate->solver_status == SOLVER_AMBIGUOUS) {
3115 /*            fprintf(stderr, "Solver completed\n"); */
3116             break;
3117         }
3118
3119         /* Once we've looped over all permitted solvers then the loop
3120          * deductions without making any progress, we'll exit this while loop */
3121         current_solver = next_solver;
3122     } while (current_solver < DIFF_MAX);
3123
3124     if (sstate->solver_status == SOLVER_SOLVED ||
3125         sstate->solver_status == SOLVER_AMBIGUOUS) {
3126         /* s/LINE_UNKNOWN/LINE_NO/g */
3127         array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO, 
3128                      HL_COUNT(sstate->state));
3129         array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO, 
3130                      VL_COUNT(sstate->state));
3131         return sstate;
3132     }
3133
3134     /* Perform recursive calls */
3135     if (sstate->recursion_remaining) {
3136         sstate_saved = dup_solver_state(sstate);
3137
3138         sstate->recursion_remaining--;
3139
3140         recursive_soln_count = 0;
3141         sstate_rec_solved = NULL;
3142
3143         /* Memory management: 
3144          * sstate_saved won't be modified but needs to be freed when we have
3145          * finished with it.
3146          * sstate is expected to contain our 'best' solution by the time we
3147          * finish this section of code.  It's the thing we'll try adding lines
3148          * to, seeing if they make it more solvable.
3149          * If sstate_rec_solved is non-NULL, it will supersede sstate
3150          * eventually.  sstate_tmp should not hold a value persistently.
3151          */
3152
3153         /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
3154          * of the possibility of additional solutions.  So as soon as we have a
3155          * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
3156          * if we get a SOLVER_SOLVED we want to keep trying in case we find
3157          * further solutions and have to mark it ambiguous.
3158          */
3159
3160 #define DO_RECURSIVE_CALL(dir_dot) \
3161     if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
3162         debug(("Trying " #dir_dot " at [%d,%d]\n", i, j)); \
3163         LV_##dir_dot(sstate->state, i, j) = LINE_YES; \
3164         sstate_tmp = solve_game_rec(sstate, diff); \
3165         switch (sstate_tmp->solver_status) { \
3166             case SOLVER_AMBIGUOUS: \
3167                 debug(("Solver ambiguous, returning\n")); \
3168                 sstate_rec_solved = sstate_tmp; \
3169                 goto finished_recursion; \
3170             case SOLVER_SOLVED: \
3171                 switch (++recursive_soln_count) { \
3172                     case 1: \
3173                         debug(("One solution found\n")); \
3174                         sstate_rec_solved = sstate_tmp; \
3175                         break; \
3176                     case 2: \
3177                         debug(("Ambiguous solutions found\n")); \
3178                         free_solver_state(sstate_tmp); \
3179                         sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS; \
3180                         goto finished_recursion; \
3181                     default: \
3182                         assert(!"recursive_soln_count out of range"); \
3183                         break; \
3184                 } \
3185                 break; \
3186             case SOLVER_MISTAKE: \
3187                 debug(("Non-solution found\n")); \
3188                 free_solver_state(sstate_tmp); \
3189                 free_solver_state(sstate_saved); \
3190                 LV_##dir_dot(sstate->state, i, j) = LINE_NO; \
3191                 goto nonrecursive_solver; \
3192             case SOLVER_INCOMPLETE: \
3193                 debug(("Recursive step inconclusive\n")); \
3194                 free_solver_state(sstate_tmp); \
3195                 break; \
3196         } \
3197         free_solver_state(sstate); \
3198         sstate = dup_solver_state(sstate_saved); \
3199     }
3200        
3201        FORALL_DOTS(state, i, j) {
3202            /* Only perform recursive calls on 'loose ends' */
3203            if (DOT_YES_COUNT(sstate, i, j) == 1) {
3204                DO_RECURSIVE_CALL(LEFTOF_DOT);
3205                DO_RECURSIVE_CALL(RIGHTOF_DOT);
3206                DO_RECURSIVE_CALL(ABOVE_DOT);
3207                DO_RECURSIVE_CALL(BELOW_DOT);
3208            }
3209        }
3210
3211 finished_recursion:
3212
3213        if (sstate_rec_solved) {
3214            free_solver_state(sstate);
3215            sstate = sstate_rec_solved;
3216        } 
3217     }
3218
3219     return sstate;
3220 }
3221
3222 #if 0
3223 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
3224                if (sstate->normal->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] & \
3225                    1<<dline) { \
3226                    if (square_order(sstate->state, i, j,  LINE_UNKNOWN) - 1 == \
3227                        CLUE_AT(sstate->state, i, j) - '0') { \
3228                        square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
3229                            /* XXX the following may overwrite known data! */ \
3230                        dir1_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3231                        dir2_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3232                    } \
3233                }
3234                SQUARE_DLINES;
3235 #undef HANDLE_DLINE
3236 #endif
3237
3238 static char *solve_game(game_state *state, game_state *currstate,
3239                         char *aux, char **error)
3240 {
3241     char *soln = NULL;
3242     solver_state *sstate, *new_sstate;
3243
3244     sstate = new_solver_state(state, DIFF_MAX);
3245     new_sstate = solve_game_rec(sstate, DIFF_MAX);
3246
3247     if (new_sstate->solver_status == SOLVER_SOLVED) {
3248         soln = encode_solve_move(new_sstate->state);
3249     } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
3250         soln = encode_solve_move(new_sstate->state);
3251         /**error = "Solver found ambiguous solutions"; */
3252     } else {
3253         soln = encode_solve_move(new_sstate->state);
3254         /**error = "Solver failed"; */
3255     }
3256
3257     free_solver_state(new_sstate);
3258     free_solver_state(sstate);
3259
3260     return soln;
3261 }
3262
3263 /* ----------------------------------------------------------------------
3264  * Drawing and mouse-handling
3265  */
3266
3267 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3268                             int x, int y, int button)
3269 {
3270     int hl_selected;
3271     int i, j, p, q; 
3272     char *ret, buf[80];
3273     char button_char = ' ';
3274     enum line_state old_state;
3275
3276     button &= ~MOD_MASK;
3277
3278     /* Around each line is a diamond-shaped region where points within that
3279      * region are closer to this line than any other.  We assume any click
3280      * within a line's diamond was meant for that line.  It would all be a lot
3281      * simpler if the / and % operators respected modulo arithmetic properly
3282      * for negative numbers. */
3283     
3284     x -= BORDER;
3285     y -= BORDER;
3286
3287     /* Get the coordinates of the square the click was in */
3288     i = (x + TILE_SIZE) / TILE_SIZE - 1; 
3289     j = (y + TILE_SIZE) / TILE_SIZE - 1;
3290
3291     /* Get the precise position inside square [i,j] */
3292     p = (x + TILE_SIZE) % TILE_SIZE;
3293     q = (y + TILE_SIZE) % TILE_SIZE;
3294
3295     /* After this bit of magic [i,j] will correspond to the point either above
3296      * or to the left of the line selected */
3297     if (p > q) { 
3298         if (TILE_SIZE - p > q) {
3299             hl_selected = TRUE;
3300         } else {
3301             hl_selected = FALSE;
3302             ++i;
3303         }
3304     } else {
3305         if (TILE_SIZE - q > p) {
3306             hl_selected = FALSE;
3307         } else {
3308             hl_selected = TRUE;
3309             ++j;
3310         }
3311     }
3312
3313     if (i < 0 || j < 0)
3314         return NULL;
3315
3316     if (hl_selected) {
3317         if (i >= state->w || j >= state->h + 1)
3318             return NULL;
3319     } else { 
3320         if (i >= state->w + 1 || j >= state->h)
3321             return NULL;
3322     }
3323
3324     /* I think it's only possible to play this game with mouse clicks, sorry */
3325     /* Maybe will add mouse drag support some time */
3326     if (hl_selected)
3327         old_state = RIGHTOF_DOT(state, i, j);
3328     else
3329         old_state = BELOW_DOT(state, i, j);
3330
3331     switch (button) {
3332         case LEFT_BUTTON:
3333             switch (old_state) {
3334                 case LINE_UNKNOWN:
3335                     button_char = 'y';
3336                     break;
3337                 case LINE_YES:
3338                 case LINE_NO:
3339                     button_char = 'u';
3340                     break;
3341             }
3342             break;
3343         case MIDDLE_BUTTON:
3344             button_char = 'u';
3345             break;
3346         case RIGHT_BUTTON:
3347             switch (old_state) {
3348                 case LINE_UNKNOWN:
3349                     button_char = 'n';
3350                     break;
3351                 case LINE_NO:
3352                 case LINE_YES:
3353                     button_char = 'u';
3354                     break;
3355             }
3356             break;
3357         default:
3358             return NULL;
3359     }
3360
3361
3362     sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
3363     ret = dupstr(buf);
3364
3365     return ret;
3366 }
3367
3368 static game_state *execute_move(game_state *state, char *move)
3369 {
3370     int i, j;
3371     game_state *newstate = dup_game(state);
3372
3373     if (move[0] == 'S') {
3374         move++;
3375         newstate->cheated = TRUE;
3376     }
3377
3378     while (*move) {
3379         i = atoi(move);
3380         move = strchr(move, ',');
3381         if (!move)
3382             goto fail;
3383         j = atoi(++move);
3384         move += strspn(move, "1234567890");
3385         switch (*(move++)) {
3386             case 'h':
3387                 if (i >= newstate->w || j > newstate->h)
3388                     goto fail;
3389                 switch (*(move++)) {
3390                     case 'y':
3391                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
3392                         break;
3393                     case 'n':
3394                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
3395                         break;
3396                     case 'u':
3397                         LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
3398                         break;
3399                     default:
3400                         goto fail;
3401                 }
3402                 break;
3403             case 'v':
3404                 if (i > newstate->w || j >= newstate->h)
3405                     goto fail;
3406                 switch (*(move++)) {
3407                     case 'y':
3408                         LV_BELOW_DOT(newstate, i, j) = LINE_YES;
3409                         break;
3410                     case 'n':
3411                         LV_BELOW_DOT(newstate, i, j) = LINE_NO;
3412                         break;
3413                     case 'u':
3414                         LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
3415                         break;
3416                     default:
3417                         goto fail;
3418                 }
3419                 break;
3420             default:
3421                 goto fail;
3422         }
3423     }
3424
3425     /*
3426      * Check for completion.
3427      */
3428     i = 0;                   /* placate optimiser */
3429     for (j = 0; j <= newstate->h; j++) {
3430         for (i = 0; i < newstate->w; i++)
3431             if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
3432                 break;
3433         if (i < newstate->w)
3434             break;
3435     }
3436     if (j <= newstate->h) {
3437         int prevdir = 'R';
3438         int x = i, y = j;
3439         int looplen, count;
3440
3441         /*
3442          * We've found a horizontal edge at (i,j). Follow it round
3443          * to see if it's part of a loop.
3444          */
3445         looplen = 0;
3446         while (1) {
3447             int order = dot_order(newstate, x, y, LINE_YES);
3448             if (order != 2)
3449                 goto completion_check_done;
3450
3451             if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
3452                 x--;
3453                 prevdir = 'R';
3454             } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
3455                        prevdir != 'R') {
3456                 x++;
3457                 prevdir = 'L';
3458             } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
3459                        prevdir != 'U') {
3460                 y--;
3461                 prevdir = 'D';
3462             } else if (BELOW_DOT(newstate, x, y) == LINE_YES && 
3463                        prevdir != 'D') {
3464                 y++;
3465                 prevdir = 'U';
3466             } else {
3467                 assert(!"Can't happen");   /* dot_order guarantees success */
3468             }
3469
3470             looplen++;
3471
3472             if (x == i && y == j)
3473                 break;
3474         }
3475
3476         if (x != i || y != j || looplen == 0)
3477             goto completion_check_done;
3478
3479         /*
3480          * We've traced our way round a loop, and we know how many
3481          * line segments were involved. Count _all_ the line
3482          * segments in the grid, to see if the loop includes them
3483          * all.
3484          */
3485         count = 0;
3486         FORALL_DOTS(newstate, i, j) {
3487             count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
3488                       (BELOW_DOT(newstate, i, j) == LINE_YES));
3489         }
3490         assert(count >= looplen);
3491         if (count != looplen)
3492             goto completion_check_done;
3493
3494         /*
3495          * The grid contains one closed loop and nothing else.
3496          * Check that all the clues are satisfied.
3497          */
3498         FORALL_SQUARES(newstate, i, j) {
3499             if (CLUE_AT(newstate, i, j) >= 0) {
3500                 if (square_order(newstate, i, j, LINE_YES) != 
3501                     CLUE_AT(newstate, i, j)) {
3502                     goto completion_check_done;
3503                 }
3504             }
3505         }
3506
3507         /*
3508          * Completed!
3509          */
3510         newstate->solved = TRUE;
3511     }
3512
3513 completion_check_done:
3514     return newstate;
3515
3516 fail:
3517     free_game(newstate);
3518     return NULL;
3519 }
3520
3521 /* ----------------------------------------------------------------------
3522  * Drawing routines.
3523  */
3524 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3525                         game_state *state, int dir, game_ui *ui,
3526                         float animtime, float flashtime)
3527 {
3528     int i, j, n;
3529     char c[2];
3530     int line_colour, flash_changed;
3531     int clue_mistake;
3532
3533     if (!ds->started) {
3534         /*
3535          * The initial contents of the window are not guaranteed and
3536          * can vary with front ends. To be on the safe side, all games
3537          * should start by drawing a big background-colour rectangle
3538          * covering the whole window.
3539          */
3540         draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
3541
3542         /* Draw dots */
3543         FORALL_DOTS(state, i, j) {
3544             draw_rect(dr, 
3545                       BORDER + i * TILE_SIZE - LINEWIDTH/2,
3546                       BORDER + j * TILE_SIZE - LINEWIDTH/2,
3547                       LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
3548         }
3549
3550         /* Draw clues */
3551         FORALL_SQUARES(state, i, j) {
3552             c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3553             c[1] = '\0';
3554             draw_text(dr, 
3555                       BORDER + i * TILE_SIZE + TILE_SIZE/2,
3556                       BORDER + j * TILE_SIZE + TILE_SIZE/2,
3557                       FONT_VARIABLE, TILE_SIZE/2, 
3558                       ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
3559         }
3560         draw_update(dr, 0, 0,
3561                     state->w * TILE_SIZE + 2*BORDER + 1,
3562                     state->h * TILE_SIZE + 2*BORDER + 1);
3563         ds->started = TRUE;
3564     }
3565
3566     if (flashtime > 0 && 
3567         (flashtime <= FLASH_TIME/3 ||
3568          flashtime >= FLASH_TIME*2/3)) {
3569         flash_changed = !ds->flashing;
3570         ds->flashing = TRUE;
3571         line_colour = COL_HIGHLIGHT;
3572     } else {
3573         flash_changed = ds->flashing;
3574         ds->flashing = FALSE;
3575         line_colour = COL_FOREGROUND;
3576     }
3577
3578 #define CROSS_SIZE (3 * LINEWIDTH / 2)
3579     
3580     /* Redraw clue colours if necessary */
3581     FORALL_SQUARES(state, i, j) {
3582         n = CLUE_AT(state, i, j);
3583         if (n < 0)
3584             continue;
3585
3586         assert(n >= 0 && n <= 4);
3587
3588         c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3589         c[1] = '\0';
3590
3591         clue_mistake = (square_order(state, i, j, LINE_YES) > n ||
3592                         square_order(state, i, j, LINE_NO ) > (4-n));
3593
3594         if (clue_mistake != ds->clue_error[SQUARE_INDEX(state, i, j)]) {
3595             draw_rect(dr, 
3596                       BORDER + i * TILE_SIZE + CROSS_SIZE,
3597                       BORDER + j * TILE_SIZE + CROSS_SIZE,
3598                       TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
3599                       COL_BACKGROUND);
3600             draw_text(dr, 
3601                       BORDER + i * TILE_SIZE + TILE_SIZE/2,
3602                       BORDER + j * TILE_SIZE + TILE_SIZE/2,
3603                       FONT_VARIABLE, TILE_SIZE/2, 
3604                       ALIGN_VCENTRE | ALIGN_HCENTRE, 
3605                       clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
3606             draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
3607                         TILE_SIZE, TILE_SIZE);
3608
3609             ds->clue_error[SQUARE_INDEX(state, i, j)] = clue_mistake;
3610         }
3611     }
3612
3613     /* I've also had a request to colour lines red if they make a non-solution
3614      * loop, or if more than two lines go into any point.  I think that would
3615      * be good some time. */
3616
3617 #define CLEAR_VL(i, j) \
3618     do { \
3619        draw_rect(dr, \
3620                  BORDER + i * TILE_SIZE - CROSS_SIZE, \
3621                  BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3622                  CROSS_SIZE * 2, \
3623                  TILE_SIZE - LINEWIDTH, \
3624                  COL_BACKGROUND); \
3625         draw_update(dr, \
3626                     BORDER + i * TILE_SIZE - CROSS_SIZE, \
3627                     BORDER + j * TILE_SIZE - CROSS_SIZE, \
3628                     CROSS_SIZE*2, \
3629                     TILE_SIZE + CROSS_SIZE*2); \
3630     } while (0)
3631
3632 #define CLEAR_HL(i, j) \
3633     do { \
3634        draw_rect(dr, \
3635                  BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3636                  BORDER + j * TILE_SIZE - CROSS_SIZE, \
3637                  TILE_SIZE - LINEWIDTH, \
3638                  CROSS_SIZE * 2, \
3639                  COL_BACKGROUND); \
3640        draw_update(dr, \
3641                    BORDER + i * TILE_SIZE - CROSS_SIZE, \
3642                    BORDER + j * TILE_SIZE - CROSS_SIZE, \
3643                    TILE_SIZE + CROSS_SIZE*2, \
3644                    CROSS_SIZE*2); \
3645     } while (0)
3646
3647     /* Vertical lines */
3648     FORALL_VL(state, i, j) {
3649         switch (BELOW_DOT(state, i, j)) {
3650             case LINE_UNKNOWN:
3651                 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3652                     CLEAR_VL(i, j);
3653                 }
3654                 break;
3655             case LINE_YES:
3656                 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j) ||
3657                     flash_changed) {
3658                     CLEAR_VL(i, j);
3659                     draw_rect(dr,
3660                               BORDER + i * TILE_SIZE - LINEWIDTH/2,
3661                               BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3662                               LINEWIDTH, TILE_SIZE - LINEWIDTH, 
3663                               line_colour);
3664                 }
3665                 break;
3666             case LINE_NO:
3667                 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3668                     CLEAR_VL(i, j);
3669                     draw_line(dr,
3670                               BORDER + i * TILE_SIZE - CROSS_SIZE,
3671                               BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3672                               BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3673                               BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3674                               COL_FOREGROUND);
3675                     draw_line(dr,
3676                               BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3677                               BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3678                               BORDER + i * TILE_SIZE - CROSS_SIZE,
3679                               BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3680                               COL_FOREGROUND);
3681                 }
3682                 break;
3683         }
3684         ds->vl[VL_INDEX(state, i, j)] = BELOW_DOT(state, i, j);
3685     }
3686
3687     /* Horizontal lines */
3688     FORALL_HL(state, i, j) {
3689         switch (RIGHTOF_DOT(state, i, j)) {
3690             case LINE_UNKNOWN:
3691                 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3692                     CLEAR_HL(i, j);
3693                 }
3694                 break;
3695             case LINE_YES:
3696                 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j) ||
3697                     flash_changed) {
3698                     CLEAR_HL(i, j);
3699                     draw_rect(dr,
3700                               BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3701                               BORDER + j * TILE_SIZE - LINEWIDTH/2,
3702                               TILE_SIZE - LINEWIDTH, LINEWIDTH, 
3703                               line_colour);
3704                 }
3705                 break; 
3706             case LINE_NO:
3707                 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3708                     CLEAR_HL(i, j);
3709                     draw_line(dr,
3710                               BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3711                               BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3712                               BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3713                               BORDER + j * TILE_SIZE - CROSS_SIZE,
3714                               COL_FOREGROUND);
3715                     draw_line(dr,
3716                               BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3717                               BORDER + j * TILE_SIZE - CROSS_SIZE,
3718                               BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3719                               BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3720                               COL_FOREGROUND);
3721                     break;
3722                 }
3723         }
3724         ds->hl[HL_INDEX(state, i, j)] = RIGHTOF_DOT(state, i, j);
3725     }
3726 }
3727
3728 static float game_flash_length(game_state *oldstate, game_state *newstate,
3729                                int dir, game_ui *ui)
3730 {
3731     if (!oldstate->solved  &&  newstate->solved &&
3732         !oldstate->cheated && !newstate->cheated) {
3733         return FLASH_TIME;
3734     }
3735
3736     return 0.0F;
3737 }
3738
3739 static void game_print_size(game_params *params, float *x, float *y)
3740 {
3741     int pw, ph;
3742
3743     /*
3744      * I'll use 7mm squares by default.
3745      */
3746     game_compute_size(params, 700, &pw, &ph);
3747     *x = pw / 100.0F;
3748     *y = ph / 100.0F;
3749 }
3750
3751 static void game_print(drawing *dr, game_state *state, int tilesize)
3752 {
3753     int ink = print_mono_colour(dr, 0);
3754     int x, y;
3755     game_drawstate ads, *ds = &ads;
3756
3757     game_set_size(dr, ds, NULL, tilesize);
3758
3759     /*
3760      * Dots. I'll deliberately make the dots a bit wider than the
3761      * lines, so you can still see them. (And also because it's
3762      * annoyingly tricky to make them _exactly_ the same size...)
3763      */
3764     FORALL_DOTS(state, x, y) {
3765         draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
3766                     LINEWIDTH, ink, ink);
3767     }
3768
3769     /*
3770      * Clues.
3771      */
3772     FORALL_SQUARES(state, x, y) {
3773         if (CLUE_AT(state, x, y) >= 0) {
3774             char c[2];
3775
3776             c[0] = CLUE2CHAR(CLUE_AT(state, x, y));
3777             c[1] = '\0';
3778             draw_text(dr, 
3779                       BORDER + x * TILE_SIZE + TILE_SIZE/2,
3780                       BORDER + y * TILE_SIZE + TILE_SIZE/2,
3781                       FONT_VARIABLE, TILE_SIZE/2, 
3782                       ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3783         }
3784     }
3785
3786     /*
3787      * Lines. (At the moment, I'm not bothering with crosses.)
3788      */
3789     FORALL_HL(state, x, y) {
3790         if (RIGHTOF_DOT(state, x, y) == LINE_YES)
3791         draw_rect(dr, BORDER + x * TILE_SIZE,
3792                   BORDER + y * TILE_SIZE - LINEWIDTH/2,
3793                   TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
3794     }
3795
3796     FORALL_VL(state, x, y) {
3797         if (BELOW_DOT(state, x, y) == LINE_YES)
3798         draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
3799                   BORDER + y * TILE_SIZE,
3800                   (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
3801     }
3802 }
3803
3804 #ifdef COMBINED
3805 #define thegame loopy
3806 #endif
3807
3808 const struct game thegame = {
3809     "Loopy", "games.loopy", "loopy",
3810     default_params,
3811     game_fetch_preset,
3812     decode_params,
3813     encode_params,
3814     free_params,
3815     dup_params,
3816     TRUE, game_configure, custom_params,
3817     validate_params,
3818     new_game_desc,
3819     validate_desc,
3820     new_game,
3821     dup_game,
3822     free_game,
3823     1, solve_game,
3824     TRUE, game_text_format,
3825     new_ui,
3826     free_ui,
3827     encode_ui,
3828     decode_ui,
3829     game_changed_state,
3830     interpret_move,
3831     execute_move,
3832     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3833     game_colours,
3834     game_new_drawstate,
3835     game_free_drawstate,
3836     game_redraw,
3837     game_anim_length,
3838     game_flash_length,
3839     TRUE, FALSE, game_print_size, game_print,
3840     FALSE /* wants_statusbar */,
3841     FALSE, game_timing_state,
3842     0,                                       /* mouse_priorities */
3843 };