chiark / gitweb /
Substantial reworking of Solo so that it implements both Sudoku-X
[sgt-puzzles.git] / solo.c
1 /*
2  * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3  *
4  * TODO:
5  *
6  *  - Jigsaw Sudoku is currently an undocumented feature enabled
7  *    by setting r (`Rows of sub-blocks' in the GUI configurer) to
8  *    1. The reason it's undocumented is because they're rather
9  *    erratic to generate, because gridgen tends to hang up for
10  *    ages. I think this is because some jigsaw block layouts
11  *    simply do not admit very many valid filled grids (and
12  *    perhaps some have none at all).
13  *     + To fix this, I think probably the solution is a change in
14  *       grid generation policy: gridgen needs to have less of an
15  *       all-or-nothing attitude and instead make only a limited
16  *       amount of effort to construct a filled grid before giving
17  *       up and trying a new layout. (Come to think of it, this
18  *       same change might also make 5x5 standard Sudoku more
19  *       practical to generate, if correctly tuned.)
20  *     + If I get this fixed, other work needed on jigsaw mode is:
21  *        * introduce a GUI config checkbox. game_configure()
22  *          ticks this box iff r==1; if it's ticked in a call to
23  *          custom_params(), we replace (c, r) with (c*r, 1).
24  *        * document it.
25  *
26  *  - reports from users are that `Trivial'-mode puzzles are still
27  *    rather hard compared to newspapers' easy ones, so some better
28  *    low-end difficulty grading would be nice
29  *     + it's possible that really easy puzzles always have
30  *       _several_ things you can do, so don't make you hunt too
31  *       hard for the one deduction you can currently make
32  *     + it's also possible that easy puzzles require fewer
33  *       cross-eliminations: perhaps there's a higher incidence of
34  *       things you can deduce by looking only at (say) rows,
35  *       rather than things you have to check both rows and columns
36  *       for
37  *     + but really, what I need to do is find some really easy
38  *       puzzles and _play_ them, to see what's actually easy about
39  *       them
40  *     + while I'm revamping this area, filling in the _last_
41  *       number in a nearly-full row or column should certainly be
42  *       permitted even at the lowest difficulty level.
43  *     + also Owen noticed that `Basic' grids requiring numeric
44  *       elimination are actually very hard, so I wonder if a
45  *       difficulty gradation between that and positional-
46  *       elimination-only might be in order
47  *     + but it's not good to have _too_ many difficulty levels, or
48  *       it'll take too long to randomly generate a given level.
49  * 
50  *  - it might still be nice to do some prioritisation on the
51  *    removal of numbers from the grid
52  *     + one possibility is to try to minimise the maximum number
53  *       of filled squares in any block, which in particular ought
54  *       to enforce never leaving a completely filled block in the
55  *       puzzle as presented.
56  *
57  *  - alternative interface modes
58  *     + sudoku.com's Windows program has a palette of possible
59  *       entries; you select a palette entry first and then click
60  *       on the square you want it to go in, thus enabling
61  *       mouse-only play. Useful for PDAs! I don't think it's
62  *       actually incompatible with the current highlight-then-type
63  *       approach: you _either_ highlight a palette entry and then
64  *       click, _or_ you highlight a square and then type. At most
65  *       one thing is ever highlighted at a time, so there's no way
66  *       to confuse the two.
67  *     + then again, I don't actually like sudoku.com's interface;
68  *       it's too much like a paint package whereas I prefer to
69  *       think of Solo as a text editor.
70  *     + another PDA-friendly possibility is a drag interface:
71  *       _drag_ numbers from the palette into the grid squares.
72  *       Thought experiments suggest I'd prefer that to the
73  *       sudoku.com approach, but I haven't actually tried it.
74  */
75
76 /*
77  * Solo puzzles need to be square overall (since each row and each
78  * column must contain one of every digit), but they need not be
79  * subdivided the same way internally. I am going to adopt a
80  * convention whereby I _always_ refer to `r' as the number of rows
81  * of _big_ divisions, and `c' as the number of columns of _big_
82  * divisions. Thus, a 2c by 3r puzzle looks something like this:
83  *
84  *   4 5 1 | 2 6 3
85  *   6 3 2 | 5 4 1
86  *   ------+------     (Of course, you can't subdivide it the other way
87  *   1 4 5 | 6 3 2     or you'll get clashes; observe that the 4 in the
88  *   3 2 6 | 4 1 5     top left would conflict with the 4 in the second
89  *   ------+------     box down on the left-hand side.)
90  *   5 1 4 | 3 2 6
91  *   2 6 3 | 1 5 4
92  *
93  * The need for a strong naming convention should now be clear:
94  * each small box is two rows of digits by three columns, while the
95  * overall puzzle has three rows of small boxes by two columns. So
96  * I will (hopefully) consistently use `r' to denote the number of
97  * rows _of small boxes_ (here 3), which is also the number of
98  * columns of digits in each small box; and `c' vice versa (here
99  * 2).
100  *
101  * I'm also going to choose arbitrarily to list c first wherever
102  * possible: the above is a 2x3 puzzle, not a 3x2 one.
103  */
104
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <assert.h>
109 #include <ctype.h>
110 #include <math.h>
111
112 #ifdef STANDALONE_SOLVER
113 #include <stdarg.h>
114 int solver_show_working, solver_recurse_depth;
115 #endif
116
117 #include "puzzles.h"
118
119 /*
120  * To save space, I store digits internally as unsigned char. This
121  * imposes a hard limit of 255 on the order of the puzzle. Since
122  * even a 5x5 takes unacceptably long to generate, I don't see this
123  * as a serious limitation unless something _really_ impressive
124  * happens in computing technology; but here's a typedef anyway for
125  * general good practice.
126  */
127 typedef unsigned char digit;
128 #define ORDER_MAX 255
129
130 #define PREFERRED_TILE_SIZE 32
131 #define TILE_SIZE (ds->tilesize)
132 #define BORDER (TILE_SIZE / 2)
133 #define GRIDEXTRA (TILE_SIZE / 32)
134
135 #define FLASH_TIME 0.4F
136
137 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
138        SYMM_REF4D, SYMM_REF8 };
139
140 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME,
141        DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
142
143 enum {
144     COL_BACKGROUND,
145     COL_XDIAGONALS,
146     COL_GRID,
147     COL_CLUE,
148     COL_USER,
149     COL_HIGHLIGHT,
150     COL_ERROR,
151     COL_PENCIL,
152     NCOLOURS
153 };
154
155 struct game_params {
156     /*
157      * For a square puzzle, `c' and `r' indicate the puzzle
158      * parameters as described above.
159      * 
160      * A jigsaw-style puzzle is indicated by r==1, in which case c
161      * can be whatever it likes (there is no constraint on
162      * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
163      */
164     int c, r, symm, diff;
165     int xtype;                         /* require all digits in X-diagonals */
166 };
167
168 struct block_structure {
169     int refcount;
170
171     /*
172      * For text formatting, we do need c and r here.
173      */
174     int c, r;
175
176     /*
177      * For any square index, whichblock[i] gives its block index.
178      * 
179      * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
180      * square in block b.
181      * 
182      * whichblock and blocks are each dynamically allocated in
183      * their own right, but the subarrays in blocks are appended
184      * to the whichblock array, so shouldn't be freed
185      * individually.
186      */
187     int *whichblock, **blocks;
188
189 #ifdef STANDALONE_SOLVER
190     /*
191      * Textual descriptions of each block. For normal Sudoku these
192      * are of the form "(1,3)"; for jigsaw they are "starting at
193      * (5,7)". So the sensible usage in both cases is to say
194      * "elimination within block %s" with one of these strings.
195      * 
196      * Only blocknames itself needs individually freeing; it's all
197      * one block.
198      */
199     char **blocknames;
200 #endif
201 };
202
203 struct game_state {
204     /*
205      * For historical reasons, I use `cr' to denote the overall
206      * width/height of the puzzle. It was a natural notation when
207      * all puzzles were divided into blocks in a grid, but doesn't
208      * really make much sense given jigsaw puzzles. However, the
209      * obvious `n' is heavily used in the solver to describe the
210      * index of a number being placed, so `cr' will have to stay.
211      */
212     int cr;
213     struct block_structure *blocks;
214     int xtype;
215     digit *grid;
216     unsigned char *pencil;             /* c*r*c*r elements */
217     unsigned char *immutable;          /* marks which digits are clues */
218     int completed, cheated;
219 };
220
221 static game_params *default_params(void)
222 {
223     game_params *ret = snew(game_params);
224
225     ret->c = ret->r = 3;
226     ret->xtype = FALSE;
227     ret->symm = SYMM_ROT2;             /* a plausible default */
228     ret->diff = DIFF_BLOCK;            /* so is this */
229
230     return ret;
231 }
232
233 static void free_params(game_params *params)
234 {
235     sfree(params);
236 }
237
238 static game_params *dup_params(game_params *params)
239 {
240     game_params *ret = snew(game_params);
241     *ret = *params;                    /* structure copy */
242     return ret;
243 }
244
245 static int game_fetch_preset(int i, char **name, game_params **params)
246 {
247     static struct {
248         char *title;
249         game_params params;
250     } presets[] = {
251         { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, FALSE } },
252         { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
253         { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, FALSE } },
254         { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
255         { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, TRUE } },
256         { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, FALSE } },
257         { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, FALSE } },
258         { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, TRUE } },
259         { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, FALSE } },
260         { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, FALSE } },
261 #ifndef SLOW_SYSTEM
262         { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
263         { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
264 #endif
265     };
266
267     if (i < 0 || i >= lenof(presets))
268         return FALSE;
269
270     *name = dupstr(presets[i].title);
271     *params = dup_params(&presets[i].params);
272
273     return TRUE;
274 }
275
276 static void decode_params(game_params *ret, char const *string)
277 {
278     int seen_r = FALSE;
279
280     ret->c = ret->r = atoi(string);
281     ret->xtype = FALSE;
282     while (*string && isdigit((unsigned char)*string)) string++;
283     if (*string == 'x') {
284         string++;
285         ret->r = atoi(string);
286         seen_r = TRUE;
287         while (*string && isdigit((unsigned char)*string)) string++;
288     }
289     while (*string) {
290         if (*string == 'j') {
291             string++;
292             if (seen_r)
293                 ret->c *= ret->r;
294             ret->r = 1;
295         } else if (*string == 'x') {
296             string++;
297             ret->xtype = TRUE;
298         } else if (*string == 'r' || *string == 'm' || *string == 'a') {
299             int sn, sc, sd;
300             sc = *string++;
301             if (sc == 'm' && *string == 'd') {
302                 sd = TRUE;
303                 string++;
304             } else {
305                 sd = FALSE;
306             }
307             sn = atoi(string);
308             while (*string && isdigit((unsigned char)*string)) string++;
309             if (sc == 'm' && sn == 8)
310                 ret->symm = SYMM_REF8;
311             if (sc == 'm' && sn == 4)
312                 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
313             if (sc == 'm' && sn == 2)
314                 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
315             if (sc == 'r' && sn == 4)
316                 ret->symm = SYMM_ROT4;
317             if (sc == 'r' && sn == 2)
318                 ret->symm = SYMM_ROT2;
319             if (sc == 'a')
320                 ret->symm = SYMM_NONE;
321         } else if (*string == 'd') {
322             string++;
323             if (*string == 't')        /* trivial */
324                 string++, ret->diff = DIFF_BLOCK;
325             else if (*string == 'b')   /* basic */
326                 string++, ret->diff = DIFF_SIMPLE;
327             else if (*string == 'i')   /* intermediate */
328                 string++, ret->diff = DIFF_INTERSECT;
329             else if (*string == 'a')   /* advanced */
330                 string++, ret->diff = DIFF_SET;
331             else if (*string == 'e')   /* extreme */
332                 string++, ret->diff = DIFF_EXTREME;
333             else if (*string == 'u')   /* unreasonable */
334                 string++, ret->diff = DIFF_RECURSIVE;
335         } else
336             string++;                  /* eat unknown character */
337     }
338 }
339
340 static char *encode_params(game_params *params, int full)
341 {
342     char str[80];
343
344     if (params->r > 1)
345         sprintf(str, "%dx%d", params->c, params->r);
346     else
347         sprintf(str, "%dj", params->c);
348     if (params->xtype)
349         strcat(str, "x");
350
351     if (full) {
352         switch (params->symm) {
353           case SYMM_REF8: strcat(str, "m8"); break;
354           case SYMM_REF4: strcat(str, "m4"); break;
355           case SYMM_REF4D: strcat(str, "md4"); break;
356           case SYMM_REF2: strcat(str, "m2"); break;
357           case SYMM_REF2D: strcat(str, "md2"); break;
358           case SYMM_ROT4: strcat(str, "r4"); break;
359           /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
360           case SYMM_NONE: strcat(str, "a"); break;
361         }
362         switch (params->diff) {
363           /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
364           case DIFF_SIMPLE: strcat(str, "db"); break;
365           case DIFF_INTERSECT: strcat(str, "di"); break;
366           case DIFF_SET: strcat(str, "da"); break;
367           case DIFF_EXTREME: strcat(str, "de"); break;
368           case DIFF_RECURSIVE: strcat(str, "du"); break;
369         }
370     }
371     return dupstr(str);
372 }
373
374 static config_item *game_configure(game_params *params)
375 {
376     config_item *ret;
377     char buf[80];
378
379     ret = snewn(6, config_item);
380
381     ret[0].name = "Columns of sub-blocks";
382     ret[0].type = C_STRING;
383     sprintf(buf, "%d", params->c);
384     ret[0].sval = dupstr(buf);
385     ret[0].ival = 0;
386
387     ret[1].name = "Rows of sub-blocks";
388     ret[1].type = C_STRING;
389     sprintf(buf, "%d", params->r);
390     ret[1].sval = dupstr(buf);
391     ret[1].ival = 0;
392
393     ret[2].name = "\"X\" (require every number in each main diagonal)";
394     ret[2].type = C_BOOLEAN;
395     ret[2].sval = NULL;
396     ret[2].ival = params->xtype;
397
398     ret[3].name = "Symmetry";
399     ret[3].type = C_CHOICES;
400     ret[3].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
401         "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
402         "8-way mirror";
403     ret[3].ival = params->symm;
404
405     ret[4].name = "Difficulty";
406     ret[4].type = C_CHOICES;
407     ret[4].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
408     ret[4].ival = params->diff;
409
410     ret[5].name = NULL;
411     ret[5].type = C_END;
412     ret[5].sval = NULL;
413     ret[5].ival = 0;
414
415     return ret;
416 }
417
418 static game_params *custom_params(config_item *cfg)
419 {
420     game_params *ret = snew(game_params);
421
422     ret->c = atoi(cfg[0].sval);
423     ret->r = atoi(cfg[1].sval);
424     ret->xtype = cfg[2].ival;
425     ret->symm = cfg[3].ival;
426     ret->diff = cfg[4].ival;
427
428     return ret;
429 }
430
431 static char *validate_params(game_params *params, int full)
432 {
433     if (params->c < 2)
434         return "Both dimensions must be at least 2";
435     if (params->c > ORDER_MAX || params->r > ORDER_MAX)
436         return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
437     if ((params->c * params->r) > 35)
438         return "Unable to support more than 35 distinct symbols in a puzzle";
439     return NULL;
440 }
441
442 /* ----------------------------------------------------------------------
443  * Solver.
444  * 
445  * This solver is used for two purposes:
446  *  + to check solubility of a grid as we gradually remove numbers
447  *    from it
448  *  + to solve an externally generated puzzle when the user selects
449  *    `Solve'.
450  * 
451  * It supports a variety of specific modes of reasoning. By
452  * enabling or disabling subsets of these modes we can arrange a
453  * range of difficulty levels.
454  */
455
456 /*
457  * Modes of reasoning currently supported:
458  *
459  *  - Positional elimination: a number must go in a particular
460  *    square because all the other empty squares in a given
461  *    row/col/blk are ruled out.
462  *
463  *  - Numeric elimination: a square must have a particular number
464  *    in because all the other numbers that could go in it are
465  *    ruled out.
466  *
467  *  - Intersectional analysis: given two domains which overlap
468  *    (hence one must be a block, and the other can be a row or
469  *    col), if the possible locations for a particular number in
470  *    one of the domains can be narrowed down to the overlap, then
471  *    that number can be ruled out everywhere but the overlap in
472  *    the other domain too.
473  *
474  *  - Set elimination: if there is a subset of the empty squares
475  *    within a domain such that the union of the possible numbers
476  *    in that subset has the same size as the subset itself, then
477  *    those numbers can be ruled out everywhere else in the domain.
478  *    (For example, if there are five empty squares and the
479  *    possible numbers in each are 12, 23, 13, 134 and 1345, then
480  *    the first three empty squares form such a subset: the numbers
481  *    1, 2 and 3 _must_ be in those three squares in some
482  *    permutation, and hence we can deduce none of them can be in
483  *    the fourth or fifth squares.)
484  *     + You can also see this the other way round, concentrating
485  *       on numbers rather than squares: if there is a subset of
486  *       the unplaced numbers within a domain such that the union
487  *       of all their possible positions has the same size as the
488  *       subset itself, then all other numbers can be ruled out for
489  *       those positions. However, it turns out that this is
490  *       exactly equivalent to the first formulation at all times:
491  *       there is a 1-1 correspondence between suitable subsets of
492  *       the unplaced numbers and suitable subsets of the unfilled
493  *       places, found by taking the _complement_ of the union of
494  *       the numbers' possible positions (or the spaces' possible
495  *       contents).
496  * 
497  *  - Forcing chains (see comment for solver_forcing().)
498  * 
499  *  - Recursion. If all else fails, we pick one of the currently
500  *    most constrained empty squares and take a random guess at its
501  *    contents, then continue solving on that basis and see if we
502  *    get any further.
503  */
504
505 struct solver_usage {
506     int cr;
507     struct block_structure *blocks;
508     /*
509      * We set up a cubic array, indexed by x, y and digit; each
510      * element of this array is TRUE or FALSE according to whether
511      * or not that digit _could_ in principle go in that position.
512      *
513      * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
514      * are macros below to help with this.
515      */
516     unsigned char *cube;
517     /*
518      * This is the grid in which we write down our final
519      * deductions. y-coordinates in here are _not_ transformed.
520      */
521     digit *grid;
522     /*
523      * Now we keep track, at a slightly higher level, of what we
524      * have yet to work out, to prevent doing the same deduction
525      * many times.
526      */
527     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
528     unsigned char *row;
529     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
530     unsigned char *col;
531     /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
532     unsigned char *blk;
533     /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
534     unsigned char *diag;               /* diag 0 is \, 1 is / */
535 };
536 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
537 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
538 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
539 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
540
541 #define ondiag0(xy) ((xy) % (cr+1) == 0)
542 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
543 #define diag0(i) ((i) * (cr+1))
544 #define diag1(i) ((i+1) * (cr-1))
545
546 /*
547  * Function called when we are certain that a particular square has
548  * a particular number in it. The y-coordinate passed in here is
549  * transformed.
550  */
551 static void solver_place(struct solver_usage *usage, int x, int y, int n)
552 {
553     int cr = usage->cr;
554     int sqindex = y*cr+x;
555     int i, bi;
556
557     assert(cube(x,y,n));
558
559     /*
560      * Rule out all other numbers in this square.
561      */
562     for (i = 1; i <= cr; i++)
563         if (i != n)
564             cube(x,y,i) = FALSE;
565
566     /*
567      * Rule out this number in all other positions in the row.
568      */
569     for (i = 0; i < cr; i++)
570         if (i != y)
571             cube(x,i,n) = FALSE;
572
573     /*
574      * Rule out this number in all other positions in the column.
575      */
576     for (i = 0; i < cr; i++)
577         if (i != x)
578             cube(i,y,n) = FALSE;
579
580     /*
581      * Rule out this number in all other positions in the block.
582      */
583     bi = usage->blocks->whichblock[sqindex];
584     for (i = 0; i < cr; i++) {
585         int bp = usage->blocks->blocks[bi][i];
586         if (bp != sqindex)
587             cube2(bp,n) = FALSE;
588     }
589
590     /*
591      * Enter the number in the result grid.
592      */
593     usage->grid[sqindex] = n;
594
595     /*
596      * Cross out this number from the list of numbers left to place
597      * in its row, its column and its block.
598      */
599     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
600         usage->blk[bi*cr+n-1] = TRUE;
601
602     if (usage->diag) {
603         if (ondiag0(sqindex)) {
604             for (i = 0; i < cr; i++)
605                 if (diag0(i) != sqindex)
606                     cube2(diag0(i),n) = FALSE;
607             usage->diag[n-1] = TRUE;
608         }
609         if (ondiag1(sqindex)) {
610             for (i = 0; i < cr; i++)
611                 if (diag1(i) != sqindex)
612                     cube2(diag1(i),n) = FALSE;
613             usage->diag[cr+n-1] = TRUE;
614         }
615     }
616 }
617
618 static int solver_elim(struct solver_usage *usage, int *indices
619 #ifdef STANDALONE_SOLVER
620                        , char *fmt, ...
621 #endif
622                        )
623 {
624     int cr = usage->cr;
625     int fpos, m, i;
626
627     /*
628      * Count the number of set bits within this section of the
629      * cube.
630      */
631     m = 0;
632     fpos = -1;
633     for (i = 0; i < cr; i++)
634         if (usage->cube[indices[i]]) {
635             fpos = indices[i];
636             m++;
637         }
638
639     if (m == 1) {
640         int x, y, n;
641         assert(fpos >= 0);
642
643         n = 1 + fpos % cr;
644         x = fpos / cr;
645         y = x / cr;
646         x %= cr;
647
648         if (!usage->grid[y*cr+x]) {
649 #ifdef STANDALONE_SOLVER
650             if (solver_show_working) {
651                 va_list ap;
652                 printf("%*s", solver_recurse_depth*4, "");
653                 va_start(ap, fmt);
654                 vprintf(fmt, ap);
655                 va_end(ap);
656                 printf(":\n%*s  placing %d at (%d,%d)\n",
657                        solver_recurse_depth*4, "", n, 1+x, 1+y);
658             }
659 #endif
660             solver_place(usage, x, y, n);
661             return +1;
662         }
663     } else if (m == 0) {
664 #ifdef STANDALONE_SOLVER
665         if (solver_show_working) {
666             va_list ap;
667             printf("%*s", solver_recurse_depth*4, "");
668             va_start(ap, fmt);
669             vprintf(fmt, ap);
670             va_end(ap);
671             printf(":\n%*s  no possibilities available\n",
672                    solver_recurse_depth*4, "");
673         }
674 #endif
675         return -1;
676     }
677
678     return 0;
679 }
680
681 static int solver_intersect(struct solver_usage *usage,
682                             int *indices1, int *indices2
683 #ifdef STANDALONE_SOLVER
684                             , char *fmt, ...
685 #endif
686                             )
687 {
688     int cr = usage->cr;
689     int ret, i, j;
690
691     /*
692      * Loop over the first domain and see if there's any set bit
693      * not also in the second.
694      */
695     for (i = j = 0; i < cr; i++) {
696         int p = indices1[i];
697         while (j < cr && indices2[j] < p)
698             j++;
699         if (usage->cube[p]) {
700             if (j < cr && indices2[j] == p)
701                 continue;              /* both domains contain this index */
702             else
703                 return 0;              /* there is, so we can't deduce */
704         }
705     }
706
707     /*
708      * We have determined that all set bits in the first domain are
709      * within its overlap with the second. So loop over the second
710      * domain and remove all set bits that aren't also in that
711      * overlap; return +1 iff we actually _did_ anything.
712      */
713     ret = 0;
714     for (i = j = 0; i < cr; i++) {
715         int p = indices2[i];
716         while (j < cr && indices1[j] < p)
717             j++;
718         if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
719 #ifdef STANDALONE_SOLVER
720             if (solver_show_working) {
721                 int px, py, pn;
722
723                 if (!ret) {
724                     va_list ap;
725                     printf("%*s", solver_recurse_depth*4, "");
726                     va_start(ap, fmt);
727                     vprintf(fmt, ap);
728                     va_end(ap);
729                     printf(":\n");
730                 }
731
732                 pn = 1 + p % cr;
733                 px = p / cr;
734                 py = px / cr;
735                 px %= cr;
736
737                 printf("%*s  ruling out %d at (%d,%d)\n",
738                        solver_recurse_depth*4, "", pn, 1+px, 1+py);
739             }
740 #endif
741             ret = +1;                  /* we did something */
742             usage->cube[p] = 0;
743         }
744     }
745
746     return ret;
747 }
748
749 struct solver_scratch {
750     unsigned char *grid, *rowidx, *colidx, *set;
751     int *neighbours, *bfsqueue;
752     int *indexlist, *indexlist2;
753 #ifdef STANDALONE_SOLVER
754     int *bfsprev;
755 #endif
756 };
757
758 static int solver_set(struct solver_usage *usage,
759                       struct solver_scratch *scratch,
760                       int *indices
761 #ifdef STANDALONE_SOLVER
762                       , char *fmt, ...
763 #endif
764                       )
765 {
766     int cr = usage->cr;
767     int i, j, n, count;
768     unsigned char *grid = scratch->grid;
769     unsigned char *rowidx = scratch->rowidx;
770     unsigned char *colidx = scratch->colidx;
771     unsigned char *set = scratch->set;
772
773     /*
774      * We are passed a cr-by-cr matrix of booleans. Our first job
775      * is to winnow it by finding any definite placements - i.e.
776      * any row with a solitary 1 - and discarding that row and the
777      * column containing the 1.
778      */
779     memset(rowidx, TRUE, cr);
780     memset(colidx, TRUE, cr);
781     for (i = 0; i < cr; i++) {
782         int count = 0, first = -1;
783         for (j = 0; j < cr; j++)
784             if (usage->cube[indices[i*cr+j]])
785                 first = j, count++;
786
787         /*
788          * If count == 0, then there's a row with no 1s at all and
789          * the puzzle is internally inconsistent. However, we ought
790          * to have caught this already during the simpler reasoning
791          * methods, so we can safely fail an assertion if we reach
792          * this point here.
793          */
794         assert(count > 0);
795         if (count == 1)
796             rowidx[i] = colidx[first] = FALSE;
797     }
798
799     /*
800      * Convert each of rowidx/colidx from a list of 0s and 1s to a
801      * list of the indices of the 1s.
802      */
803     for (i = j = 0; i < cr; i++)
804         if (rowidx[i])
805             rowidx[j++] = i;
806     n = j;
807     for (i = j = 0; i < cr; i++)
808         if (colidx[i])
809             colidx[j++] = i;
810     assert(n == j);
811
812     /*
813      * And create the smaller matrix.
814      */
815     for (i = 0; i < n; i++)
816         for (j = 0; j < n; j++)
817             grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
818
819     /*
820      * Having done that, we now have a matrix in which every row
821      * has at least two 1s in. Now we search to see if we can find
822      * a rectangle of zeroes (in the set-theoretic sense of
823      * `rectangle', i.e. a subset of rows crossed with a subset of
824      * columns) whose width and height add up to n.
825      */
826
827     memset(set, 0, n);
828     count = 0;
829     while (1) {
830         /*
831          * We have a candidate set. If its size is <=1 or >=n-1
832          * then we move on immediately.
833          */
834         if (count > 1 && count < n-1) {
835             /*
836              * The number of rows we need is n-count. See if we can
837              * find that many rows which each have a zero in all
838              * the positions listed in `set'.
839              */
840             int rows = 0;
841             for (i = 0; i < n; i++) {
842                 int ok = TRUE;
843                 for (j = 0; j < n; j++)
844                     if (set[j] && grid[i*cr+j]) {
845                         ok = FALSE;
846                         break;
847                     }
848                 if (ok)
849                     rows++;
850             }
851
852             /*
853              * We expect never to be able to get _more_ than
854              * n-count suitable rows: this would imply that (for
855              * example) there are four numbers which between them
856              * have at most three possible positions, and hence it
857              * indicates a faulty deduction before this point or
858              * even a bogus clue.
859              */
860             if (rows > n - count) {
861 #ifdef STANDALONE_SOLVER
862                 if (solver_show_working) {
863                     va_list ap;
864                     printf("%*s", solver_recurse_depth*4,
865                            "");
866                     va_start(ap, fmt);
867                     vprintf(fmt, ap);
868                     va_end(ap);
869                     printf(":\n%*s  contradiction reached\n",
870                            solver_recurse_depth*4, "");
871                 }
872 #endif
873                 return -1;
874             }
875
876             if (rows >= n - count) {
877                 int progress = FALSE;
878
879                 /*
880                  * We've got one! Now, for each row which _doesn't_
881                  * satisfy the criterion, eliminate all its set
882                  * bits in the positions _not_ listed in `set'.
883                  * Return +1 (meaning progress has been made) if we
884                  * successfully eliminated anything at all.
885                  * 
886                  * This involves referring back through
887                  * rowidx/colidx in order to work out which actual
888                  * positions in the cube to meddle with.
889                  */
890                 for (i = 0; i < n; i++) {
891                     int ok = TRUE;
892                     for (j = 0; j < n; j++)
893                         if (set[j] && grid[i*cr+j]) {
894                             ok = FALSE;
895                             break;
896                         }
897                     if (!ok) {
898                         for (j = 0; j < n; j++)
899                             if (!set[j] && grid[i*cr+j]) {
900                                 int fpos = indices[rowidx[i]*cr+colidx[j]];
901 #ifdef STANDALONE_SOLVER
902                                 if (solver_show_working) {
903                                     int px, py, pn;
904
905                                     if (!progress) {
906                                         va_list ap;
907                                         printf("%*s", solver_recurse_depth*4,
908                                                "");
909                                         va_start(ap, fmt);
910                                         vprintf(fmt, ap);
911                                         va_end(ap);
912                                         printf(":\n");
913                                     }
914
915                                     pn = 1 + fpos % cr;
916                                     px = fpos / cr;
917                                     py = px / cr;
918                                     px %= cr;
919
920                                     printf("%*s  ruling out %d at (%d,%d)\n",
921                                            solver_recurse_depth*4, "",
922                                            pn, 1+px, 1+py);
923                                 }
924 #endif
925                                 progress = TRUE;
926                                 usage->cube[fpos] = FALSE;
927                             }
928                     }
929                 }
930
931                 if (progress) {
932                     return +1;
933                 }
934             }
935         }
936
937         /*
938          * Binary increment: change the rightmost 0 to a 1, and
939          * change all 1s to the right of it to 0s.
940          */
941         i = n;
942         while (i > 0 && set[i-1])
943             set[--i] = 0, count--;
944         if (i > 0)
945             set[--i] = 1, count++;
946         else
947             break;                     /* done */
948     }
949
950     return 0;
951 }
952
953 /*
954  * Look for forcing chains. A forcing chain is a path of
955  * pairwise-exclusive squares (i.e. each pair of adjacent squares
956  * in the path are in the same row, column or block) with the
957  * following properties:
958  *
959  *  (a) Each square on the path has precisely two possible numbers.
960  *
961  *  (b) Each pair of squares which are adjacent on the path share
962  *      at least one possible number in common.
963  *
964  *  (c) Each square in the middle of the path shares _both_ of its
965  *      numbers with at least one of its neighbours (not the same
966  *      one with both neighbours).
967  *
968  * These together imply that at least one of the possible number
969  * choices at one end of the path forces _all_ the rest of the
970  * numbers along the path. In order to make real use of this, we
971  * need further properties:
972  *
973  *  (c) Ruling out some number N from the square at one end of the
974  *      path forces the square at the other end to take the same
975  *      number N.
976  *
977  *  (d) The two end squares are both in line with some third
978  *      square.
979  *
980  *  (e) That third square currently has N as a possibility.
981  *
982  * If we can find all of that lot, we can deduce that at least one
983  * of the two ends of the forcing chain has number N, and that
984  * therefore the mutually adjacent third square does not.
985  *
986  * To find forcing chains, we're going to start a bfs at each
987  * suitable square, once for each of its two possible numbers.
988  */
989 static int solver_forcing(struct solver_usage *usage,
990                           struct solver_scratch *scratch)
991 {
992     int cr = usage->cr;
993     int *bfsqueue = scratch->bfsqueue;
994 #ifdef STANDALONE_SOLVER
995     int *bfsprev = scratch->bfsprev;
996 #endif
997     unsigned char *number = scratch->grid;
998     int *neighbours = scratch->neighbours;
999     int x, y;
1000
1001     for (y = 0; y < cr; y++)
1002         for (x = 0; x < cr; x++) {
1003             int count, t, n;
1004
1005             /*
1006              * If this square doesn't have exactly two candidate
1007              * numbers, don't try it.
1008              * 
1009              * In this loop we also sum the candidate numbers,
1010              * which is a nasty hack to allow us to quickly find
1011              * `the other one' (since we will shortly know there
1012              * are exactly two).
1013              */
1014             for (count = t = 0, n = 1; n <= cr; n++)
1015                 if (cube(x, y, n))
1016                     count++, t += n;
1017             if (count != 2)
1018                 continue;
1019
1020             /*
1021              * Now attempt a bfs for each candidate.
1022              */
1023             for (n = 1; n <= cr; n++)
1024                 if (cube(x, y, n)) {
1025                     int orign, currn, head, tail;
1026
1027                     /*
1028                      * Begin a bfs.
1029                      */
1030                     orign = n;
1031
1032                     memset(number, cr+1, cr*cr);
1033                     head = tail = 0;
1034                     bfsqueue[tail++] = y*cr+x;
1035 #ifdef STANDALONE_SOLVER
1036                     bfsprev[y*cr+x] = -1;
1037 #endif
1038                     number[y*cr+x] = t - n;
1039
1040                     while (head < tail) {
1041                         int xx, yy, nneighbours, xt, yt, i;
1042
1043                         xx = bfsqueue[head++];
1044                         yy = xx / cr;
1045                         xx %= cr;
1046
1047                         currn = number[yy*cr+xx];
1048
1049                         /*
1050                          * Find neighbours of yy,xx.
1051                          */
1052                         nneighbours = 0;
1053                         for (yt = 0; yt < cr; yt++)
1054                             neighbours[nneighbours++] = yt*cr+xx;
1055                         for (xt = 0; xt < cr; xt++)
1056                             neighbours[nneighbours++] = yy*cr+xt;
1057                         xt = usage->blocks->whichblock[yy*cr+xx];
1058                         for (yt = 0; yt < cr; yt++)
1059                             neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1060                         if (usage->diag) {
1061                             int sqindex = yy*cr+xx;
1062                             if (ondiag0(sqindex)) {
1063                                 for (i = 0; i < cr; i++)
1064                                     neighbours[nneighbours++] = diag0(i);
1065                             }
1066                             if (ondiag1(sqindex)) {
1067                                 for (i = 0; i < cr; i++)
1068                                     neighbours[nneighbours++] = diag1(i);
1069                             }
1070                         }
1071
1072                         /*
1073                          * Try visiting each of those neighbours.
1074                          */
1075                         for (i = 0; i < nneighbours; i++) {
1076                             int cc, tt, nn;
1077
1078                             xt = neighbours[i] % cr;
1079                             yt = neighbours[i] / cr;
1080
1081                             /*
1082                              * We need this square to not be
1083                              * already visited, and to include
1084                              * currn as a possible number.
1085                              */
1086                             if (number[yt*cr+xt] <= cr)
1087                                 continue;
1088                             if (!cube(xt, yt, currn))
1089                                 continue;
1090
1091                             /*
1092                              * Don't visit _this_ square a second
1093                              * time!
1094                              */
1095                             if (xt == xx && yt == yy)
1096                                 continue;
1097
1098                             /*
1099                              * To continue with the bfs, we need
1100                              * this square to have exactly two
1101                              * possible numbers.
1102                              */
1103                             for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1104                                 if (cube(xt, yt, nn))
1105                                     cc++, tt += nn;
1106                             if (cc == 2) {
1107                                 bfsqueue[tail++] = yt*cr+xt;
1108 #ifdef STANDALONE_SOLVER
1109                                 bfsprev[yt*cr+xt] = yy*cr+xx;
1110 #endif
1111                                 number[yt*cr+xt] = tt - currn;
1112                             }
1113
1114                             /*
1115                              * One other possibility is that this
1116                              * might be the square in which we can
1117                              * make a real deduction: if it's
1118                              * adjacent to x,y, and currn is equal
1119                              * to the original number we ruled out.
1120                              */
1121                             if (currn == orign &&
1122                                 (xt == x || yt == y ||
1123                                  (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1124                                  (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1125                                                   (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1126 #ifdef STANDALONE_SOLVER
1127                                 if (solver_show_working) {
1128                                     char *sep = "";
1129                                     int xl, yl;
1130                                     printf("%*sforcing chain, %d at ends of ",
1131                                            solver_recurse_depth*4, "", orign);
1132                                     xl = xx;
1133                                     yl = yy;
1134                                     while (1) {
1135                                         printf("%s(%d,%d)", sep, 1+xl,
1136                                                1+yl);
1137                                         xl = bfsprev[yl*cr+xl];
1138                                         if (xl < 0)
1139                                             break;
1140                                         yl = xl / cr;
1141                                         xl %= cr;
1142                                         sep = "-";
1143                                     }
1144                                     printf("\n%*s  ruling out %d at (%d,%d)\n",
1145                                            solver_recurse_depth*4, "",
1146                                            orign, 1+xt, 1+yt);
1147                                 }
1148 #endif
1149                                 cube(xt, yt, orign) = FALSE;
1150                                 return 1;
1151                             }
1152                         }
1153                     }
1154                 }
1155         }
1156
1157     return 0;
1158 }
1159
1160 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1161 {
1162     struct solver_scratch *scratch = snew(struct solver_scratch);
1163     int cr = usage->cr;
1164     scratch->grid = snewn(cr*cr, unsigned char);
1165     scratch->rowidx = snewn(cr, unsigned char);
1166     scratch->colidx = snewn(cr, unsigned char);
1167     scratch->set = snewn(cr, unsigned char);
1168     scratch->neighbours = snewn(5*cr, int);
1169     scratch->bfsqueue = snewn(cr*cr, int);
1170 #ifdef STANDALONE_SOLVER
1171     scratch->bfsprev = snewn(cr*cr, int);
1172 #endif
1173     scratch->indexlist = snewn(cr*cr, int);   /* used for set elimination */
1174     scratch->indexlist2 = snewn(cr, int);   /* only used for intersect() */
1175     return scratch;
1176 }
1177
1178 static void solver_free_scratch(struct solver_scratch *scratch)
1179 {
1180 #ifdef STANDALONE_SOLVER
1181     sfree(scratch->bfsprev);
1182 #endif
1183     sfree(scratch->bfsqueue);
1184     sfree(scratch->neighbours);
1185     sfree(scratch->set);
1186     sfree(scratch->colidx);
1187     sfree(scratch->rowidx);
1188     sfree(scratch->grid);
1189     sfree(scratch->indexlist);
1190     sfree(scratch->indexlist2);
1191     sfree(scratch);
1192 }
1193
1194 static int solver(int cr, struct block_structure *blocks, int xtype,
1195                   digit *grid, int maxdiff)
1196 {
1197     struct solver_usage *usage;
1198     struct solver_scratch *scratch;
1199     int x, y, b, i, n, ret;
1200     int diff = DIFF_BLOCK;
1201
1202     /*
1203      * Set up a usage structure as a clean slate (everything
1204      * possible).
1205      */
1206     usage = snew(struct solver_usage);
1207     usage->cr = cr;
1208     usage->blocks = blocks;
1209     usage->cube = snewn(cr*cr*cr, unsigned char);
1210     usage->grid = grid;                /* write straight back to the input */
1211     memset(usage->cube, TRUE, cr*cr*cr);
1212
1213     usage->row = snewn(cr * cr, unsigned char);
1214     usage->col = snewn(cr * cr, unsigned char);
1215     usage->blk = snewn(cr * cr, unsigned char);
1216     memset(usage->row, FALSE, cr * cr);
1217     memset(usage->col, FALSE, cr * cr);
1218     memset(usage->blk, FALSE, cr * cr);
1219
1220     if (xtype) {
1221         usage->diag = snewn(cr * 2, unsigned char);
1222         memset(usage->diag, FALSE, cr * 2);
1223     } else
1224         usage->diag = NULL; 
1225
1226     scratch = solver_new_scratch(usage);
1227
1228     /*
1229      * Place all the clue numbers we are given.
1230      */
1231     for (x = 0; x < cr; x++)
1232         for (y = 0; y < cr; y++)
1233             if (grid[y*cr+x])
1234                 solver_place(usage, x, y, grid[y*cr+x]);
1235
1236     /*
1237      * Now loop over the grid repeatedly trying all permitted modes
1238      * of reasoning. The loop terminates if we complete an
1239      * iteration without making any progress; we then return
1240      * failure or success depending on whether the grid is full or
1241      * not.
1242      */
1243     while (1) {
1244         /*
1245          * I'd like to write `continue;' inside each of the
1246          * following loops, so that the solver returns here after
1247          * making some progress. However, I can't specify that I
1248          * want to continue an outer loop rather than the innermost
1249          * one, so I'm apologetically resorting to a goto.
1250          */
1251         cont:
1252
1253         /*
1254          * Blockwise positional elimination.
1255          */
1256         for (b = 0; b < cr; b++)
1257             for (n = 1; n <= cr; n++)
1258                 if (!usage->blk[b*cr+n-1]) {
1259                     for (i = 0; i < cr; i++)
1260                         scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1261                     ret = solver_elim(usage, scratch->indexlist
1262 #ifdef STANDALONE_SOLVER
1263                                       , "positional elimination,"
1264                                       " %d in block %s", n,
1265                                       usage->blocks->blocknames[b]
1266 #endif
1267                                       );
1268                     if (ret < 0) {
1269                         diff = DIFF_IMPOSSIBLE;
1270                         goto got_result;
1271                     } else if (ret > 0) {
1272                         diff = max(diff, DIFF_BLOCK);
1273                         goto cont;
1274                     }
1275                 }
1276
1277         if (maxdiff <= DIFF_BLOCK)
1278             break;
1279
1280         /*
1281          * Row-wise positional elimination.
1282          */
1283         for (y = 0; y < cr; y++)
1284             for (n = 1; n <= cr; n++)
1285                 if (!usage->row[y*cr+n-1]) {
1286                     for (x = 0; x < cr; x++)
1287                         scratch->indexlist[x] = cubepos(x, y, n);
1288                     ret = solver_elim(usage, scratch->indexlist
1289 #ifdef STANDALONE_SOLVER
1290                                       , "positional elimination,"
1291                                       " %d in row %d", n, 1+y
1292 #endif
1293                                       );
1294                     if (ret < 0) {
1295                         diff = DIFF_IMPOSSIBLE;
1296                         goto got_result;
1297                     } else if (ret > 0) {
1298                         diff = max(diff, DIFF_SIMPLE);
1299                         goto cont;
1300                     }
1301                 }
1302         /*
1303          * Column-wise positional elimination.
1304          */
1305         for (x = 0; x < cr; x++)
1306             for (n = 1; n <= cr; n++)
1307                 if (!usage->col[x*cr+n-1]) {
1308                     for (y = 0; y < cr; y++)
1309                         scratch->indexlist[y] = cubepos(x, y, n);
1310                     ret = solver_elim(usage, scratch->indexlist
1311 #ifdef STANDALONE_SOLVER
1312                                       , "positional elimination,"
1313                                       " %d in column %d", n, 1+x
1314 #endif
1315                                       );
1316                     if (ret < 0) {
1317                         diff = DIFF_IMPOSSIBLE;
1318                         goto got_result;
1319                     } else if (ret > 0) {
1320                         diff = max(diff, DIFF_SIMPLE);
1321                         goto cont;
1322                     }
1323                 }
1324
1325         /*
1326          * X-diagonal positional elimination.
1327          */
1328         if (usage->diag) {
1329             for (n = 1; n <= cr; n++)
1330                 if (!usage->diag[n-1]) {
1331                     for (i = 0; i < cr; i++)
1332                         scratch->indexlist[i] = cubepos2(diag0(i), n);
1333                     ret = solver_elim(usage, scratch->indexlist
1334 #ifdef STANDALONE_SOLVER
1335                                       , "positional elimination,"
1336                                       " %d in \\-diagonal", n
1337 #endif
1338                                       );
1339                     if (ret < 0) {
1340                         diff = DIFF_IMPOSSIBLE;
1341                         goto got_result;
1342                     } else if (ret > 0) {
1343                         diff = max(diff, DIFF_SIMPLE);
1344                         goto cont;
1345                     }
1346                 }
1347             for (n = 1; n <= cr; n++)
1348                 if (!usage->diag[cr+n-1]) {
1349                     for (i = 0; i < cr; i++)
1350                         scratch->indexlist[i] = cubepos2(diag1(i), n);
1351                     ret = solver_elim(usage, scratch->indexlist
1352 #ifdef STANDALONE_SOLVER
1353                                       , "positional elimination,"
1354                                       " %d in /-diagonal", n
1355 #endif
1356                                       );
1357                     if (ret < 0) {
1358                         diff = DIFF_IMPOSSIBLE;
1359                         goto got_result;
1360                     } else if (ret > 0) {
1361                         diff = max(diff, DIFF_SIMPLE);
1362                         goto cont;
1363                     }
1364                 }
1365         }
1366
1367         /*
1368          * Numeric elimination.
1369          */
1370         for (x = 0; x < cr; x++)
1371             for (y = 0; y < cr; y++)
1372                 if (!usage->grid[y*cr+x]) {
1373                     for (n = 1; n <= cr; n++)
1374                         scratch->indexlist[n-1] = cubepos(x, y, n);
1375                     ret = solver_elim(usage, scratch->indexlist
1376 #ifdef STANDALONE_SOLVER
1377                                       , "numeric elimination at (%d,%d)",
1378                                       1+x, 1+y
1379 #endif
1380                                       );
1381                     if (ret < 0) {
1382                         diff = DIFF_IMPOSSIBLE;
1383                         goto got_result;
1384                     } else if (ret > 0) {
1385                         diff = max(diff, DIFF_SIMPLE);
1386                         goto cont;
1387                     }
1388                 }
1389
1390         if (maxdiff <= DIFF_SIMPLE)
1391             break;
1392
1393         /*
1394          * Intersectional analysis, rows vs blocks.
1395          */
1396         for (y = 0; y < cr; y++)
1397             for (b = 0; b < cr; b++)
1398                 for (n = 1; n <= cr; n++) {
1399                     if (usage->row[y*cr+n-1] ||
1400                         usage->blk[b*cr+n-1])
1401                         continue;
1402                     for (i = 0; i < cr; i++) {
1403                         scratch->indexlist[i] = cubepos(i, y, n);
1404                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1405                     }
1406                     /*
1407                      * solver_intersect() never returns -1.
1408                      */
1409                     if (solver_intersect(usage, scratch->indexlist,
1410                                          scratch->indexlist2
1411 #ifdef STANDALONE_SOLVER
1412                                           , "intersectional analysis,"
1413                                           " %d in row %d vs block %s",
1414                                           n, 1+y, usage->blocks->blocknames[b]
1415 #endif
1416                                           ) ||
1417                          solver_intersect(usage, scratch->indexlist2,
1418                                          scratch->indexlist
1419 #ifdef STANDALONE_SOLVER
1420                                           , "intersectional analysis,"
1421                                           " %d in block %s vs row %d",
1422                                           n, usage->blocks->blocknames[b], 1+y
1423 #endif
1424                                           )) {
1425                         diff = max(diff, DIFF_INTERSECT);
1426                         goto cont;
1427                     }
1428                 }
1429
1430         /*
1431          * Intersectional analysis, columns vs blocks.
1432          */
1433         for (x = 0; x < cr; x++)
1434             for (b = 0; b < cr; b++)
1435                 for (n = 1; n <= cr; n++) {
1436                     if (usage->col[x*cr+n-1] ||
1437                         usage->blk[b*cr+n-1])
1438                         continue;
1439                     for (i = 0; i < cr; i++) {
1440                         scratch->indexlist[i] = cubepos(x, i, n);
1441                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1442                     }
1443                     if (solver_intersect(usage, scratch->indexlist,
1444                                          scratch->indexlist2
1445 #ifdef STANDALONE_SOLVER
1446                                           , "intersectional analysis,"
1447                                           " %d in column %d vs block %s",
1448                                           n, 1+x, usage->blocks->blocknames[b]
1449 #endif
1450                                           ) ||
1451                          solver_intersect(usage, scratch->indexlist2,
1452                                          scratch->indexlist
1453 #ifdef STANDALONE_SOLVER
1454                                           , "intersectional analysis,"
1455                                           " %d in block %s vs column %d",
1456                                           n, usage->blocks->blocknames[b], 1+x
1457 #endif
1458                                           )) {
1459                         diff = max(diff, DIFF_INTERSECT);
1460                         goto cont;
1461                     }
1462                 }
1463
1464         if (usage->diag) {
1465             /*
1466              * Intersectional analysis, \-diagonal vs blocks.
1467              */
1468             for (b = 0; b < cr; b++)
1469                 for (n = 1; n <= cr; n++) {
1470                     if (usage->diag[n-1] ||
1471                         usage->blk[b*cr+n-1])
1472                         continue;
1473                     for (i = 0; i < cr; i++) {
1474                         scratch->indexlist[i] = cubepos2(diag0(i), n);
1475                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1476                     }
1477                     if (solver_intersect(usage, scratch->indexlist,
1478                                          scratch->indexlist2
1479 #ifdef STANDALONE_SOLVER
1480                                           , "intersectional analysis,"
1481                                           " %d in \\-diagonal vs block %s",
1482                                           n, 1+x, usage->blocks->blocknames[b]
1483 #endif
1484                                           ) ||
1485                          solver_intersect(usage, scratch->indexlist2,
1486                                          scratch->indexlist
1487 #ifdef STANDALONE_SOLVER
1488                                           , "intersectional analysis,"
1489                                           " %d in block %s vs \\-diagonal",
1490                                           n, usage->blocks->blocknames[b], 1+x
1491 #endif
1492                                           )) {
1493                         diff = max(diff, DIFF_INTERSECT);
1494                         goto cont;
1495                     }
1496                 }
1497
1498             /*
1499              * Intersectional analysis, /-diagonal vs blocks.
1500              */
1501             for (b = 0; b < cr; b++)
1502                 for (n = 1; n <= cr; n++) {
1503                     if (usage->diag[cr+n-1] ||
1504                         usage->blk[b*cr+n-1])
1505                         continue;
1506                     for (i = 0; i < cr; i++) {
1507                         scratch->indexlist[i] = cubepos2(diag1(i), n);
1508                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1509                     }
1510                     if (solver_intersect(usage, scratch->indexlist,
1511                                          scratch->indexlist2
1512 #ifdef STANDALONE_SOLVER
1513                                           , "intersectional analysis,"
1514                                           " %d in /-diagonal vs block %s",
1515                                           n, 1+x, usage->blocks->blocknames[b]
1516 #endif
1517                                           ) ||
1518                          solver_intersect(usage, scratch->indexlist2,
1519                                          scratch->indexlist
1520 #ifdef STANDALONE_SOLVER
1521                                           , "intersectional analysis,"
1522                                           " %d in block %s vs /-diagonal",
1523                                           n, usage->blocks->blocknames[b], 1+x
1524 #endif
1525                                           )) {
1526                         diff = max(diff, DIFF_INTERSECT);
1527                         goto cont;
1528                     }
1529                 }
1530         }
1531
1532         if (maxdiff <= DIFF_INTERSECT)
1533             break;
1534
1535         /*
1536          * Blockwise set elimination.
1537          */
1538         for (b = 0; b < cr; b++) {
1539             for (i = 0; i < cr; i++)
1540                 for (n = 1; n <= cr; n++)
1541                     scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
1542             ret = solver_set(usage, scratch, scratch->indexlist
1543 #ifdef STANDALONE_SOLVER
1544                              , "set elimination, block %s",
1545                              usage->blocks->blocknames[b]
1546 #endif
1547                                  );
1548             if (ret < 0) {
1549                 diff = DIFF_IMPOSSIBLE;
1550                 goto got_result;
1551             } else if (ret > 0) {
1552                 diff = max(diff, DIFF_SET);
1553                 goto cont;
1554             }
1555         }
1556
1557         /*
1558          * Row-wise set elimination.
1559          */
1560         for (y = 0; y < cr; y++) {
1561             for (x = 0; x < cr; x++)
1562                 for (n = 1; n <= cr; n++)
1563                     scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
1564             ret = solver_set(usage, scratch, scratch->indexlist
1565 #ifdef STANDALONE_SOLVER
1566                              , "set elimination, row %d", 1+y
1567 #endif
1568                              );
1569             if (ret < 0) {
1570                 diff = DIFF_IMPOSSIBLE;
1571                 goto got_result;
1572             } else if (ret > 0) {
1573                 diff = max(diff, DIFF_SET);
1574                 goto cont;
1575             }
1576         }
1577
1578         /*
1579          * Column-wise set elimination.
1580          */
1581         for (x = 0; x < cr; x++) {
1582             for (y = 0; y < cr; y++)
1583                 for (n = 1; n <= cr; n++)
1584                     scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
1585             ret = solver_set(usage, scratch, scratch->indexlist
1586 #ifdef STANDALONE_SOLVER
1587                              , "set elimination, column %d", 1+x
1588 #endif
1589                              );
1590             if (ret < 0) {
1591                 diff = DIFF_IMPOSSIBLE;
1592                 goto got_result;
1593             } else if (ret > 0) {
1594                 diff = max(diff, DIFF_SET);
1595                 goto cont;
1596             }
1597         }
1598
1599         if (usage->diag) {
1600             /*
1601              * \-diagonal set elimination.
1602              */
1603             for (i = 0; i < cr; i++)
1604                 for (n = 1; n <= cr; n++)
1605                     scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
1606             ret = solver_set(usage, scratch, scratch->indexlist
1607 #ifdef STANDALONE_SOLVER
1608                              , "set elimination, \\-diagonal"
1609 #endif
1610                              );
1611             if (ret < 0) {
1612                 diff = DIFF_IMPOSSIBLE;
1613                 goto got_result;
1614             } else if (ret > 0) {
1615                 diff = max(diff, DIFF_SET);
1616                 goto cont;
1617             }
1618
1619             /*
1620              * /-diagonal set elimination.
1621              */
1622             for (i = 0; i < cr; i++)
1623                 for (n = 1; n <= cr; n++)
1624                     scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
1625             ret = solver_set(usage, scratch, scratch->indexlist
1626 #ifdef STANDALONE_SOLVER
1627                              , "set elimination, \\-diagonal"
1628 #endif
1629                              );
1630             if (ret < 0) {
1631                 diff = DIFF_IMPOSSIBLE;
1632                 goto got_result;
1633             } else if (ret > 0) {
1634                 diff = max(diff, DIFF_SET);
1635                 goto cont;
1636             }
1637         }
1638
1639         if (maxdiff <= DIFF_SET)
1640             break;
1641
1642         /*
1643          * Row-vs-column set elimination on a single number.
1644          */
1645         for (n = 1; n <= cr; n++) {
1646             for (y = 0; y < cr; y++)
1647                 for (x = 0; x < cr; x++)
1648                     scratch->indexlist[y*cr+x] = cubepos(x, y, n);
1649             ret = solver_set(usage, scratch, scratch->indexlist
1650 #ifdef STANDALONE_SOLVER
1651                              , "positional set elimination, number %d", n
1652 #endif
1653                              );
1654             if (ret < 0) {
1655                 diff = DIFF_IMPOSSIBLE;
1656                 goto got_result;
1657             } else if (ret > 0) {
1658                 diff = max(diff, DIFF_EXTREME);
1659                 goto cont;
1660             }
1661         }
1662
1663         /*
1664          * Forcing chains.
1665          */
1666         if (solver_forcing(usage, scratch)) {
1667             diff = max(diff, DIFF_EXTREME);
1668             goto cont;
1669         }
1670
1671         /*
1672          * If we reach here, we have made no deductions in this
1673          * iteration, so the algorithm terminates.
1674          */
1675         break;
1676     }
1677
1678     /*
1679      * Last chance: if we haven't fully solved the puzzle yet, try
1680      * recursing based on guesses for a particular square. We pick
1681      * one of the most constrained empty squares we can find, which
1682      * has the effect of pruning the search tree as much as
1683      * possible.
1684      */
1685     if (maxdiff >= DIFF_RECURSIVE) {
1686         int best, bestcount;
1687
1688         best = -1;
1689         bestcount = cr+1;
1690
1691         for (y = 0; y < cr; y++)
1692             for (x = 0; x < cr; x++)
1693                 if (!grid[y*cr+x]) {
1694                     int count;
1695
1696                     /*
1697                      * An unfilled square. Count the number of
1698                      * possible digits in it.
1699                      */
1700                     count = 0;
1701                     for (n = 1; n <= cr; n++)
1702                         if (cube(x,y,n))
1703                             count++;
1704
1705                     /*
1706                      * We should have found any impossibilities
1707                      * already, so this can safely be an assert.
1708                      */
1709                     assert(count > 1);
1710
1711                     if (count < bestcount) {
1712                         bestcount = count;
1713                         best = y*cr+x;
1714                     }
1715                 }
1716
1717         if (best != -1) {
1718             int i, j;
1719             digit *list, *ingrid, *outgrid;
1720
1721             diff = DIFF_IMPOSSIBLE;    /* no solution found yet */
1722
1723             /*
1724              * Attempt recursion.
1725              */
1726             y = best / cr;
1727             x = best % cr;
1728
1729             list = snewn(cr, digit);
1730             ingrid = snewn(cr * cr, digit);
1731             outgrid = snewn(cr * cr, digit);
1732             memcpy(ingrid, grid, cr * cr);
1733
1734             /* Make a list of the possible digits. */
1735             for (j = 0, n = 1; n <= cr; n++)
1736                 if (cube(x,y,n))
1737                     list[j++] = n;
1738
1739 #ifdef STANDALONE_SOLVER
1740             if (solver_show_working) {
1741                 char *sep = "";
1742                 printf("%*srecursing on (%d,%d) [",
1743                        solver_recurse_depth*4, "", x + 1, y + 1);
1744                 for (i = 0; i < j; i++) {
1745                     printf("%s%d", sep, list[i]);
1746                     sep = " or ";
1747                 }
1748                 printf("]\n");
1749             }
1750 #endif
1751
1752             /*
1753              * And step along the list, recursing back into the
1754              * main solver at every stage.
1755              */
1756             for (i = 0; i < j; i++) {
1757                 int ret;
1758
1759                 memcpy(outgrid, ingrid, cr * cr);
1760                 outgrid[y*cr+x] = list[i];
1761
1762 #ifdef STANDALONE_SOLVER
1763                 if (solver_show_working)
1764                     printf("%*sguessing %d at (%d,%d)\n",
1765                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1766                 solver_recurse_depth++;
1767 #endif
1768
1769                 ret = solver(cr, blocks, xtype, outgrid, maxdiff);
1770
1771 #ifdef STANDALONE_SOLVER
1772                 solver_recurse_depth--;
1773                 if (solver_show_working) {
1774                     printf("%*sretracting %d at (%d,%d)\n",
1775                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1776                 }
1777 #endif
1778
1779                 /*
1780                  * If we have our first solution, copy it into the
1781                  * grid we will return.
1782                  */
1783                 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1784                     memcpy(grid, outgrid, cr*cr);
1785
1786                 if (ret == DIFF_AMBIGUOUS)
1787                     diff = DIFF_AMBIGUOUS;
1788                 else if (ret == DIFF_IMPOSSIBLE)
1789                     /* do not change our return value */;
1790                 else {
1791                     /* the recursion turned up exactly one solution */
1792                     if (diff == DIFF_IMPOSSIBLE)
1793                         diff = DIFF_RECURSIVE;
1794                     else
1795                         diff = DIFF_AMBIGUOUS;
1796                 }
1797
1798                 /*
1799                  * As soon as we've found more than one solution,
1800                  * give up immediately.
1801                  */
1802                 if (diff == DIFF_AMBIGUOUS)
1803                     break;
1804             }
1805
1806             sfree(outgrid);
1807             sfree(ingrid);
1808             sfree(list);
1809         }
1810
1811     } else {
1812         /*
1813          * We're forbidden to use recursion, so we just see whether
1814          * our grid is fully solved, and return DIFF_IMPOSSIBLE
1815          * otherwise.
1816          */
1817         for (y = 0; y < cr; y++)
1818             for (x = 0; x < cr; x++)
1819                 if (!grid[y*cr+x])
1820                     diff = DIFF_IMPOSSIBLE;
1821     }
1822
1823     got_result:;
1824
1825 #ifdef STANDALONE_SOLVER
1826     if (solver_show_working)
1827         printf("%*s%s found\n",
1828                solver_recurse_depth*4, "",
1829                diff == DIFF_IMPOSSIBLE ? "no solution" :
1830                diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1831                "one solution");
1832 #endif
1833
1834     sfree(usage->cube);
1835     sfree(usage->row);
1836     sfree(usage->col);
1837     sfree(usage->blk);
1838     sfree(usage);
1839
1840     solver_free_scratch(scratch);
1841
1842     return diff;
1843 }
1844
1845 /* ----------------------------------------------------------------------
1846  * End of solver code.
1847  */
1848
1849 /* ----------------------------------------------------------------------
1850  * Solo filled-grid generator.
1851  *
1852  * This grid generator works by essentially trying to solve a grid
1853  * starting from no clues, and not worrying that there's more than
1854  * one possible solution. Unfortunately, it isn't computationally
1855  * feasible to do this by calling the above solver with an empty
1856  * grid, because that one needs to allocate a lot of scratch space
1857  * at every recursion level. Instead, I have a much simpler
1858  * algorithm which I shamelessly copied from a Python solver
1859  * written by Andrew Wilkinson (which is GPLed, but I've reused
1860  * only ideas and no code). It mostly just does the obvious
1861  * recursive thing: pick an empty square, put one of the possible
1862  * digits in it, recurse until all squares are filled, backtrack
1863  * and change some choices if necessary.
1864  *
1865  * The clever bit is that every time it chooses which square to
1866  * fill in next, it does so by counting the number of _possible_
1867  * numbers that can go in each square, and it prioritises so that
1868  * it picks a square with the _lowest_ number of possibilities. The
1869  * idea is that filling in lots of the obvious bits (particularly
1870  * any squares with only one possibility) will cut down on the list
1871  * of possibilities for other squares and hence reduce the enormous
1872  * search space as much as possible as early as possible.
1873  */
1874
1875 /*
1876  * Internal data structure used in gridgen to keep track of
1877  * progress.
1878  */
1879 struct gridgen_coord { int x, y, r; };
1880 struct gridgen_usage {
1881     int cr;
1882     struct block_structure *blocks;
1883     /* grid is a copy of the input grid, modified as we go along */
1884     digit *grid;
1885     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1886     unsigned char *row;
1887     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1888     unsigned char *col;
1889     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1890     unsigned char *blk;
1891     /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
1892     unsigned char *diag;
1893     /* This lists all the empty spaces remaining in the grid. */
1894     struct gridgen_coord *spaces;
1895     int nspaces;
1896     /* If we need randomisation in the solve, this is our random state. */
1897     random_state *rs;
1898 };
1899
1900 /*
1901  * The real recursive step in the generating function.
1902  *
1903  * Return values: 1 means solution found, 0 means no solution
1904  * found on this branch.
1905  */
1906 static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1907 {
1908     int cr = usage->cr;
1909     int i, j, n, sx, sy, bestm, bestr, ret;
1910     int *digits;
1911
1912     /*
1913      * Firstly, check for completion! If there are no spaces left
1914      * in the grid, we have a solution.
1915      */
1916     if (usage->nspaces == 0) {
1917         memcpy(grid, usage->grid, cr * cr);
1918         return TRUE;
1919     }
1920
1921     /*
1922      * Otherwise, there must be at least one space. Find the most
1923      * constrained space, using the `r' field as a tie-breaker.
1924      */
1925     bestm = cr+1;                      /* so that any space will beat it */
1926     bestr = 0;
1927     i = sx = sy = -1;
1928     for (j = 0; j < usage->nspaces; j++) {
1929         int x = usage->spaces[j].x, y = usage->spaces[j].y;
1930         int m;
1931
1932         /*
1933          * Find the number of digits that could go in this space.
1934          */
1935         m = 0;
1936         for (n = 0; n < cr; n++)
1937             if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1938                 !usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n] &&
1939                 (!usage->diag || ((!ondiag0(y*cr+x) || !usage->diag[n]) &&
1940                                   (!ondiag1(y*cr+x) || !usage->diag[cr+n]))))
1941                 m++;
1942
1943         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1944             bestm = m;
1945             bestr = usage->spaces[j].r;
1946             sx = x;
1947             sy = y;
1948             i = j;
1949         }
1950     }
1951
1952     /*
1953      * Swap that square into the final place in the spaces array,
1954      * so that decrementing nspaces will remove it from the list.
1955      */
1956     if (i != usage->nspaces-1) {
1957         struct gridgen_coord t;
1958         t = usage->spaces[usage->nspaces-1];
1959         usage->spaces[usage->nspaces-1] = usage->spaces[i];
1960         usage->spaces[i] = t;
1961     }
1962
1963     /*
1964      * Now we've decided which square to start our recursion at,
1965      * simply go through all possible values, shuffling them
1966      * randomly first if necessary.
1967      */
1968     digits = snewn(bestm, int);
1969     j = 0;
1970     for (n = 0; n < cr; n++)
1971         if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1972             !usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n] &&
1973             (!usage->diag || ((!ondiag0(sy*cr+sx) || !usage->diag[n]) &&
1974                               (!ondiag1(sy*cr+sx) || !usage->diag[cr+n])))) {
1975             digits[j++] = n+1;
1976         }
1977
1978     if (usage->rs)
1979         shuffle(digits, j, sizeof(*digits), usage->rs);
1980
1981     /* And finally, go through the digit list and actually recurse. */
1982     ret = FALSE;
1983     for (i = 0; i < j; i++) {
1984         n = digits[i];
1985
1986         /* Update the usage structure to reflect the placing of this digit. */
1987         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1988             usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n-1] = TRUE;
1989         if (usage->diag) {
1990             if (ondiag0(sy*cr+sx))
1991                 usage->diag[n-1] = TRUE;
1992             if (ondiag1(sy*cr+sx))
1993                 usage->diag[cr+n-1] = TRUE;
1994         }
1995         usage->grid[sy*cr+sx] = n;
1996         usage->nspaces--;
1997
1998         /* Call the solver recursively. Stop when we find a solution. */
1999         if (gridgen_real(usage, grid))
2000             ret = TRUE;
2001
2002         /* Revert the usage structure. */
2003         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
2004             usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n-1] = FALSE;
2005         if (usage->diag) {
2006             if (ondiag0(sy*cr+sx))
2007                 usage->diag[n-1] = FALSE;
2008             if (ondiag1(sy*cr+sx))
2009                 usage->diag[cr+n-1] = FALSE;
2010         }
2011         usage->grid[sy*cr+sx] = 0;
2012         usage->nspaces++;
2013
2014         if (ret)
2015             break;
2016     }
2017
2018     sfree(digits);
2019     return ret;
2020 }
2021
2022 /*
2023  * Entry point to generator. You give it parameters and a starting
2024  * grid, which is simply an array of cr*cr digits.
2025  */
2026 static int gridgen(int cr, struct block_structure *blocks, int xtype,
2027                    digit *grid, random_state *rs)
2028 {
2029     struct gridgen_usage *usage;
2030     int x, y, ret;
2031
2032     /*
2033      * Clear the grid to start with.
2034      */
2035     memset(grid, 0, cr*cr);
2036
2037     /*
2038      * Create a gridgen_usage structure.
2039      */
2040     usage = snew(struct gridgen_usage);
2041
2042     usage->cr = cr;
2043     usage->blocks = blocks;
2044
2045     usage->grid = snewn(cr * cr, digit);
2046     memcpy(usage->grid, grid, cr * cr);
2047
2048     usage->row = snewn(cr * cr, unsigned char);
2049     usage->col = snewn(cr * cr, unsigned char);
2050     usage->blk = snewn(cr * cr, unsigned char);
2051     memset(usage->row, FALSE, cr * cr);
2052     memset(usage->col, FALSE, cr * cr);
2053     memset(usage->blk, FALSE, cr * cr);
2054
2055     if (xtype) {
2056         usage->diag = snewn(2 * cr, unsigned char);
2057         memset(usage->diag, FALSE, 2 * cr);
2058     } else {
2059         usage->diag = NULL;
2060     }
2061
2062     usage->spaces = snewn(cr * cr, struct gridgen_coord);
2063     usage->nspaces = 0;
2064
2065     usage->rs = rs;
2066
2067     /*
2068      * Initialise the list of grid spaces.
2069      */
2070     for (y = 0; y < cr; y++) {
2071         for (x = 0; x < cr; x++) {
2072             usage->spaces[usage->nspaces].x = x;
2073             usage->spaces[usage->nspaces].y = y;
2074             usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2075             usage->nspaces++;
2076         }
2077     }
2078
2079     /*
2080      * Run the real generator function.
2081      */
2082     ret = gridgen_real(usage, grid);
2083
2084     /*
2085      * Clean up the usage structure now we have our answer.
2086      */
2087     sfree(usage->spaces);
2088     sfree(usage->blk);
2089     sfree(usage->col);
2090     sfree(usage->row);
2091     sfree(usage->grid);
2092     sfree(usage);
2093
2094     return ret;
2095 }
2096
2097 /* ----------------------------------------------------------------------
2098  * End of grid generator code.
2099  */
2100
2101 /*
2102  * Check whether a grid contains a valid complete puzzle.
2103  */
2104 static int check_valid(int cr, struct block_structure *blocks, int xtype,
2105                        digit *grid)
2106 {
2107     unsigned char *used;
2108     int x, y, i, j, n;
2109
2110     used = snewn(cr, unsigned char);
2111
2112     /*
2113      * Check that each row contains precisely one of everything.
2114      */
2115     for (y = 0; y < cr; y++) {
2116         memset(used, FALSE, cr);
2117         for (x = 0; x < cr; x++)
2118             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2119                 used[grid[y*cr+x]-1] = TRUE;
2120         for (n = 0; n < cr; n++)
2121             if (!used[n]) {
2122                 sfree(used);
2123                 return FALSE;
2124             }
2125     }
2126
2127     /*
2128      * Check that each column contains precisely one of everything.
2129      */
2130     for (x = 0; x < cr; x++) {
2131         memset(used, FALSE, cr);
2132         for (y = 0; y < cr; y++)
2133             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2134                 used[grid[y*cr+x]-1] = TRUE;
2135         for (n = 0; n < cr; n++)
2136             if (!used[n]) {
2137                 sfree(used);
2138                 return FALSE;
2139             }
2140     }
2141
2142     /*
2143      * Check that each block contains precisely one of everything.
2144      */
2145     for (i = 0; i < cr; i++) {
2146         memset(used, FALSE, cr);
2147         for (j = 0; j < cr; j++)
2148             if (grid[blocks->blocks[i][j]] > 0 &&
2149                 grid[blocks->blocks[i][j]] <= cr)
2150                 used[grid[blocks->blocks[i][j]]-1] = TRUE;
2151         for (n = 0; n < cr; n++)
2152             if (!used[n]) {
2153                 sfree(used);
2154                 return FALSE;
2155             }
2156     }
2157
2158     /*
2159      * Check that each diagonal contains precisely one of everything.
2160      */
2161     if (xtype) {
2162         memset(used, FALSE, cr);
2163         for (i = 0; i < cr; i++)
2164             if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
2165                 used[grid[diag0(i)]-1] = TRUE;
2166         for (n = 0; n < cr; n++)
2167             if (!used[n]) {
2168                 sfree(used);
2169                 return FALSE;
2170             }
2171         for (i = 0; i < cr; i++)
2172             if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
2173                 used[grid[diag1(i)]-1] = TRUE;
2174         for (n = 0; n < cr; n++)
2175             if (!used[n]) {
2176                 sfree(used);
2177                 return FALSE;
2178             }
2179     }
2180
2181     sfree(used);
2182     return TRUE;
2183 }
2184
2185 static int symmetries(game_params *params, int x, int y, int *output, int s)
2186 {
2187     int c = params->c, r = params->r, cr = c*r;
2188     int i = 0;
2189
2190 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2191
2192     ADD(x, y);
2193
2194     switch (s) {
2195       case SYMM_NONE:
2196         break;                         /* just x,y is all we need */
2197       case SYMM_ROT2:
2198         ADD(cr - 1 - x, cr - 1 - y);
2199         break;
2200       case SYMM_ROT4:
2201         ADD(cr - 1 - y, x);
2202         ADD(y, cr - 1 - x);
2203         ADD(cr - 1 - x, cr - 1 - y);
2204         break;
2205       case SYMM_REF2:
2206         ADD(cr - 1 - x, y);
2207         break;
2208       case SYMM_REF2D:
2209         ADD(y, x);
2210         break;
2211       case SYMM_REF4:
2212         ADD(cr - 1 - x, y);
2213         ADD(x, cr - 1 - y);
2214         ADD(cr - 1 - x, cr - 1 - y);
2215         break;
2216       case SYMM_REF4D:
2217         ADD(y, x);
2218         ADD(cr - 1 - x, cr - 1 - y);
2219         ADD(cr - 1 - y, cr - 1 - x);
2220         break;
2221       case SYMM_REF8:
2222         ADD(cr - 1 - x, y);
2223         ADD(x, cr - 1 - y);
2224         ADD(cr - 1 - x, cr - 1 - y);
2225         ADD(y, x);
2226         ADD(y, cr - 1 - x);
2227         ADD(cr - 1 - y, x);
2228         ADD(cr - 1 - y, cr - 1 - x);
2229         break;
2230     }
2231
2232 #undef ADD
2233
2234     return i;
2235 }
2236
2237 static char *encode_solve_move(int cr, digit *grid)
2238 {
2239     int i, len;
2240     char *ret, *p, *sep;
2241
2242     /*
2243      * It's surprisingly easy to work out _exactly_ how long this
2244      * string needs to be. To decimal-encode all the numbers from 1
2245      * to n:
2246      * 
2247      *  - every number has a units digit; total is n.
2248      *  - all numbers above 9 have a tens digit; total is max(n-9,0).
2249      *  - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2250      *  - and so on.
2251      */
2252     len = 0;
2253     for (i = 1; i <= cr; i *= 10)
2254         len += max(cr - i + 1, 0);
2255     len += cr;                 /* don't forget the commas */
2256     len *= cr;                 /* there are cr rows of these */
2257
2258     /*
2259      * Now len is one bigger than the total size of the
2260      * comma-separated numbers (because we counted an
2261      * additional leading comma). We need to have a leading S
2262      * and a trailing NUL, so we're off by one in total.
2263      */
2264     len++;
2265
2266     ret = snewn(len, char);
2267     p = ret;
2268     *p++ = 'S';
2269     sep = "";
2270     for (i = 0; i < cr*cr; i++) {
2271         p += sprintf(p, "%s%d", sep, grid[i]);
2272         sep = ",";
2273     }
2274     *p++ = '\0';
2275     assert(p - ret == len);
2276
2277     return ret;
2278 }
2279
2280 static char *new_game_desc(game_params *params, random_state *rs,
2281                            char **aux, int interactive)
2282 {
2283     int c = params->c, r = params->r, cr = c*r;
2284     int area = cr*cr;
2285     struct block_structure *blocks;
2286     digit *grid, *grid2;
2287     struct xy { int x, y; } *locs;
2288     int nlocs;
2289     char *desc;
2290     int coords[16], ncoords;
2291     int maxdiff;
2292     int x, y, i, j;
2293
2294     /*
2295      * Adjust the maximum difficulty level to be consistent with
2296      * the puzzle size: all 2x2 puzzles appear to be Trivial
2297      * (DIFF_BLOCK) so we cannot hold out for even a Basic
2298      * (DIFF_SIMPLE) one.
2299      */
2300     maxdiff = params->diff;
2301     if (c == 2 && r == 2)
2302         maxdiff = DIFF_BLOCK;
2303
2304     grid = snewn(area, digit);
2305     locs = snewn(area, struct xy);
2306     grid2 = snewn(area, digit);
2307
2308     blocks = snew(struct block_structure);
2309     blocks->c = params->c; blocks->r = params->r;
2310     blocks->whichblock = snewn(area*2, int);
2311     blocks->blocks = snewn(cr, int *);
2312     for (i = 0; i < cr; i++)
2313         blocks->blocks[i] = blocks->whichblock + area + i*cr;
2314 #ifdef STANDALONE_SOLVER
2315     assert(!"This should never happen, so we don't need to create blocknames");
2316 #endif
2317
2318     /*
2319      * Loop until we get a grid of the required difficulty. This is
2320      * nasty, but it seems to be unpleasantly hard to generate
2321      * difficult grids otherwise.
2322      */
2323     while (1) {
2324         /*
2325          * Generate a random solved state, starting by
2326          * constructing the block structure.
2327          */
2328         if (r == 1) {                  /* jigsaw mode */
2329             int *dsf = divvy_rectangle(cr, cr, cr, rs);
2330             int nb = 0;
2331
2332             for (i = 0; i < area; i++)
2333                 blocks->whichblock[i] = -1;
2334             for (i = 0; i < area; i++) {
2335                 int j = dsf_canonify(dsf, i);
2336                 if (blocks->whichblock[j] < 0)
2337                     blocks->whichblock[j] = nb++;
2338                 blocks->whichblock[i] = blocks->whichblock[j];
2339             }
2340             assert(nb == cr);
2341
2342             sfree(dsf);
2343         } else {                       /* basic Sudoku mode */
2344             for (y = 0; y < cr; y++)
2345                 for (x = 0; x < cr; x++)
2346                     blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2347         }
2348         for (i = 0; i < cr; i++)
2349             blocks->blocks[i][cr-1] = 0;
2350         for (i = 0; i < area; i++) {
2351             int b = blocks->whichblock[i];
2352             j = blocks->blocks[b][cr-1]++;
2353             assert(j < cr);
2354             blocks->blocks[b][j] = i;
2355         }
2356
2357         if (!gridgen(cr, blocks, params->xtype, grid, rs))
2358             continue;  /* this might happen if the jigsaw is unsuitable */
2359         assert(check_valid(cr, blocks, params->xtype, grid));
2360
2361         /*
2362          * Save the solved grid in aux.
2363          */
2364         {
2365             /*
2366              * We might already have written *aux the last time we
2367              * went round this loop, in which case we should free
2368              * the old aux before overwriting it with the new one.
2369              */
2370             if (*aux) {
2371                 sfree(*aux);
2372             }
2373
2374             *aux = encode_solve_move(cr, grid);
2375         }
2376
2377         /*
2378          * Now we have a solved grid, start removing things from it
2379          * while preserving solubility.
2380          */
2381
2382         /*
2383          * Find the set of equivalence classes of squares permitted
2384          * by the selected symmetry. We do this by enumerating all
2385          * the grid squares which have no symmetric companion
2386          * sorting lower than themselves.
2387          */
2388         nlocs = 0;
2389         for (y = 0; y < cr; y++)
2390             for (x = 0; x < cr; x++) {
2391                 int i = y*cr+x;
2392                 int j;
2393
2394                 ncoords = symmetries(params, x, y, coords, params->symm);
2395                 for (j = 0; j < ncoords; j++)
2396                     if (coords[2*j+1]*cr+coords[2*j] < i)
2397                         break;
2398                 if (j == ncoords) {
2399                     locs[nlocs].x = x;
2400                     locs[nlocs].y = y;
2401                     nlocs++;
2402                 }
2403             }
2404
2405         /*
2406          * Now shuffle that list.
2407          */
2408         shuffle(locs, nlocs, sizeof(*locs), rs);
2409
2410         /*
2411          * Now loop over the shuffled list and, for each element,
2412          * see whether removing that element (and its reflections)
2413          * from the grid will still leave the grid soluble.
2414          */
2415         for (i = 0; i < nlocs; i++) {
2416             int ret;
2417
2418             x = locs[i].x;
2419             y = locs[i].y;
2420
2421             memcpy(grid2, grid, area);
2422             ncoords = symmetries(params, x, y, coords, params->symm);
2423             for (j = 0; j < ncoords; j++)
2424                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
2425
2426             ret = solver(cr, blocks, params->xtype, grid2, maxdiff);
2427             if (ret <= maxdiff) {
2428                 for (j = 0; j < ncoords; j++)
2429                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
2430             }
2431         }
2432
2433         memcpy(grid2, grid, area);
2434         
2435         if (solver(cr, blocks, params->xtype, grid2, maxdiff) == maxdiff)
2436             break;                     /* found one! */
2437     }
2438
2439     sfree(grid2);
2440     sfree(locs);
2441
2442     /*
2443      * Now we have the grid as it will be presented to the user.
2444      * Encode it in a game desc.
2445      */
2446     {
2447         char *p;
2448         int run, i;
2449
2450         desc = snewn(7 * area, char);
2451         p = desc;
2452         run = 0;
2453         for (i = 0; i <= area; i++) {
2454             int n = (i < area ? grid[i] : -1);
2455
2456             if (!n)
2457                 run++;
2458             else {
2459                 if (run) {
2460                     while (run > 0) {
2461                         int c = 'a' - 1 + run;
2462                         if (run > 26)
2463                             c = 'z';
2464                         *p++ = c;
2465                         run -= c - ('a' - 1);
2466                     }
2467                 } else {
2468                     /*
2469                      * If there's a number in the very top left or
2470                      * bottom right, there's no point putting an
2471                      * unnecessary _ before or after it.
2472                      */
2473                     if (p > desc && n > 0)
2474                         *p++ = '_';
2475                 }
2476                 if (n > 0)
2477                     p += sprintf(p, "%d", n);
2478                 run = 0;
2479             }
2480         }
2481
2482         if (r == 1) {
2483             int currrun = 0;
2484
2485             *p++ = ',';
2486
2487             /*
2488              * Encode the block structure. We do this by encoding
2489              * the pattern of dividing lines: first we iterate
2490              * over the cr*(cr-1) internal vertical grid lines in
2491              * ordinary reading order, then over the cr*(cr-1)
2492              * internal horizontal ones in transposed reading
2493              * order.
2494              * 
2495              * We encode the number of non-lines between the
2496              * lines; _ means zero (two adjacent divisions), a
2497              * means 1, ..., y means 25, and z means 25 non-lines
2498              * _and no following line_ (so that za means 26, zb 27
2499              * etc).
2500              */
2501             for (i = 0; i <= 2*cr*(cr-1); i++) {
2502                 int p0, p1, edge;
2503
2504                 if (i == 2*cr*(cr-1)) {
2505                     edge = TRUE;       /* terminating virtual edge */
2506                 } else {
2507                     if (i < cr*(cr-1)) {
2508                         y = i/(cr-1);
2509                         x = i%(cr-1);
2510                         p0 = y*cr+x;
2511                         p1 = y*cr+x+1;
2512                     } else {
2513                         x = i/(cr-1) - cr;
2514                         y = i%(cr-1);
2515                         p0 = y*cr+x;
2516                         p1 = (y+1)*cr+x;
2517                     }
2518                     edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
2519                 }
2520
2521                 if (edge) {
2522                     while (currrun > 25)
2523                         *p++ = 'z', currrun -= 25;
2524                     if (currrun)
2525                         *p++ = 'a'-1 + currrun;
2526                     else
2527                         *p++ = '_';
2528                     currrun = 0;
2529                 } else
2530                     currrun++;
2531             }
2532         }
2533
2534         assert(p - desc < 7 * area);
2535         *p++ = '\0';
2536         desc = sresize(desc, p - desc, char);
2537     }
2538
2539     sfree(grid);
2540
2541     return desc;
2542 }
2543
2544 static char *validate_desc(game_params *params, char *desc)
2545 {
2546     int cr = params->c * params->r, area = cr*cr;
2547     int squares = 0;
2548     int *dsf;
2549
2550     while (*desc && *desc != ',') {
2551         int n = *desc++;
2552         if (n >= 'a' && n <= 'z') {
2553             squares += n - 'a' + 1;
2554         } else if (n == '_') {
2555             /* do nothing */;
2556         } else if (n > '0' && n <= '9') {
2557             int val = atoi(desc-1);
2558             if (val < 1 || val > params->c * params->r)
2559                 return "Out-of-range number in game description";
2560             squares++;
2561             while (*desc >= '0' && *desc <= '9')
2562                 desc++;
2563         } else
2564             return "Invalid character in game description";
2565     }
2566
2567     if (squares < area)
2568         return "Not enough data to fill grid";
2569
2570     if (squares > area)
2571         return "Too much data to fit in grid";
2572
2573     if (params->r == 1) {
2574         /*
2575          * Now we expect a suffix giving the jigsaw block
2576          * structure. Parse it and validate that it divides the
2577          * grid into the right number of regions which are the
2578          * right size.
2579          */
2580         if (*desc != ',')
2581             return "Expected jigsaw block structure in game description";
2582         int pos = 0;
2583
2584         dsf = snew_dsf(area);
2585         desc++;
2586
2587         while (*desc) {
2588             int c, adv;
2589
2590             if (*desc == '_')
2591                 c = 0;
2592             else if (*desc >= 'a' && *desc <= 'z')
2593                 c = *desc - 'a' + 1;
2594             else {
2595                 sfree(dsf);
2596                 return "Invalid character in game description";
2597             }
2598             desc++;
2599
2600             adv = (c != 25);           /* 'z' is a special case */
2601
2602             while (c-- > 0) {
2603                 int p0, p1;
2604
2605                 /*
2606                  * Non-edge; merge the two dsf classes on either
2607                  * side of it.
2608                  */
2609                 if (pos >= 2*cr*(cr-1)) {
2610                     sfree(dsf);
2611                     return "Too much data in block structure specification";
2612                 } else if (pos < cr*(cr-1)) {
2613                     int y = pos/(cr-1);
2614                     int x = pos%(cr-1);
2615                     p0 = y*cr+x;
2616                     p1 = y*cr+x+1;
2617                 } else {
2618                     int x = pos/(cr-1) - cr;
2619                     int y = pos%(cr-1);
2620                     p0 = y*cr+x;
2621                     p1 = (y+1)*cr+x;
2622                 }
2623                 dsf_merge(dsf, p0, p1);
2624
2625                 pos++;
2626             }
2627             if (adv)
2628                 pos++;
2629         }
2630
2631         /*
2632          * When desc is exhausted, we expect to have gone exactly
2633          * one space _past_ the end of the grid, due to the dummy
2634          * edge at the end.
2635          */
2636         if (pos != 2*cr*(cr-1)+1) {
2637             sfree(dsf);
2638             return "Not enough data in block structure specification";
2639         }
2640
2641         /*
2642          * Now we've got our dsf. Verify that it matches
2643          * expectations.
2644          */
2645         {
2646             int *canons, *counts;
2647             int i, j, c, ncanons = 0;
2648
2649             canons = snewn(cr, int);
2650             counts = snewn(cr, int);
2651
2652             for (i = 0; i < area; i++) {
2653                 j = dsf_canonify(dsf, i);
2654
2655                 for (c = 0; c < ncanons; c++)
2656                     if (canons[c] == j) {
2657                         counts[c]++;
2658                         if (counts[c] > cr) {
2659                             sfree(dsf);
2660                             sfree(canons);
2661                             sfree(counts);
2662                             return "A jigsaw block is too big";
2663                         }
2664                         break;
2665                     }
2666
2667                 if (c == ncanons) {
2668                     if (ncanons >= cr) {
2669                         sfree(dsf);
2670                         sfree(canons);
2671                         sfree(counts);
2672                         return "Too many distinct jigsaw blocks";
2673                     }
2674                     canons[ncanons] = j;
2675                     counts[ncanons] = 1;
2676                     ncanons++;
2677                 }
2678             }
2679
2680             /*
2681              * If we've managed to get through that loop without
2682              * tripping either of the error conditions, then we
2683              * must have partitioned the entire grid into at most
2684              * cr blocks of at most cr squares each; therefore we
2685              * must have _exactly_ cr blocks of _exactly_ cr
2686              * squares each. I'll verify that by assertion just in
2687              * case something has gone horribly wrong, but it
2688              * shouldn't have been able to happen by duff input,
2689              * only by a bug in the above code.
2690              */
2691             assert(ncanons == cr);
2692             for (c = 0; c < ncanons; c++)
2693                 assert(counts[c] == cr);
2694
2695             sfree(canons);
2696             sfree(counts);
2697         }
2698
2699         sfree(dsf);
2700     } else {
2701         if (*desc)
2702             return "Unexpected jigsaw block structure in game description";
2703     }
2704
2705     return NULL;
2706 }
2707
2708 static game_state *new_game(midend *me, game_params *params, char *desc)
2709 {
2710     game_state *state = snew(game_state);
2711     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2712     int i;
2713
2714     state->cr = cr;
2715     state->xtype = params->xtype;
2716
2717     state->grid = snewn(area, digit);
2718     state->pencil = snewn(area * cr, unsigned char);
2719     memset(state->pencil, 0, area * cr);
2720     state->immutable = snewn(area, unsigned char);
2721     memset(state->immutable, FALSE, area);
2722
2723     state->blocks = snew(struct block_structure);
2724     state->blocks->c = c; state->blocks->r = r;
2725     state->blocks->refcount = 1;
2726     state->blocks->whichblock = snewn(area*2, int);
2727     state->blocks->blocks = snewn(cr, int *);
2728     for (i = 0; i < cr; i++)
2729         state->blocks->blocks[i] = state->blocks->whichblock + area + i*cr;
2730 #ifdef STANDALONE_SOLVER
2731     state->blocks->blocknames = (char **)smalloc(cr*(sizeof(char *)+80));
2732 #endif
2733
2734     state->completed = state->cheated = FALSE;
2735
2736     i = 0;
2737     while (*desc && *desc != ',') {
2738         int n = *desc++;
2739         if (n >= 'a' && n <= 'z') {
2740             int run = n - 'a' + 1;
2741             assert(i + run <= area);
2742             while (run-- > 0)
2743                 state->grid[i++] = 0;
2744         } else if (n == '_') {
2745             /* do nothing */;
2746         } else if (n > '0' && n <= '9') {
2747             assert(i < area);
2748             state->immutable[i] = TRUE;
2749             state->grid[i++] = atoi(desc-1);
2750             while (*desc >= '0' && *desc <= '9')
2751                 desc++;
2752         } else {
2753             assert(!"We can't get here");
2754         }
2755     }
2756     assert(i == area);
2757
2758     if (r == 1) {
2759         int pos = 0;
2760         int *dsf;
2761         int nb;
2762
2763         assert(*desc == ',');
2764
2765         dsf = snew_dsf(area);
2766         desc++;
2767
2768         while (*desc) {
2769             int c, adv;
2770
2771             if (*desc == '_')
2772                 c = 0;
2773             else if (*desc >= 'a' && *desc <= 'z')
2774                 c = *desc - 'a' + 1;
2775             else
2776                 assert(!"Shouldn't get here");
2777             desc++;
2778
2779             adv = (c != 25);           /* 'z' is a special case */
2780
2781             while (c-- > 0) {
2782                 int p0, p1;
2783
2784                 /*
2785                  * Non-edge; merge the two dsf classes on either
2786                  * side of it.
2787                  */
2788                 assert(pos < 2*cr*(cr-1));
2789                 if (pos < cr*(cr-1)) {
2790                     int y = pos/(cr-1);
2791                     int x = pos%(cr-1);
2792                     p0 = y*cr+x;
2793                     p1 = y*cr+x+1;
2794                 } else {
2795                     int x = pos/(cr-1) - cr;
2796                     int y = pos%(cr-1);
2797                     p0 = y*cr+x;
2798                     p1 = (y+1)*cr+x;
2799                 }
2800                 dsf_merge(dsf, p0, p1);
2801
2802                 pos++;
2803             }
2804             if (adv)
2805                 pos++;
2806         }
2807
2808         /*
2809          * When desc is exhausted, we expect to have gone exactly
2810          * one space _past_ the end of the grid, due to the dummy
2811          * edge at the end.
2812          */
2813         assert(pos == 2*cr*(cr-1)+1);
2814
2815         /*
2816          * Now we've got our dsf. Translate it into a block
2817          * structure.
2818          */
2819         nb = 0;
2820         for (i = 0; i < area; i++)
2821             state->blocks->whichblock[i] = -1;
2822         for (i = 0; i < area; i++) {
2823             int j = dsf_canonify(dsf, i);
2824             if (state->blocks->whichblock[j] < 0)
2825                 state->blocks->whichblock[j] = nb++;
2826             state->blocks->whichblock[i] = state->blocks->whichblock[j];
2827         }
2828         assert(nb == cr);
2829
2830         sfree(dsf);
2831     } else {
2832         int x, y;
2833
2834         assert(!*desc);
2835
2836         for (y = 0; y < cr; y++)
2837             for (x = 0; x < cr; x++)
2838                 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2839     }
2840
2841     /*
2842      * Having sorted out whichblock[], set up the block index arrays.
2843      */
2844     for (i = 0; i < cr; i++)
2845         state->blocks->blocks[i][cr-1] = 0;
2846     for (i = 0; i < area; i++) {
2847         int b = state->blocks->whichblock[i];
2848         int j = state->blocks->blocks[b][cr-1]++;
2849         assert(j < cr);
2850         state->blocks->blocks[b][j] = i;
2851     }
2852
2853 #ifdef STANDALONE_SOLVER
2854     /*
2855      * Set up the block names for solver diagnostic output.
2856      */
2857     {
2858         char *p = (char *)(state->blocks->blocknames + cr);
2859
2860         if (r == 1) {
2861             for (i = 0; i < cr; i++)
2862                 state->blocks->blocknames[i] = NULL;
2863
2864             for (i = 0; i < area; i++) {
2865                 int j = state->blocks->whichblock[i];
2866                 if (!state->blocks->blocknames[j]) {
2867                     state->blocks->blocknames[j] = p;
2868                     p += 1 + sprintf(p, "starting at (%d,%d)",
2869                                      1 + i%cr, 1 + i/cr);
2870                 }
2871             }
2872         } else {
2873             int bx, by;
2874             for (by = 0; by < r; by++)
2875                 for (bx = 0; bx < c; bx++) {
2876                     state->blocks->blocknames[by*c+bx] = p;
2877                     p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
2878                 }
2879         }
2880         assert(p - (char *)state->blocks->blocknames < cr*(sizeof(char *)+80));
2881         for (i = 0; i < cr; i++)
2882             assert(state->blocks->blocknames[i]);
2883     }
2884 #endif
2885
2886     return state;
2887 }
2888
2889 static game_state *dup_game(game_state *state)
2890 {
2891     game_state *ret = snew(game_state);
2892     int cr = state->cr, area = cr * cr;
2893
2894     ret->cr = state->cr;
2895     ret->xtype = state->xtype;
2896
2897     ret->blocks = state->blocks;
2898     ret->blocks->refcount++;
2899
2900     ret->grid = snewn(area, digit);
2901     memcpy(ret->grid, state->grid, area);
2902
2903     ret->pencil = snewn(area * cr, unsigned char);
2904     memcpy(ret->pencil, state->pencil, area * cr);
2905
2906     ret->immutable = snewn(area, unsigned char);
2907     memcpy(ret->immutable, state->immutable, area);
2908
2909     ret->completed = state->completed;
2910     ret->cheated = state->cheated;
2911
2912     return ret;
2913 }
2914
2915 static void free_game(game_state *state)
2916 {
2917     if (--state->blocks->refcount == 0) {
2918         sfree(state->blocks->whichblock);
2919         sfree(state->blocks->blocks);
2920 #ifdef STANDALONE_SOLVER
2921         sfree(state->blocks->blocknames);
2922 #endif
2923         sfree(state->blocks);
2924     }
2925     sfree(state->immutable);
2926     sfree(state->pencil);
2927     sfree(state->grid);
2928     sfree(state);
2929 }
2930
2931 static char *solve_game(game_state *state, game_state *currstate,
2932                         char *ai, char **error)
2933 {
2934     int cr = state->cr;
2935     char *ret;
2936     digit *grid;
2937     int solve_ret;
2938
2939     /*
2940      * If we already have the solution in ai, save ourselves some
2941      * time.
2942      */
2943     if (ai)
2944         return dupstr(ai);
2945
2946     grid = snewn(cr*cr, digit);
2947     memcpy(grid, state->grid, cr*cr);
2948     solve_ret = solver(cr, state->blocks, state->xtype, grid, DIFF_RECURSIVE);
2949
2950     *error = NULL;
2951
2952     if (solve_ret == DIFF_IMPOSSIBLE)
2953         *error = "No solution exists for this puzzle";
2954     else if (solve_ret == DIFF_AMBIGUOUS)
2955         *error = "Multiple solutions exist for this puzzle";
2956
2957     if (*error) {
2958         sfree(grid);
2959         return NULL;
2960     }
2961
2962     ret = encode_solve_move(cr, grid);
2963
2964     sfree(grid);
2965
2966     return ret;
2967 }
2968
2969 static char *grid_text_format(int cr, struct block_structure *blocks,
2970                               int xtype, digit *grid)
2971 {
2972     int vmod, hmod;
2973     int x, y;
2974     int totallen, linelen, nlines;
2975     char *ret, *p, ch;
2976
2977     /*
2978      * For non-jigsaw Sudoku, we format in the way we always have,
2979      * by having the digits unevenly spaced so that the dividing
2980      * lines can fit in:
2981      *
2982      * . . | . .
2983      * . . | . .
2984      * ----+----
2985      * . . | . .
2986      * . . | . .
2987      *
2988      * For jigsaw puzzles, however, we must leave space between
2989      * _all_ pairs of digits for an optional dividing line, so we
2990      * have to move to the rather ugly
2991      * 
2992      * .   .   .   .
2993      * ------+------
2994      * .   . | .   .
2995      *       +---+  
2996      * .   . | . | .
2997      * ------+   |  
2998      * .   .   . | .
2999      * 
3000      * We deal with both cases using the same formatting code; we
3001      * simply invent a vmod value such that there's a vertical
3002      * dividing line before column i iff i is divisible by vmod
3003      * (so it's r in the first case and 1 in the second), and hmod
3004      * likewise for horizontal dividing lines.
3005      */
3006
3007     if (blocks->r != 1) {
3008         vmod = blocks->r;
3009         hmod = blocks->c;
3010     } else {
3011         vmod = hmod = 1;
3012     }
3013
3014     /*
3015      * Line length: we have cr digits, each with a space after it,
3016      * and (cr-1)/vmod dividing lines, each with a space after it.
3017      * The final space is replaced by a newline, but that doesn't
3018      * affect the length.
3019      */
3020     linelen = 2*(cr + (cr-1)/vmod);
3021
3022     /*
3023      * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3024      * dividing rows.
3025      */
3026     nlines = cr + (cr-1)/hmod;
3027
3028     /*
3029      * Allocate the space.
3030      */
3031     totallen = linelen * nlines;
3032     ret = snewn(totallen+1, char);     /* leave room for terminating NUL */
3033
3034     /*
3035      * Write the text.
3036      */
3037     p = ret;
3038     for (y = 0; y < cr; y++) {
3039         /*
3040          * Row of digits.
3041          */
3042         for (x = 0; x < cr; x++) {
3043             /*
3044              * Digit.
3045              */
3046             digit d = grid[y*cr+x];
3047
3048             if (d == 0) {
3049                 /*
3050                  * Empty space: we usually write a dot, but we'll
3051                  * highlight spaces on the X-diagonals (in X mode)
3052                  * by using underscores instead.
3053                  */
3054                 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
3055                     ch = '_';
3056                 else
3057                     ch = '.';
3058             } else if (d <= 9) {
3059                 ch = '0' + d;
3060             } else {
3061                 ch = 'a' + d-10;
3062             }
3063
3064             *p++ = ch;
3065             if (x == cr-1) {
3066                 *p++ = '\n';
3067                 continue;
3068             }
3069             *p++ = ' ';
3070
3071             if ((x+1) % vmod)
3072                 continue;
3073
3074             /*
3075              * Optional dividing line.
3076              */
3077             if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
3078                 ch = '|';
3079             else
3080                 ch = ' ';
3081             *p++ = ch;
3082             *p++ = ' ';
3083         }
3084         if (y == cr-1 || (y+1) % hmod)
3085             continue;
3086
3087         /*
3088          * Dividing row.
3089          */
3090         for (x = 0; x < cr; x++) {
3091             int dwid;
3092             int tl, tr, bl, br;
3093
3094             /*
3095              * Division between two squares. This varies
3096              * complicatedly in length.
3097              */
3098             dwid = 2;                  /* digit and its following space */
3099             if (x == cr-1)
3100                 dwid--;                /* no following space at end of line */
3101             if (x > 0 && x % vmod == 0)
3102                 dwid++;                /* preceding space after a divider */
3103
3104             if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
3105                 ch = '-';
3106             else
3107                 ch = ' ';
3108
3109             while (dwid-- > 0)
3110                 *p++ = ch;
3111
3112             if (x == cr-1) {
3113                 *p++ = '\n';
3114                 break;
3115             }
3116
3117             if ((x+1) % vmod)
3118                 continue;
3119
3120             /*
3121              * Corner square. This is:
3122              *  - a space if all four surrounding squares are in
3123              *    the same block
3124              *  - a vertical line if the two left ones are in one
3125              *    block and the two right in another
3126              *  - a horizontal line if the two top ones are in one
3127              *    block and the two bottom in another
3128              *  - a plus sign in all other cases. (If we had a
3129              *    richer character set available we could break
3130              *    this case up further by doing fun things with
3131              *    line-drawing T-pieces.)
3132              */
3133             tl = blocks->whichblock[y*cr+x];
3134             tr = blocks->whichblock[y*cr+x+1];
3135             bl = blocks->whichblock[(y+1)*cr+x];
3136             br = blocks->whichblock[(y+1)*cr+x+1];
3137
3138             if (tl == tr && tr == bl && bl == br)
3139                 ch = ' ';
3140             else if (tl == bl && tr == br)
3141                 ch = '|';
3142             else if (tl == tr && bl == br)
3143                 ch = '-';
3144             else
3145                 ch = '+';
3146
3147             *p++ = ch;
3148         }
3149     }
3150
3151     assert(p - ret == totallen);
3152     *p = '\0';
3153     return ret;
3154 }
3155
3156 static char *game_text_format(game_state *state)
3157 {
3158     return grid_text_format(state->cr, state->blocks, state->xtype,
3159                             state->grid);
3160 }
3161
3162 struct game_ui {
3163     /*
3164      * These are the coordinates of the currently highlighted
3165      * square on the grid, or -1,-1 if there isn't one. When there
3166      * is, pressing a valid number or letter key or Space will
3167      * enter that number or letter in the grid.
3168      */
3169     int hx, hy;
3170     /*
3171      * This indicates whether the current highlight is a
3172      * pencil-mark one or a real one.
3173      */
3174     int hpencil;
3175 };
3176
3177 static game_ui *new_ui(game_state *state)
3178 {
3179     game_ui *ui = snew(game_ui);
3180
3181     ui->hx = ui->hy = -1;
3182     ui->hpencil = 0;
3183
3184     return ui;
3185 }
3186
3187 static void free_ui(game_ui *ui)
3188 {
3189     sfree(ui);
3190 }
3191
3192 static char *encode_ui(game_ui *ui)
3193 {
3194     return NULL;
3195 }
3196
3197 static void decode_ui(game_ui *ui, char *encoding)
3198 {
3199 }
3200
3201 static void game_changed_state(game_ui *ui, game_state *oldstate,
3202                                game_state *newstate)
3203 {
3204     int cr = newstate->cr;
3205     /*
3206      * We prevent pencil-mode highlighting of a filled square. So
3207      * if the user has just filled in a square which we had a
3208      * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3209      * then we cancel the highlight.
3210      */
3211     if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
3212         newstate->grid[ui->hy * cr + ui->hx] != 0) {
3213         ui->hx = ui->hy = -1;
3214     }
3215 }
3216
3217 struct game_drawstate {
3218     int started;
3219     int cr, xtype;
3220     int tilesize;
3221     digit *grid;
3222     unsigned char *pencil;
3223     unsigned char *hl;
3224     /* This is scratch space used within a single call to game_redraw. */
3225     int *entered_items;
3226 };
3227
3228 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3229                             int x, int y, int button)
3230 {
3231     int cr = state->cr;
3232     int tx, ty;
3233     char buf[80];
3234
3235     button &= ~MOD_MASK;
3236
3237     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3238     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3239
3240     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
3241         if (button == LEFT_BUTTON) {
3242             if (state->immutable[ty*cr+tx]) {
3243                 ui->hx = ui->hy = -1;
3244             } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
3245                 ui->hx = ui->hy = -1;
3246             } else {
3247                 ui->hx = tx;
3248                 ui->hy = ty;
3249                 ui->hpencil = 0;
3250             }
3251             return "";                 /* UI activity occurred */
3252         }
3253         if (button == RIGHT_BUTTON) {
3254             /*
3255              * Pencil-mode highlighting for non filled squares.
3256              */
3257             if (state->grid[ty*cr+tx] == 0) {
3258                 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
3259                     ui->hx = ui->hy = -1;
3260                 } else {
3261                     ui->hpencil = 1;
3262                     ui->hx = tx;
3263                     ui->hy = ty;
3264                 }
3265             } else {
3266                 ui->hx = ui->hy = -1;
3267             }
3268             return "";                 /* UI activity occurred */
3269         }
3270     }
3271
3272     if (ui->hx != -1 && ui->hy != -1 &&
3273         ((button >= '1' && button <= '9' && button - '0' <= cr) ||
3274          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
3275          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
3276          button == ' ' || button == '\010' || button == '\177')) {
3277         int n = button - '0';
3278         if (button >= 'A' && button <= 'Z')
3279             n = button - 'A' + 10;
3280         if (button >= 'a' && button <= 'z')
3281             n = button - 'a' + 10;
3282         if (button == ' ' || button == '\010' || button == '\177')
3283             n = 0;
3284
3285         /*
3286          * Can't overwrite this square. In principle this shouldn't
3287          * happen anyway because we should never have even been
3288          * able to highlight the square, but it never hurts to be
3289          * careful.
3290          */
3291         if (state->immutable[ui->hy*cr+ui->hx])
3292             return NULL;
3293
3294         /*
3295          * Can't make pencil marks in a filled square. In principle
3296          * this shouldn't happen anyway because we should never
3297          * have even been able to pencil-highlight the square, but
3298          * it never hurts to be careful.
3299          */
3300         if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
3301             return NULL;
3302
3303         sprintf(buf, "%c%d,%d,%d",
3304                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
3305
3306         ui->hx = ui->hy = -1;
3307
3308         return dupstr(buf);
3309     }
3310
3311     return NULL;
3312 }
3313
3314 static game_state *execute_move(game_state *from, char *move)
3315 {
3316     int cr = from->cr;
3317     game_state *ret;
3318     int x, y, n;
3319
3320     if (move[0] == 'S') {
3321         char *p;
3322
3323         ret = dup_game(from);
3324         ret->completed = ret->cheated = TRUE;
3325
3326         p = move+1;
3327         for (n = 0; n < cr*cr; n++) {
3328             ret->grid[n] = atoi(p);
3329
3330             if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
3331                 free_game(ret);
3332                 return NULL;
3333             }
3334
3335             while (*p && isdigit((unsigned char)*p)) p++;
3336             if (*p == ',') p++;
3337         }
3338
3339         return ret;
3340     } else if ((move[0] == 'P' || move[0] == 'R') &&
3341         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
3342         x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
3343
3344         ret = dup_game(from);
3345         if (move[0] == 'P' && n > 0) {
3346             int index = (y*cr+x) * cr + (n-1);
3347             ret->pencil[index] = !ret->pencil[index];
3348         } else {
3349             ret->grid[y*cr+x] = n;
3350             memset(ret->pencil + (y*cr+x)*cr, 0, cr);
3351
3352             /*
3353              * We've made a real change to the grid. Check to see
3354              * if the game has been completed.
3355              */
3356             if (!ret->completed && check_valid(cr, ret->blocks, ret->xtype,
3357                                                ret->grid)) {
3358                 ret->completed = TRUE;
3359             }
3360         }
3361         return ret;
3362     } else
3363         return NULL;                   /* couldn't parse move string */
3364 }
3365
3366 /* ----------------------------------------------------------------------
3367  * Drawing routines.
3368  */
3369
3370 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3371 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3372
3373 static void game_compute_size(game_params *params, int tilesize,
3374                               int *x, int *y)
3375 {
3376     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3377     struct { int tilesize; } ads, *ds = &ads;
3378     ads.tilesize = tilesize;
3379
3380     *x = SIZE(params->c * params->r);
3381     *y = SIZE(params->c * params->r);
3382 }
3383
3384 static void game_set_size(drawing *dr, game_drawstate *ds,
3385                           game_params *params, int tilesize)
3386 {
3387     ds->tilesize = tilesize;
3388 }
3389
3390 static float *game_colours(frontend *fe, int *ncolours)
3391 {
3392     float *ret = snewn(3 * NCOLOURS, float);
3393
3394     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
3395
3396     ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
3397     ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
3398     ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
3399
3400     ret[COL_GRID * 3 + 0] = 0.0F;
3401     ret[COL_GRID * 3 + 1] = 0.0F;
3402     ret[COL_GRID * 3 + 2] = 0.0F;
3403
3404     ret[COL_CLUE * 3 + 0] = 0.0F;
3405     ret[COL_CLUE * 3 + 1] = 0.0F;
3406     ret[COL_CLUE * 3 + 2] = 0.0F;
3407
3408     ret[COL_USER * 3 + 0] = 0.0F;
3409     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
3410     ret[COL_USER * 3 + 2] = 0.0F;
3411
3412     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
3413     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
3414     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
3415
3416     ret[COL_ERROR * 3 + 0] = 1.0F;
3417     ret[COL_ERROR * 3 + 1] = 0.0F;
3418     ret[COL_ERROR * 3 + 2] = 0.0F;
3419
3420     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
3421     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
3422     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
3423
3424     *ncolours = NCOLOURS;
3425     return ret;
3426 }
3427
3428 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
3429 {
3430     struct game_drawstate *ds = snew(struct game_drawstate);
3431     int cr = state->cr;
3432
3433     ds->started = FALSE;
3434     ds->cr = cr;
3435     ds->xtype = state->xtype;
3436     ds->grid = snewn(cr*cr, digit);
3437     memset(ds->grid, cr+2, cr*cr);
3438     ds->pencil = snewn(cr*cr*cr, digit);
3439     memset(ds->pencil, 0, cr*cr*cr);
3440     ds->hl = snewn(cr*cr, unsigned char);
3441     memset(ds->hl, 0, cr*cr);
3442     ds->entered_items = snewn(cr*cr, int);
3443     ds->tilesize = 0;                  /* not decided yet */
3444     return ds;
3445 }
3446
3447 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3448 {
3449     sfree(ds->hl);
3450     sfree(ds->pencil);
3451     sfree(ds->grid);
3452     sfree(ds->entered_items);
3453     sfree(ds);
3454 }
3455
3456 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
3457                         int x, int y, int hl)
3458 {
3459     int cr = state->cr;
3460     int tx, ty;
3461     int cx, cy, cw, ch;
3462     char str[2];
3463
3464     if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
3465         ds->hl[y*cr+x] == hl &&
3466         !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
3467         return;                        /* no change required */
3468
3469     tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
3470     ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
3471
3472     cx = tx;
3473     cy = ty;
3474     cw = TILE_SIZE-1-2*GRIDEXTRA;
3475     ch = TILE_SIZE-1-2*GRIDEXTRA;
3476
3477     if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
3478         cx -= GRIDEXTRA, cw += GRIDEXTRA;
3479     if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
3480         cw += GRIDEXTRA;
3481     if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
3482         cy -= GRIDEXTRA, ch += GRIDEXTRA;
3483     if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
3484         ch += GRIDEXTRA;
3485
3486     clip(dr, cx, cy, cw, ch);
3487
3488     /* background needs erasing */
3489     draw_rect(dr, cx, cy, cw, ch,
3490               ((hl & 15) == 1 ? COL_HIGHLIGHT :
3491                (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
3492                COL_BACKGROUND));
3493
3494     /*
3495      * Draw the corners of thick lines in corner-adjacent squares,
3496      * which jut into this square by one pixel.
3497      */
3498     if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
3499         draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3500     if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
3501         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3502     if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
3503         draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3504     if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
3505         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3506
3507     /* pencil-mode highlight */
3508     if ((hl & 15) == 2) {
3509         int coords[6];
3510         coords[0] = cx;
3511         coords[1] = cy;
3512         coords[2] = cx+cw/2;
3513         coords[3] = cy;
3514         coords[4] = cx;
3515         coords[5] = cy+ch/2;
3516         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
3517     }
3518
3519     /* new number needs drawing? */
3520     if (state->grid[y*cr+x]) {
3521         str[1] = '\0';
3522         str[0] = state->grid[y*cr+x] + '0';
3523         if (str[0] > '9')
3524             str[0] += 'a' - ('9'+1);
3525         draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
3526                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
3527                   state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
3528     } else {
3529         int i, j, npencil;
3530         int pw, ph, pmax, fontsize;
3531
3532         /* count the pencil marks required */
3533         for (i = npencil = 0; i < cr; i++)
3534             if (state->pencil[(y*cr+x)*cr+i])
3535                 npencil++;
3536
3537         /*
3538          * It's not sensible to arrange pencil marks in the same
3539          * layout as the squares within a block, because this leads
3540          * to the font being too small. Instead, we arrange pencil
3541          * marks in the nearest thing we can to a square layout,
3542          * and we adjust the square layout depending on the number
3543          * of pencil marks in the square.
3544          */
3545         for (pw = 1; pw * pw < npencil; pw++);
3546         if (pw < 3) pw = 3;            /* otherwise it just looks _silly_ */
3547         ph = (npencil + pw - 1) / pw;
3548         if (ph < 2) ph = 2;            /* likewise */
3549         pmax = max(pw, ph);
3550         fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
3551
3552         for (i = j = 0; i < cr; i++)
3553             if (state->pencil[(y*cr+x)*cr+i]) {
3554                 int dx = j % pw, dy = j / pw;
3555
3556                 str[1] = '\0';
3557                 str[0] = i + '1';
3558                 if (str[0] > '9')
3559                     str[0] += 'a' - ('9'+1);
3560                 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
3561                           ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
3562                           FONT_VARIABLE, fontsize,
3563                           ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
3564                 j++;
3565             }
3566     }
3567
3568     unclip(dr);
3569
3570     draw_update(dr, cx, cy, cw, ch);
3571
3572     ds->grid[y*cr+x] = state->grid[y*cr+x];
3573     memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
3574     ds->hl[y*cr+x] = hl;
3575 }
3576
3577 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3578                         game_state *state, int dir, game_ui *ui,
3579                         float animtime, float flashtime)
3580 {
3581     int cr = state->cr;
3582     int x, y;
3583
3584     if (!ds->started) {
3585         /*
3586          * The initial contents of the window are not guaranteed
3587          * and can vary with front ends. To be on the safe side,
3588          * all games should start by drawing a big
3589          * background-colour rectangle covering the whole window.
3590          */
3591         draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
3592
3593         /*
3594          * Draw the grid. We draw it as a big thick rectangle of
3595          * COL_GRID initially; individual calls to draw_number()
3596          * will poke the right-shaped holes in it.
3597          */
3598         draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
3599                   cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
3600                   COL_GRID);
3601     }
3602
3603     /*
3604      * This array is used to keep track of rows, columns and boxes
3605      * which contain a number more than once.
3606      */
3607     for (x = 0; x < cr * cr; x++)
3608         ds->entered_items[x] = 0;
3609     for (x = 0; x < cr; x++)
3610         for (y = 0; y < cr; y++) {
3611             digit d = state->grid[y*cr+x];
3612             if (d) {
3613                 int box = state->blocks->whichblock[y*cr+x];
3614                 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
3615                 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
3616                 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
3617                 if (ds->xtype) {
3618                     if (ondiag0(y*cr+x))
3619                         ds->entered_items[d-1] |= ((ds->entered_items[d-1] & 64) << 1) | 64;
3620                     if (ondiag1(y*cr+x))
3621                         ds->entered_items[cr+d-1] |= ((ds->entered_items[cr+d-1] & 64) << 1) | 64;
3622                 }
3623             }
3624         }
3625
3626     /*
3627      * Draw any numbers which need redrawing.
3628      */
3629     for (x = 0; x < cr; x++) {
3630         for (y = 0; y < cr; y++) {
3631             int highlight = 0;
3632             digit d = state->grid[y*cr+x];
3633
3634             if (flashtime > 0 &&
3635                 (flashtime <= FLASH_TIME/3 ||
3636                  flashtime >= FLASH_TIME*2/3))
3637                 highlight = 1;
3638
3639             /* Highlight active input areas. */
3640             if (x == ui->hx && y == ui->hy)
3641                 highlight = ui->hpencil ? 2 : 1;
3642
3643             /* Mark obvious errors (ie, numbers which occur more than once
3644              * in a single row, column, or box). */
3645             if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
3646                       (ds->entered_items[y*cr+d-1] & 8) ||
3647                       (ds->entered_items[state->blocks->whichblock[y*cr+x]*cr+d-1] & 32) ||
3648                       (ds->xtype && ((ondiag0(y*cr+x) && (ds->entered_items[d-1] & 128)) ||
3649                                      (ondiag1(y*cr+x) && (ds->entered_items[cr+d-1] & 128))))))
3650                 highlight |= 16;
3651
3652             draw_number(dr, ds, state, x, y, highlight);
3653         }
3654     }
3655
3656     /*
3657      * Update the _entire_ grid if necessary.
3658      */
3659     if (!ds->started) {
3660         draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
3661         ds->started = TRUE;
3662     }
3663 }
3664
3665 static float game_anim_length(game_state *oldstate, game_state *newstate,
3666                               int dir, game_ui *ui)
3667 {
3668     return 0.0F;
3669 }
3670
3671 static float game_flash_length(game_state *oldstate, game_state *newstate,
3672                                int dir, game_ui *ui)
3673 {
3674     if (!oldstate->completed && newstate->completed &&
3675         !oldstate->cheated && !newstate->cheated)
3676         return FLASH_TIME;
3677     return 0.0F;
3678 }
3679
3680 static int game_timing_state(game_state *state, game_ui *ui)
3681 {
3682     return TRUE;
3683 }
3684
3685 static void game_print_size(game_params *params, float *x, float *y)
3686 {
3687     int pw, ph;
3688
3689     /*
3690      * I'll use 9mm squares by default. They should be quite big
3691      * for this game, because players will want to jot down no end
3692      * of pencil marks in the squares.
3693      */
3694     game_compute_size(params, 900, &pw, &ph);
3695     *x = pw / 100.0;
3696     *y = ph / 100.0;
3697 }
3698
3699 static void game_print(drawing *dr, game_state *state, int tilesize)
3700 {
3701     int cr = state->cr;
3702     int ink = print_mono_colour(dr, 0);
3703     int x, y;
3704
3705     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3706     game_drawstate ads, *ds = &ads;
3707     game_set_size(dr, ds, NULL, tilesize);
3708
3709     /*
3710      * Border.
3711      */
3712     print_line_width(dr, 3 * TILE_SIZE / 40);
3713     draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
3714
3715     /*
3716      * Highlight X-diagonal squares.
3717      */
3718     if (state->xtype) {
3719         int i;
3720         int xhighlight = print_grey_colour(dr, HATCH_SLASH, 0.90F);
3721
3722         for (i = 0; i < cr; i++)
3723             draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
3724                       TILE_SIZE, TILE_SIZE, xhighlight);
3725         for (i = 0; i < cr; i++)
3726             if (i*2 != cr-1)  /* avoid redoing centre square, just for fun */
3727                 draw_rect(dr, BORDER + i*TILE_SIZE,
3728                           BORDER + (cr-1-i)*TILE_SIZE,
3729                           TILE_SIZE, TILE_SIZE, xhighlight);
3730     }
3731
3732     /*
3733      * Main grid.
3734      */
3735     for (x = 1; x < cr; x++) {
3736         print_line_width(dr, TILE_SIZE / 40);
3737         draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
3738                   BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
3739     }
3740     for (y = 1; y < cr; y++) {
3741         print_line_width(dr, TILE_SIZE / 40);
3742         draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
3743                   BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
3744     }
3745
3746     /*
3747      * Thick lines between cells. In order to do this using the
3748      * line-drawing rather than rectangle-drawing API (so as to
3749      * get line thicknesses to scale correctly) and yet have
3750      * correctly mitred joins between lines, we must do this by
3751      * tracing the boundary of each sub-block and drawing it in
3752      * one go as a single polygon.
3753      */
3754     {
3755         int *coords;
3756         int bi, i, n;
3757         int x, y, dx, dy, sx, sy, sdx, sdy;
3758
3759         print_line_width(dr, 3 * TILE_SIZE / 40);
3760
3761         /*
3762          * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3763          * with k unconnected squares, with total perimeter 4k.
3764          * Now repeatedly join two disconnected components
3765          * together into a larger one; every time you do so you
3766          * remove at least two unit edges, and you require k-1 of
3767          * these operations to create a single connected piece, so
3768          * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3769          * afterwards.)
3770          */
3771         coords = snewn(4*cr+4, int);   /* 2k+2 points, 2 coords per point */
3772
3773         /*
3774          * Iterate over all the blocks.
3775          */
3776         for (bi = 0; bi < cr; bi++) {
3777
3778             /*
3779              * For each block, find a starting square within it
3780              * which has a boundary at the left.
3781              */
3782             for (i = 0; i < cr; i++) {
3783                 int j = state->blocks->blocks[bi][i];
3784                 if (j % cr == 0 || state->blocks->whichblock[j-1] != bi)
3785                     break;
3786             }
3787             assert(i < cr); /* every block must have _some_ leftmost square */
3788             x = state->blocks->blocks[bi][i] % cr;
3789             y = state->blocks->blocks[bi][i] / cr;
3790             dx = -1;
3791             dy = 0;
3792
3793             /*
3794              * Now begin tracing round the perimeter. At all
3795              * times, (x,y) describes some square within the
3796              * block, and (x+dx,y+dy) is some adjacent square
3797              * outside it; so the edge between those two squares
3798              * is always an edge of the block.
3799              */
3800             sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
3801             n = 0;
3802             do {
3803                 int cx, cy, tx, ty, nin;
3804
3805                 /*
3806                  * To begin with, record the point at one end of
3807                  * the edge. To do this, we translate (x,y) down
3808                  * and right by half a unit (so they're describing
3809                  * a point in the _centre_ of the square) and then
3810                  * translate back again in a manner rotated by dy
3811                  * and dx.
3812                  */
3813                 assert(n < 2*cr+2);
3814                 cx = ((2*x+1) + dy + dx) / 2;
3815                 cy = ((2*y+1) - dx + dy) / 2;
3816                 coords[2*n+0] = BORDER + cx * TILE_SIZE;
3817                 coords[2*n+1] = BORDER + cy * TILE_SIZE;
3818                 n++;
3819
3820                 /*
3821                  * Now advance to the next edge, by looking at the
3822                  * two squares beyond it. If they're both outside
3823                  * the block, we turn right (by leaving x,y the
3824                  * same and rotating dx,dy clockwise); if they're
3825                  * both inside, we turn left (by rotating dx,dy
3826                  * anticlockwise and contriving to leave x+dx,y+dy
3827                  * unchanged); if one of each, we go straight on
3828                  * (and may enforce by assertion that they're one
3829                  * of each the _right_ way round).
3830                  */
3831                 nin = 0;
3832                 tx = x - dy + dx;
3833                 ty = y + dx + dy;
3834                 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3835                         state->blocks->whichblock[ty*cr+tx] == bi);
3836                 tx = x - dy;
3837                 ty = y + dx;
3838                 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3839                         state->blocks->whichblock[ty*cr+tx] == bi);
3840                 if (nin == 0) {
3841                     /*
3842                      * Turn right.
3843                      */
3844                     int tmp;
3845                     tmp = dx;
3846                     dx = -dy;
3847                     dy = tmp;
3848                 } else if (nin == 2) {
3849                     /*
3850                      * Turn left.
3851                      */
3852                     int tmp;
3853
3854                     x += dx;
3855                     y += dy;
3856                     
3857                     tmp = dx;
3858                     dx = dy;
3859                     dy = -tmp;
3860
3861                     x -= dx;
3862                     y -= dy;
3863                 } else {
3864                     /*
3865                      * Go straight on.
3866                      */
3867                     x -= dy;
3868                     y += dx;
3869                 }
3870
3871                 /*
3872                  * Now enforce by assertion that we ended up
3873                  * somewhere sensible.
3874                  */
3875                 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
3876                        state->blocks->whichblock[y*cr+x] == bi);
3877                 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
3878                        state->blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
3879
3880             } while (x != sx || y != sy || dx != sdx || dy != sdy);
3881
3882             /*
3883              * That's our polygon; now draw it.
3884              */
3885             draw_polygon(dr, coords, n, -1, ink);
3886         }
3887
3888         sfree(coords);
3889     }
3890
3891     /*
3892      * Numbers.
3893      */
3894     for (y = 0; y < cr; y++)
3895         for (x = 0; x < cr; x++)
3896             if (state->grid[y*cr+x]) {
3897                 char str[2];
3898                 str[1] = '\0';
3899                 str[0] = state->grid[y*cr+x] + '0';
3900                 if (str[0] > '9')
3901                     str[0] += 'a' - ('9'+1);
3902                 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
3903                           BORDER + y*TILE_SIZE + TILE_SIZE/2,
3904                           FONT_VARIABLE, TILE_SIZE/2,
3905                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
3906             }
3907 }
3908
3909 #ifdef COMBINED
3910 #define thegame solo
3911 #endif
3912
3913 const struct game thegame = {
3914     "Solo", "games.solo", "solo",
3915     default_params,
3916     game_fetch_preset,
3917     decode_params,
3918     encode_params,
3919     free_params,
3920     dup_params,
3921     TRUE, game_configure, custom_params,
3922     validate_params,
3923     new_game_desc,
3924     validate_desc,
3925     new_game,
3926     dup_game,
3927     free_game,
3928     TRUE, solve_game,
3929     TRUE, game_text_format,
3930     new_ui,
3931     free_ui,
3932     encode_ui,
3933     decode_ui,
3934     game_changed_state,
3935     interpret_move,
3936     execute_move,
3937     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3938     game_colours,
3939     game_new_drawstate,
3940     game_free_drawstate,
3941     game_redraw,
3942     game_anim_length,
3943     game_flash_length,
3944     TRUE, FALSE, game_print_size, game_print,
3945     FALSE,                             /* wants_statusbar */
3946     FALSE, game_timing_state,
3947     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
3948 };
3949
3950 #ifdef STANDALONE_SOLVER
3951
3952 int main(int argc, char **argv)
3953 {
3954     game_params *p;
3955     game_state *s;
3956     char *id = NULL, *desc, *err;
3957     int grade = FALSE;
3958     int ret;
3959
3960     while (--argc > 0) {
3961         char *p = *++argv;
3962         if (!strcmp(p, "-v")) {
3963             solver_show_working = TRUE;
3964         } else if (!strcmp(p, "-g")) {
3965             grade = TRUE;
3966         } else if (*p == '-') {
3967             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3968             return 1;
3969         } else {
3970             id = p;
3971         }
3972     }
3973
3974     if (!id) {
3975         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3976         return 1;
3977     }
3978
3979     desc = strchr(id, ':');
3980     if (!desc) {
3981         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3982         return 1;
3983     }
3984     *desc++ = '\0';
3985
3986     p = default_params();
3987     decode_params(p, id);
3988     err = validate_desc(p, desc);
3989     if (err) {
3990         fprintf(stderr, "%s: %s\n", argv[0], err);
3991         return 1;
3992     }
3993     s = new_game(NULL, p, desc);
3994
3995     ret = solver(s->cr, s->blocks, s->xtype, s->grid, DIFF_RECURSIVE);
3996     if (grade) {
3997         printf("Difficulty rating: %s\n",
3998                ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
3999                ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
4000                ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
4001                ret==DIFF_SET ? "Advanced (set elimination required)":
4002                ret==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
4003                ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
4004                ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
4005                ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
4006                "INTERNAL ERROR: unrecognised difficulty code");
4007     } else {
4008         printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
4009     }
4010
4011     return 0;
4012 }
4013
4014 #endif