chiark / gitweb /
Improvements to filled-grid generation. Introduced a cunning idea
[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 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n,
1901                           int placing)
1902 {
1903     int cr = usage->cr;
1904     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
1905         usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n-1] = placing;
1906     if (usage->diag) {
1907         if (ondiag0(y*cr+x))
1908             usage->diag[n-1] = placing;
1909         if (ondiag1(y*cr+x))
1910             usage->diag[cr+n-1] = placing;
1911     }
1912     usage->grid[y*cr+x] = placing ? n : 0;
1913 }
1914
1915 /*
1916  * The real recursive step in the generating function.
1917  *
1918  * Return values: 1 means solution found, 0 means no solution
1919  * found on this branch.
1920  */
1921 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
1922 {
1923     int cr = usage->cr;
1924     int i, j, n, sx, sy, bestm, bestr, ret;
1925     int *digits;
1926
1927     /*
1928      * Firstly, check for completion! If there are no spaces left
1929      * in the grid, we have a solution.
1930      */
1931     if (usage->nspaces == 0)
1932         return TRUE;
1933
1934     /*
1935      * Next, abandon generation if we went over our steps limit.
1936      */
1937     if (*steps <= 0)
1938         return FALSE;
1939     (*steps)--;
1940
1941     /*
1942      * Otherwise, there must be at least one space. Find the most
1943      * constrained space, using the `r' field as a tie-breaker.
1944      */
1945     bestm = cr+1;                      /* so that any space will beat it */
1946     bestr = 0;
1947     i = sx = sy = -1;
1948     for (j = 0; j < usage->nspaces; j++) {
1949         int x = usage->spaces[j].x, y = usage->spaces[j].y;
1950         int m;
1951
1952         /*
1953          * Find the number of digits that could go in this space.
1954          */
1955         m = 0;
1956         for (n = 0; n < cr; n++)
1957             if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1958                 !usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n] &&
1959                 (!usage->diag || ((!ondiag0(y*cr+x) || !usage->diag[n]) &&
1960                                   (!ondiag1(y*cr+x) || !usage->diag[cr+n]))))
1961                 m++;
1962
1963         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1964             bestm = m;
1965             bestr = usage->spaces[j].r;
1966             sx = x;
1967             sy = y;
1968             i = j;
1969         }
1970     }
1971
1972     /*
1973      * Swap that square into the final place in the spaces array,
1974      * so that decrementing nspaces will remove it from the list.
1975      */
1976     if (i != usage->nspaces-1) {
1977         struct gridgen_coord t;
1978         t = usage->spaces[usage->nspaces-1];
1979         usage->spaces[usage->nspaces-1] = usage->spaces[i];
1980         usage->spaces[i] = t;
1981     }
1982
1983     /*
1984      * Now we've decided which square to start our recursion at,
1985      * simply go through all possible values, shuffling them
1986      * randomly first if necessary.
1987      */
1988     digits = snewn(bestm, int);
1989     j = 0;
1990     for (n = 0; n < cr; n++)
1991         if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1992             !usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n] &&
1993             (!usage->diag || ((!ondiag0(sy*cr+sx) || !usage->diag[n]) &&
1994                               (!ondiag1(sy*cr+sx) || !usage->diag[cr+n])))) {
1995             digits[j++] = n+1;
1996         }
1997
1998     if (usage->rs)
1999         shuffle(digits, j, sizeof(*digits), usage->rs);
2000
2001     /* And finally, go through the digit list and actually recurse. */
2002     ret = FALSE;
2003     for (i = 0; i < j; i++) {
2004         n = digits[i];
2005
2006         /* Update the usage structure to reflect the placing of this digit. */
2007         gridgen_place(usage, sx, sy, n, TRUE);
2008         usage->nspaces--;
2009
2010         /* Call the solver recursively. Stop when we find a solution. */
2011         if (gridgen_real(usage, grid, steps)) {
2012             ret = TRUE;
2013             break;
2014         }
2015
2016         /* Revert the usage structure. */
2017         gridgen_place(usage, sx, sy, n, FALSE);
2018         usage->nspaces++;
2019     }
2020
2021     sfree(digits);
2022     return ret;
2023 }
2024
2025 /*
2026  * Entry point to generator. You give it parameters and a starting
2027  * grid, which is simply an array of cr*cr digits.
2028  */
2029 static int gridgen(int cr, struct block_structure *blocks, int xtype,
2030                    digit *grid, random_state *rs, int maxsteps)
2031 {
2032     struct gridgen_usage *usage;
2033     int x, y, ret;
2034
2035     /*
2036      * Clear the grid to start with.
2037      */
2038     memset(grid, 0, cr*cr);
2039
2040     /*
2041      * Create a gridgen_usage structure.
2042      */
2043     usage = snew(struct gridgen_usage);
2044
2045     usage->cr = cr;
2046     usage->blocks = blocks;
2047
2048     usage->grid = grid;
2049
2050     usage->row = snewn(cr * cr, unsigned char);
2051     usage->col = snewn(cr * cr, unsigned char);
2052     usage->blk = snewn(cr * cr, unsigned char);
2053     memset(usage->row, FALSE, cr * cr);
2054     memset(usage->col, FALSE, cr * cr);
2055     memset(usage->blk, FALSE, cr * cr);
2056
2057     if (xtype) {
2058         usage->diag = snewn(2 * cr, unsigned char);
2059         memset(usage->diag, FALSE, 2 * cr);
2060     } else {
2061         usage->diag = NULL;
2062     }
2063
2064     /*
2065      * Begin by filling in the whole top row with randomly chosen
2066      * numbers. This cannot introduce any bias or restriction on
2067      * the available grids, since we already know those numbers
2068      * are all distinct so all we're doing is choosing their
2069      * labels.
2070      */
2071     for (x = 0; x < cr; x++)
2072         grid[x] = x+1;
2073     shuffle(grid, cr, sizeof(*grid), rs);
2074     for (x = 0; x < cr; x++)
2075         gridgen_place(usage, x, 0, grid[x], TRUE);
2076
2077     usage->spaces = snewn(cr * cr, struct gridgen_coord);
2078     usage->nspaces = 0;
2079
2080     usage->rs = rs;
2081
2082     /*
2083      * Initialise the list of grid spaces, taking care to leave
2084      * out the row I've already filled in above.
2085      */
2086     for (y = 1; y < cr; y++) {
2087         for (x = 0; x < cr; x++) {
2088             usage->spaces[usage->nspaces].x = x;
2089             usage->spaces[usage->nspaces].y = y;
2090             usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2091             usage->nspaces++;
2092         }
2093     }
2094
2095     /*
2096      * Run the real generator function.
2097      */
2098     ret = gridgen_real(usage, grid, &maxsteps);
2099
2100     /*
2101      * Clean up the usage structure now we have our answer.
2102      */
2103     sfree(usage->spaces);
2104     sfree(usage->blk);
2105     sfree(usage->col);
2106     sfree(usage->row);
2107     sfree(usage);
2108
2109     return ret;
2110 }
2111
2112 /* ----------------------------------------------------------------------
2113  * End of grid generator code.
2114  */
2115
2116 /*
2117  * Check whether a grid contains a valid complete puzzle.
2118  */
2119 static int check_valid(int cr, struct block_structure *blocks, int xtype,
2120                        digit *grid)
2121 {
2122     unsigned char *used;
2123     int x, y, i, j, n;
2124
2125     used = snewn(cr, unsigned char);
2126
2127     /*
2128      * Check that each row contains precisely one of everything.
2129      */
2130     for (y = 0; y < cr; y++) {
2131         memset(used, FALSE, cr);
2132         for (x = 0; x < cr; x++)
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 column contains precisely one of everything.
2144      */
2145     for (x = 0; x < cr; x++) {
2146         memset(used, FALSE, cr);
2147         for (y = 0; y < cr; y++)
2148             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2149                 used[grid[y*cr+x]-1] = TRUE;
2150         for (n = 0; n < cr; n++)
2151             if (!used[n]) {
2152                 sfree(used);
2153                 return FALSE;
2154             }
2155     }
2156
2157     /*
2158      * Check that each block contains precisely one of everything.
2159      */
2160     for (i = 0; i < cr; i++) {
2161         memset(used, FALSE, cr);
2162         for (j = 0; j < cr; j++)
2163             if (grid[blocks->blocks[i][j]] > 0 &&
2164                 grid[blocks->blocks[i][j]] <= cr)
2165                 used[grid[blocks->blocks[i][j]]-1] = TRUE;
2166         for (n = 0; n < cr; n++)
2167             if (!used[n]) {
2168                 sfree(used);
2169                 return FALSE;
2170             }
2171     }
2172
2173     /*
2174      * Check that each diagonal contains precisely one of everything.
2175      */
2176     if (xtype) {
2177         memset(used, FALSE, cr);
2178         for (i = 0; i < cr; i++)
2179             if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
2180                 used[grid[diag0(i)]-1] = TRUE;
2181         for (n = 0; n < cr; n++)
2182             if (!used[n]) {
2183                 sfree(used);
2184                 return FALSE;
2185             }
2186         for (i = 0; i < cr; i++)
2187             if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
2188                 used[grid[diag1(i)]-1] = TRUE;
2189         for (n = 0; n < cr; n++)
2190             if (!used[n]) {
2191                 sfree(used);
2192                 return FALSE;
2193             }
2194     }
2195
2196     sfree(used);
2197     return TRUE;
2198 }
2199
2200 static int symmetries(game_params *params, int x, int y, int *output, int s)
2201 {
2202     int c = params->c, r = params->r, cr = c*r;
2203     int i = 0;
2204
2205 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2206
2207     ADD(x, y);
2208
2209     switch (s) {
2210       case SYMM_NONE:
2211         break;                         /* just x,y is all we need */
2212       case SYMM_ROT2:
2213         ADD(cr - 1 - x, cr - 1 - y);
2214         break;
2215       case SYMM_ROT4:
2216         ADD(cr - 1 - y, x);
2217         ADD(y, cr - 1 - x);
2218         ADD(cr - 1 - x, cr - 1 - y);
2219         break;
2220       case SYMM_REF2:
2221         ADD(cr - 1 - x, y);
2222         break;
2223       case SYMM_REF2D:
2224         ADD(y, x);
2225         break;
2226       case SYMM_REF4:
2227         ADD(cr - 1 - x, y);
2228         ADD(x, cr - 1 - y);
2229         ADD(cr - 1 - x, cr - 1 - y);
2230         break;
2231       case SYMM_REF4D:
2232         ADD(y, x);
2233         ADD(cr - 1 - x, cr - 1 - y);
2234         ADD(cr - 1 - y, cr - 1 - x);
2235         break;
2236       case SYMM_REF8:
2237         ADD(cr - 1 - x, y);
2238         ADD(x, cr - 1 - y);
2239         ADD(cr - 1 - x, cr - 1 - y);
2240         ADD(y, x);
2241         ADD(y, cr - 1 - x);
2242         ADD(cr - 1 - y, x);
2243         ADD(cr - 1 - y, cr - 1 - x);
2244         break;
2245     }
2246
2247 #undef ADD
2248
2249     return i;
2250 }
2251
2252 static char *encode_solve_move(int cr, digit *grid)
2253 {
2254     int i, len;
2255     char *ret, *p, *sep;
2256
2257     /*
2258      * It's surprisingly easy to work out _exactly_ how long this
2259      * string needs to be. To decimal-encode all the numbers from 1
2260      * to n:
2261      * 
2262      *  - every number has a units digit; total is n.
2263      *  - all numbers above 9 have a tens digit; total is max(n-9,0).
2264      *  - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2265      *  - and so on.
2266      */
2267     len = 0;
2268     for (i = 1; i <= cr; i *= 10)
2269         len += max(cr - i + 1, 0);
2270     len += cr;                 /* don't forget the commas */
2271     len *= cr;                 /* there are cr rows of these */
2272
2273     /*
2274      * Now len is one bigger than the total size of the
2275      * comma-separated numbers (because we counted an
2276      * additional leading comma). We need to have a leading S
2277      * and a trailing NUL, so we're off by one in total.
2278      */
2279     len++;
2280
2281     ret = snewn(len, char);
2282     p = ret;
2283     *p++ = 'S';
2284     sep = "";
2285     for (i = 0; i < cr*cr; i++) {
2286         p += sprintf(p, "%s%d", sep, grid[i]);
2287         sep = ",";
2288     }
2289     *p++ = '\0';
2290     assert(p - ret == len);
2291
2292     return ret;
2293 }
2294
2295 static char *new_game_desc(game_params *params, random_state *rs,
2296                            char **aux, int interactive)
2297 {
2298     int c = params->c, r = params->r, cr = c*r;
2299     int area = cr*cr;
2300     struct block_structure *blocks;
2301     digit *grid, *grid2;
2302     struct xy { int x, y; } *locs;
2303     int nlocs;
2304     char *desc;
2305     int coords[16], ncoords;
2306     int maxdiff;
2307     int x, y, i, j;
2308
2309     /*
2310      * Adjust the maximum difficulty level to be consistent with
2311      * the puzzle size: all 2x2 puzzles appear to be Trivial
2312      * (DIFF_BLOCK) so we cannot hold out for even a Basic
2313      * (DIFF_SIMPLE) one.
2314      */
2315     maxdiff = params->diff;
2316     if (c == 2 && r == 2)
2317         maxdiff = DIFF_BLOCK;
2318
2319     grid = snewn(area, digit);
2320     locs = snewn(area, struct xy);
2321     grid2 = snewn(area, digit);
2322
2323     blocks = snew(struct block_structure);
2324     blocks->c = params->c; blocks->r = params->r;
2325     blocks->whichblock = snewn(area*2, int);
2326     blocks->blocks = snewn(cr, int *);
2327     for (i = 0; i < cr; i++)
2328         blocks->blocks[i] = blocks->whichblock + area + i*cr;
2329 #ifdef STANDALONE_SOLVER
2330     assert(!"This should never happen, so we don't need to create blocknames");
2331 #endif
2332
2333     /*
2334      * Loop until we get a grid of the required difficulty. This is
2335      * nasty, but it seems to be unpleasantly hard to generate
2336      * difficult grids otherwise.
2337      */
2338     while (1) {
2339         /*
2340          * Generate a random solved state, starting by
2341          * constructing the block structure.
2342          */
2343         if (r == 1) {                  /* jigsaw mode */
2344             int *dsf = divvy_rectangle(cr, cr, cr, rs);
2345             int nb = 0;
2346
2347             for (i = 0; i < area; i++)
2348                 blocks->whichblock[i] = -1;
2349             for (i = 0; i < area; i++) {
2350                 int j = dsf_canonify(dsf, i);
2351                 if (blocks->whichblock[j] < 0)
2352                     blocks->whichblock[j] = nb++;
2353                 blocks->whichblock[i] = blocks->whichblock[j];
2354             }
2355             assert(nb == cr);
2356
2357             sfree(dsf);
2358         } else {                       /* basic Sudoku mode */
2359             for (y = 0; y < cr; y++)
2360                 for (x = 0; x < cr; x++)
2361                     blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2362         }
2363         for (i = 0; i < cr; i++)
2364             blocks->blocks[i][cr-1] = 0;
2365         for (i = 0; i < area; i++) {
2366             int b = blocks->whichblock[i];
2367             j = blocks->blocks[b][cr-1]++;
2368             assert(j < cr);
2369             blocks->blocks[b][j] = i;
2370         }
2371
2372         if (!gridgen(cr, blocks, params->xtype, grid, rs, area*area))
2373             continue;
2374         assert(check_valid(cr, blocks, params->xtype, grid));
2375
2376         /*
2377          * Save the solved grid in aux.
2378          */
2379         {
2380             /*
2381              * We might already have written *aux the last time we
2382              * went round this loop, in which case we should free
2383              * the old aux before overwriting it with the new one.
2384              */
2385             if (*aux) {
2386                 sfree(*aux);
2387             }
2388
2389             *aux = encode_solve_move(cr, grid);
2390         }
2391
2392         /*
2393          * Now we have a solved grid, start removing things from it
2394          * while preserving solubility.
2395          */
2396
2397         /*
2398          * Find the set of equivalence classes of squares permitted
2399          * by the selected symmetry. We do this by enumerating all
2400          * the grid squares which have no symmetric companion
2401          * sorting lower than themselves.
2402          */
2403         nlocs = 0;
2404         for (y = 0; y < cr; y++)
2405             for (x = 0; x < cr; x++) {
2406                 int i = y*cr+x;
2407                 int j;
2408
2409                 ncoords = symmetries(params, x, y, coords, params->symm);
2410                 for (j = 0; j < ncoords; j++)
2411                     if (coords[2*j+1]*cr+coords[2*j] < i)
2412                         break;
2413                 if (j == ncoords) {
2414                     locs[nlocs].x = x;
2415                     locs[nlocs].y = y;
2416                     nlocs++;
2417                 }
2418             }
2419
2420         /*
2421          * Now shuffle that list.
2422          */
2423         shuffle(locs, nlocs, sizeof(*locs), rs);
2424
2425         /*
2426          * Now loop over the shuffled list and, for each element,
2427          * see whether removing that element (and its reflections)
2428          * from the grid will still leave the grid soluble.
2429          */
2430         for (i = 0; i < nlocs; i++) {
2431             int ret;
2432
2433             x = locs[i].x;
2434             y = locs[i].y;
2435
2436             memcpy(grid2, grid, area);
2437             ncoords = symmetries(params, x, y, coords, params->symm);
2438             for (j = 0; j < ncoords; j++)
2439                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
2440
2441             ret = solver(cr, blocks, params->xtype, grid2, maxdiff);
2442             if (ret <= maxdiff) {
2443                 for (j = 0; j < ncoords; j++)
2444                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
2445             }
2446         }
2447
2448         memcpy(grid2, grid, area);
2449         
2450         if (solver(cr, blocks, params->xtype, grid2, maxdiff) == maxdiff)
2451             break;                     /* found one! */
2452     }
2453
2454     sfree(grid2);
2455     sfree(locs);
2456
2457     /*
2458      * Now we have the grid as it will be presented to the user.
2459      * Encode it in a game desc.
2460      */
2461     {
2462         char *p;
2463         int run, i;
2464
2465         desc = snewn(7 * area, char);
2466         p = desc;
2467         run = 0;
2468         for (i = 0; i <= area; i++) {
2469             int n = (i < area ? grid[i] : -1);
2470
2471             if (!n)
2472                 run++;
2473             else {
2474                 if (run) {
2475                     while (run > 0) {
2476                         int c = 'a' - 1 + run;
2477                         if (run > 26)
2478                             c = 'z';
2479                         *p++ = c;
2480                         run -= c - ('a' - 1);
2481                     }
2482                 } else {
2483                     /*
2484                      * If there's a number in the very top left or
2485                      * bottom right, there's no point putting an
2486                      * unnecessary _ before or after it.
2487                      */
2488                     if (p > desc && n > 0)
2489                         *p++ = '_';
2490                 }
2491                 if (n > 0)
2492                     p += sprintf(p, "%d", n);
2493                 run = 0;
2494             }
2495         }
2496
2497         if (r == 1) {
2498             int currrun = 0;
2499
2500             *p++ = ',';
2501
2502             /*
2503              * Encode the block structure. We do this by encoding
2504              * the pattern of dividing lines: first we iterate
2505              * over the cr*(cr-1) internal vertical grid lines in
2506              * ordinary reading order, then over the cr*(cr-1)
2507              * internal horizontal ones in transposed reading
2508              * order.
2509              * 
2510              * We encode the number of non-lines between the
2511              * lines; _ means zero (two adjacent divisions), a
2512              * means 1, ..., y means 25, and z means 25 non-lines
2513              * _and no following line_ (so that za means 26, zb 27
2514              * etc).
2515              */
2516             for (i = 0; i <= 2*cr*(cr-1); i++) {
2517                 int p0, p1, edge;
2518
2519                 if (i == 2*cr*(cr-1)) {
2520                     edge = TRUE;       /* terminating virtual edge */
2521                 } else {
2522                     if (i < cr*(cr-1)) {
2523                         y = i/(cr-1);
2524                         x = i%(cr-1);
2525                         p0 = y*cr+x;
2526                         p1 = y*cr+x+1;
2527                     } else {
2528                         x = i/(cr-1) - cr;
2529                         y = i%(cr-1);
2530                         p0 = y*cr+x;
2531                         p1 = (y+1)*cr+x;
2532                     }
2533                     edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
2534                 }
2535
2536                 if (edge) {
2537                     while (currrun > 25)
2538                         *p++ = 'z', currrun -= 25;
2539                     if (currrun)
2540                         *p++ = 'a'-1 + currrun;
2541                     else
2542                         *p++ = '_';
2543                     currrun = 0;
2544                 } else
2545                     currrun++;
2546             }
2547         }
2548
2549         assert(p - desc < 7 * area);
2550         *p++ = '\0';
2551         desc = sresize(desc, p - desc, char);
2552     }
2553
2554     sfree(grid);
2555
2556     return desc;
2557 }
2558
2559 static char *validate_desc(game_params *params, char *desc)
2560 {
2561     int cr = params->c * params->r, area = cr*cr;
2562     int squares = 0;
2563     int *dsf;
2564
2565     while (*desc && *desc != ',') {
2566         int n = *desc++;
2567         if (n >= 'a' && n <= 'z') {
2568             squares += n - 'a' + 1;
2569         } else if (n == '_') {
2570             /* do nothing */;
2571         } else if (n > '0' && n <= '9') {
2572             int val = atoi(desc-1);
2573             if (val < 1 || val > params->c * params->r)
2574                 return "Out-of-range number in game description";
2575             squares++;
2576             while (*desc >= '0' && *desc <= '9')
2577                 desc++;
2578         } else
2579             return "Invalid character in game description";
2580     }
2581
2582     if (squares < area)
2583         return "Not enough data to fill grid";
2584
2585     if (squares > area)
2586         return "Too much data to fit in grid";
2587
2588     if (params->r == 1) {
2589         int pos;
2590
2591         /*
2592          * Now we expect a suffix giving the jigsaw block
2593          * structure. Parse it and validate that it divides the
2594          * grid into the right number of regions which are the
2595          * right size.
2596          */
2597         if (*desc != ',')
2598             return "Expected jigsaw block structure in game description";
2599         pos = 0;
2600
2601         dsf = snew_dsf(area);
2602         desc++;
2603
2604         while (*desc) {
2605             int c, adv;
2606
2607             if (*desc == '_')
2608                 c = 0;
2609             else if (*desc >= 'a' && *desc <= 'z')
2610                 c = *desc - 'a' + 1;
2611             else {
2612                 sfree(dsf);
2613                 return "Invalid character in game description";
2614             }
2615             desc++;
2616
2617             adv = (c != 25);           /* 'z' is a special case */
2618
2619             while (c-- > 0) {
2620                 int p0, p1;
2621
2622                 /*
2623                  * Non-edge; merge the two dsf classes on either
2624                  * side of it.
2625                  */
2626                 if (pos >= 2*cr*(cr-1)) {
2627                     sfree(dsf);
2628                     return "Too much data in block structure specification";
2629                 } else if (pos < cr*(cr-1)) {
2630                     int y = pos/(cr-1);
2631                     int x = pos%(cr-1);
2632                     p0 = y*cr+x;
2633                     p1 = y*cr+x+1;
2634                 } else {
2635                     int x = pos/(cr-1) - cr;
2636                     int y = pos%(cr-1);
2637                     p0 = y*cr+x;
2638                     p1 = (y+1)*cr+x;
2639                 }
2640                 dsf_merge(dsf, p0, p1);
2641
2642                 pos++;
2643             }
2644             if (adv)
2645                 pos++;
2646         }
2647
2648         /*
2649          * When desc is exhausted, we expect to have gone exactly
2650          * one space _past_ the end of the grid, due to the dummy
2651          * edge at the end.
2652          */
2653         if (pos != 2*cr*(cr-1)+1) {
2654             sfree(dsf);
2655             return "Not enough data in block structure specification";
2656         }
2657
2658         /*
2659          * Now we've got our dsf. Verify that it matches
2660          * expectations.
2661          */
2662         {
2663             int *canons, *counts;
2664             int i, j, c, ncanons = 0;
2665
2666             canons = snewn(cr, int);
2667             counts = snewn(cr, int);
2668
2669             for (i = 0; i < area; i++) {
2670                 j = dsf_canonify(dsf, i);
2671
2672                 for (c = 0; c < ncanons; c++)
2673                     if (canons[c] == j) {
2674                         counts[c]++;
2675                         if (counts[c] > cr) {
2676                             sfree(dsf);
2677                             sfree(canons);
2678                             sfree(counts);
2679                             return "A jigsaw block is too big";
2680                         }
2681                         break;
2682                     }
2683
2684                 if (c == ncanons) {
2685                     if (ncanons >= cr) {
2686                         sfree(dsf);
2687                         sfree(canons);
2688                         sfree(counts);
2689                         return "Too many distinct jigsaw blocks";
2690                     }
2691                     canons[ncanons] = j;
2692                     counts[ncanons] = 1;
2693                     ncanons++;
2694                 }
2695             }
2696
2697             /*
2698              * If we've managed to get through that loop without
2699              * tripping either of the error conditions, then we
2700              * must have partitioned the entire grid into at most
2701              * cr blocks of at most cr squares each; therefore we
2702              * must have _exactly_ cr blocks of _exactly_ cr
2703              * squares each. I'll verify that by assertion just in
2704              * case something has gone horribly wrong, but it
2705              * shouldn't have been able to happen by duff input,
2706              * only by a bug in the above code.
2707              */
2708             assert(ncanons == cr);
2709             for (c = 0; c < ncanons; c++)
2710                 assert(counts[c] == cr);
2711
2712             sfree(canons);
2713             sfree(counts);
2714         }
2715
2716         sfree(dsf);
2717     } else {
2718         if (*desc)
2719             return "Unexpected jigsaw block structure in game description";
2720     }
2721
2722     return NULL;
2723 }
2724
2725 static game_state *new_game(midend *me, game_params *params, char *desc)
2726 {
2727     game_state *state = snew(game_state);
2728     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2729     int i;
2730
2731     state->cr = cr;
2732     state->xtype = params->xtype;
2733
2734     state->grid = snewn(area, digit);
2735     state->pencil = snewn(area * cr, unsigned char);
2736     memset(state->pencil, 0, area * cr);
2737     state->immutable = snewn(area, unsigned char);
2738     memset(state->immutable, FALSE, area);
2739
2740     state->blocks = snew(struct block_structure);
2741     state->blocks->c = c; state->blocks->r = r;
2742     state->blocks->refcount = 1;
2743     state->blocks->whichblock = snewn(area*2, int);
2744     state->blocks->blocks = snewn(cr, int *);
2745     for (i = 0; i < cr; i++)
2746         state->blocks->blocks[i] = state->blocks->whichblock + area + i*cr;
2747 #ifdef STANDALONE_SOLVER
2748     state->blocks->blocknames = (char **)smalloc(cr*(sizeof(char *)+80));
2749 #endif
2750
2751     state->completed = state->cheated = FALSE;
2752
2753     i = 0;
2754     while (*desc && *desc != ',') {
2755         int n = *desc++;
2756         if (n >= 'a' && n <= 'z') {
2757             int run = n - 'a' + 1;
2758             assert(i + run <= area);
2759             while (run-- > 0)
2760                 state->grid[i++] = 0;
2761         } else if (n == '_') {
2762             /* do nothing */;
2763         } else if (n > '0' && n <= '9') {
2764             assert(i < area);
2765             state->immutable[i] = TRUE;
2766             state->grid[i++] = atoi(desc-1);
2767             while (*desc >= '0' && *desc <= '9')
2768                 desc++;
2769         } else {
2770             assert(!"We can't get here");
2771         }
2772     }
2773     assert(i == area);
2774
2775     if (r == 1) {
2776         int pos = 0;
2777         int *dsf;
2778         int nb;
2779
2780         assert(*desc == ',');
2781
2782         dsf = snew_dsf(area);
2783         desc++;
2784
2785         while (*desc) {
2786             int c, adv;
2787
2788             if (*desc == '_')
2789                 c = 0;
2790             else if (*desc >= 'a' && *desc <= 'z')
2791                 c = *desc - 'a' + 1;
2792             else
2793                 assert(!"Shouldn't get here");
2794             desc++;
2795
2796             adv = (c != 25);           /* 'z' is a special case */
2797
2798             while (c-- > 0) {
2799                 int p0, p1;
2800
2801                 /*
2802                  * Non-edge; merge the two dsf classes on either
2803                  * side of it.
2804                  */
2805                 assert(pos < 2*cr*(cr-1));
2806                 if (pos < cr*(cr-1)) {
2807                     int y = pos/(cr-1);
2808                     int x = pos%(cr-1);
2809                     p0 = y*cr+x;
2810                     p1 = y*cr+x+1;
2811                 } else {
2812                     int x = pos/(cr-1) - cr;
2813                     int y = pos%(cr-1);
2814                     p0 = y*cr+x;
2815                     p1 = (y+1)*cr+x;
2816                 }
2817                 dsf_merge(dsf, p0, p1);
2818
2819                 pos++;
2820             }
2821             if (adv)
2822                 pos++;
2823         }
2824
2825         /*
2826          * When desc is exhausted, we expect to have gone exactly
2827          * one space _past_ the end of the grid, due to the dummy
2828          * edge at the end.
2829          */
2830         assert(pos == 2*cr*(cr-1)+1);
2831
2832         /*
2833          * Now we've got our dsf. Translate it into a block
2834          * structure.
2835          */
2836         nb = 0;
2837         for (i = 0; i < area; i++)
2838             state->blocks->whichblock[i] = -1;
2839         for (i = 0; i < area; i++) {
2840             int j = dsf_canonify(dsf, i);
2841             if (state->blocks->whichblock[j] < 0)
2842                 state->blocks->whichblock[j] = nb++;
2843             state->blocks->whichblock[i] = state->blocks->whichblock[j];
2844         }
2845         assert(nb == cr);
2846
2847         sfree(dsf);
2848     } else {
2849         int x, y;
2850
2851         assert(!*desc);
2852
2853         for (y = 0; y < cr; y++)
2854             for (x = 0; x < cr; x++)
2855                 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2856     }
2857
2858     /*
2859      * Having sorted out whichblock[], set up the block index arrays.
2860      */
2861     for (i = 0; i < cr; i++)
2862         state->blocks->blocks[i][cr-1] = 0;
2863     for (i = 0; i < area; i++) {
2864         int b = state->blocks->whichblock[i];
2865         int j = state->blocks->blocks[b][cr-1]++;
2866         assert(j < cr);
2867         state->blocks->blocks[b][j] = i;
2868     }
2869
2870 #ifdef STANDALONE_SOLVER
2871     /*
2872      * Set up the block names for solver diagnostic output.
2873      */
2874     {
2875         char *p = (char *)(state->blocks->blocknames + cr);
2876
2877         if (r == 1) {
2878             for (i = 0; i < cr; i++)
2879                 state->blocks->blocknames[i] = NULL;
2880
2881             for (i = 0; i < area; i++) {
2882                 int j = state->blocks->whichblock[i];
2883                 if (!state->blocks->blocknames[j]) {
2884                     state->blocks->blocknames[j] = p;
2885                     p += 1 + sprintf(p, "starting at (%d,%d)",
2886                                      1 + i%cr, 1 + i/cr);
2887                 }
2888             }
2889         } else {
2890             int bx, by;
2891             for (by = 0; by < r; by++)
2892                 for (bx = 0; bx < c; bx++) {
2893                     state->blocks->blocknames[by*c+bx] = p;
2894                     p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
2895                 }
2896         }
2897         assert(p - (char *)state->blocks->blocknames < cr*(sizeof(char *)+80));
2898         for (i = 0; i < cr; i++)
2899             assert(state->blocks->blocknames[i]);
2900     }
2901 #endif
2902
2903     return state;
2904 }
2905
2906 static game_state *dup_game(game_state *state)
2907 {
2908     game_state *ret = snew(game_state);
2909     int cr = state->cr, area = cr * cr;
2910
2911     ret->cr = state->cr;
2912     ret->xtype = state->xtype;
2913
2914     ret->blocks = state->blocks;
2915     ret->blocks->refcount++;
2916
2917     ret->grid = snewn(area, digit);
2918     memcpy(ret->grid, state->grid, area);
2919
2920     ret->pencil = snewn(area * cr, unsigned char);
2921     memcpy(ret->pencil, state->pencil, area * cr);
2922
2923     ret->immutable = snewn(area, unsigned char);
2924     memcpy(ret->immutable, state->immutable, area);
2925
2926     ret->completed = state->completed;
2927     ret->cheated = state->cheated;
2928
2929     return ret;
2930 }
2931
2932 static void free_game(game_state *state)
2933 {
2934     if (--state->blocks->refcount == 0) {
2935         sfree(state->blocks->whichblock);
2936         sfree(state->blocks->blocks);
2937 #ifdef STANDALONE_SOLVER
2938         sfree(state->blocks->blocknames);
2939 #endif
2940         sfree(state->blocks);
2941     }
2942     sfree(state->immutable);
2943     sfree(state->pencil);
2944     sfree(state->grid);
2945     sfree(state);
2946 }
2947
2948 static char *solve_game(game_state *state, game_state *currstate,
2949                         char *ai, char **error)
2950 {
2951     int cr = state->cr;
2952     char *ret;
2953     digit *grid;
2954     int solve_ret;
2955
2956     /*
2957      * If we already have the solution in ai, save ourselves some
2958      * time.
2959      */
2960     if (ai)
2961         return dupstr(ai);
2962
2963     grid = snewn(cr*cr, digit);
2964     memcpy(grid, state->grid, cr*cr);
2965     solve_ret = solver(cr, state->blocks, state->xtype, grid, DIFF_RECURSIVE);
2966
2967     *error = NULL;
2968
2969     if (solve_ret == DIFF_IMPOSSIBLE)
2970         *error = "No solution exists for this puzzle";
2971     else if (solve_ret == DIFF_AMBIGUOUS)
2972         *error = "Multiple solutions exist for this puzzle";
2973
2974     if (*error) {
2975         sfree(grid);
2976         return NULL;
2977     }
2978
2979     ret = encode_solve_move(cr, grid);
2980
2981     sfree(grid);
2982
2983     return ret;
2984 }
2985
2986 static char *grid_text_format(int cr, struct block_structure *blocks,
2987                               int xtype, digit *grid)
2988 {
2989     int vmod, hmod;
2990     int x, y;
2991     int totallen, linelen, nlines;
2992     char *ret, *p, ch;
2993
2994     /*
2995      * For non-jigsaw Sudoku, we format in the way we always have,
2996      * by having the digits unevenly spaced so that the dividing
2997      * lines can fit in:
2998      *
2999      * . . | . .
3000      * . . | . .
3001      * ----+----
3002      * . . | . .
3003      * . . | . .
3004      *
3005      * For jigsaw puzzles, however, we must leave space between
3006      * _all_ pairs of digits for an optional dividing line, so we
3007      * have to move to the rather ugly
3008      * 
3009      * .   .   .   .
3010      * ------+------
3011      * .   . | .   .
3012      *       +---+  
3013      * .   . | . | .
3014      * ------+   |  
3015      * .   .   . | .
3016      * 
3017      * We deal with both cases using the same formatting code; we
3018      * simply invent a vmod value such that there's a vertical
3019      * dividing line before column i iff i is divisible by vmod
3020      * (so it's r in the first case and 1 in the second), and hmod
3021      * likewise for horizontal dividing lines.
3022      */
3023
3024     if (blocks->r != 1) {
3025         vmod = blocks->r;
3026         hmod = blocks->c;
3027     } else {
3028         vmod = hmod = 1;
3029     }
3030
3031     /*
3032      * Line length: we have cr digits, each with a space after it,
3033      * and (cr-1)/vmod dividing lines, each with a space after it.
3034      * The final space is replaced by a newline, but that doesn't
3035      * affect the length.
3036      */
3037     linelen = 2*(cr + (cr-1)/vmod);
3038
3039     /*
3040      * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3041      * dividing rows.
3042      */
3043     nlines = cr + (cr-1)/hmod;
3044
3045     /*
3046      * Allocate the space.
3047      */
3048     totallen = linelen * nlines;
3049     ret = snewn(totallen+1, char);     /* leave room for terminating NUL */
3050
3051     /*
3052      * Write the text.
3053      */
3054     p = ret;
3055     for (y = 0; y < cr; y++) {
3056         /*
3057          * Row of digits.
3058          */
3059         for (x = 0; x < cr; x++) {
3060             /*
3061              * Digit.
3062              */
3063             digit d = grid[y*cr+x];
3064
3065             if (d == 0) {
3066                 /*
3067                  * Empty space: we usually write a dot, but we'll
3068                  * highlight spaces on the X-diagonals (in X mode)
3069                  * by using underscores instead.
3070                  */
3071                 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
3072                     ch = '_';
3073                 else
3074                     ch = '.';
3075             } else if (d <= 9) {
3076                 ch = '0' + d;
3077             } else {
3078                 ch = 'a' + d-10;
3079             }
3080
3081             *p++ = ch;
3082             if (x == cr-1) {
3083                 *p++ = '\n';
3084                 continue;
3085             }
3086             *p++ = ' ';
3087
3088             if ((x+1) % vmod)
3089                 continue;
3090
3091             /*
3092              * Optional dividing line.
3093              */
3094             if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
3095                 ch = '|';
3096             else
3097                 ch = ' ';
3098             *p++ = ch;
3099             *p++ = ' ';
3100         }
3101         if (y == cr-1 || (y+1) % hmod)
3102             continue;
3103
3104         /*
3105          * Dividing row.
3106          */
3107         for (x = 0; x < cr; x++) {
3108             int dwid;
3109             int tl, tr, bl, br;
3110
3111             /*
3112              * Division between two squares. This varies
3113              * complicatedly in length.
3114              */
3115             dwid = 2;                  /* digit and its following space */
3116             if (x == cr-1)
3117                 dwid--;                /* no following space at end of line */
3118             if (x > 0 && x % vmod == 0)
3119                 dwid++;                /* preceding space after a divider */
3120
3121             if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
3122                 ch = '-';
3123             else
3124                 ch = ' ';
3125
3126             while (dwid-- > 0)
3127                 *p++ = ch;
3128
3129             if (x == cr-1) {
3130                 *p++ = '\n';
3131                 break;
3132             }
3133
3134             if ((x+1) % vmod)
3135                 continue;
3136
3137             /*
3138              * Corner square. This is:
3139              *  - a space if all four surrounding squares are in
3140              *    the same block
3141              *  - a vertical line if the two left ones are in one
3142              *    block and the two right in another
3143              *  - a horizontal line if the two top ones are in one
3144              *    block and the two bottom in another
3145              *  - a plus sign in all other cases. (If we had a
3146              *    richer character set available we could break
3147              *    this case up further by doing fun things with
3148              *    line-drawing T-pieces.)
3149              */
3150             tl = blocks->whichblock[y*cr+x];
3151             tr = blocks->whichblock[y*cr+x+1];
3152             bl = blocks->whichblock[(y+1)*cr+x];
3153             br = blocks->whichblock[(y+1)*cr+x+1];
3154
3155             if (tl == tr && tr == bl && bl == br)
3156                 ch = ' ';
3157             else if (tl == bl && tr == br)
3158                 ch = '|';
3159             else if (tl == tr && bl == br)
3160                 ch = '-';
3161             else
3162                 ch = '+';
3163
3164             *p++ = ch;
3165         }
3166     }
3167
3168     assert(p - ret == totallen);
3169     *p = '\0';
3170     return ret;
3171 }
3172
3173 static char *game_text_format(game_state *state)
3174 {
3175     return grid_text_format(state->cr, state->blocks, state->xtype,
3176                             state->grid);
3177 }
3178
3179 struct game_ui {
3180     /*
3181      * These are the coordinates of the currently highlighted
3182      * square on the grid, or -1,-1 if there isn't one. When there
3183      * is, pressing a valid number or letter key or Space will
3184      * enter that number or letter in the grid.
3185      */
3186     int hx, hy;
3187     /*
3188      * This indicates whether the current highlight is a
3189      * pencil-mark one or a real one.
3190      */
3191     int hpencil;
3192 };
3193
3194 static game_ui *new_ui(game_state *state)
3195 {
3196     game_ui *ui = snew(game_ui);
3197
3198     ui->hx = ui->hy = -1;
3199     ui->hpencil = 0;
3200
3201     return ui;
3202 }
3203
3204 static void free_ui(game_ui *ui)
3205 {
3206     sfree(ui);
3207 }
3208
3209 static char *encode_ui(game_ui *ui)
3210 {
3211     return NULL;
3212 }
3213
3214 static void decode_ui(game_ui *ui, char *encoding)
3215 {
3216 }
3217
3218 static void game_changed_state(game_ui *ui, game_state *oldstate,
3219                                game_state *newstate)
3220 {
3221     int cr = newstate->cr;
3222     /*
3223      * We prevent pencil-mode highlighting of a filled square. So
3224      * if the user has just filled in a square which we had a
3225      * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3226      * then we cancel the highlight.
3227      */
3228     if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
3229         newstate->grid[ui->hy * cr + ui->hx] != 0) {
3230         ui->hx = ui->hy = -1;
3231     }
3232 }
3233
3234 struct game_drawstate {
3235     int started;
3236     int cr, xtype;
3237     int tilesize;
3238     digit *grid;
3239     unsigned char *pencil;
3240     unsigned char *hl;
3241     /* This is scratch space used within a single call to game_redraw. */
3242     int *entered_items;
3243 };
3244
3245 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3246                             int x, int y, int button)
3247 {
3248     int cr = state->cr;
3249     int tx, ty;
3250     char buf[80];
3251
3252     button &= ~MOD_MASK;
3253
3254     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3255     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3256
3257     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
3258         if (button == LEFT_BUTTON) {
3259             if (state->immutable[ty*cr+tx]) {
3260                 ui->hx = ui->hy = -1;
3261             } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
3262                 ui->hx = ui->hy = -1;
3263             } else {
3264                 ui->hx = tx;
3265                 ui->hy = ty;
3266                 ui->hpencil = 0;
3267             }
3268             return "";                 /* UI activity occurred */
3269         }
3270         if (button == RIGHT_BUTTON) {
3271             /*
3272              * Pencil-mode highlighting for non filled squares.
3273              */
3274             if (state->grid[ty*cr+tx] == 0) {
3275                 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
3276                     ui->hx = ui->hy = -1;
3277                 } else {
3278                     ui->hpencil = 1;
3279                     ui->hx = tx;
3280                     ui->hy = ty;
3281                 }
3282             } else {
3283                 ui->hx = ui->hy = -1;
3284             }
3285             return "";                 /* UI activity occurred */
3286         }
3287     }
3288
3289     if (ui->hx != -1 && ui->hy != -1 &&
3290         ((button >= '1' && button <= '9' && button - '0' <= cr) ||
3291          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
3292          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
3293          button == ' ' || button == '\010' || button == '\177')) {
3294         int n = button - '0';
3295         if (button >= 'A' && button <= 'Z')
3296             n = button - 'A' + 10;
3297         if (button >= 'a' && button <= 'z')
3298             n = button - 'a' + 10;
3299         if (button == ' ' || button == '\010' || button == '\177')
3300             n = 0;
3301
3302         /*
3303          * Can't overwrite this square. In principle this shouldn't
3304          * happen anyway because we should never have even been
3305          * able to highlight the square, but it never hurts to be
3306          * careful.
3307          */
3308         if (state->immutable[ui->hy*cr+ui->hx])
3309             return NULL;
3310
3311         /*
3312          * Can't make pencil marks in a filled square. In principle
3313          * this shouldn't happen anyway because we should never
3314          * have even been able to pencil-highlight the square, but
3315          * it never hurts to be careful.
3316          */
3317         if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
3318             return NULL;
3319
3320         sprintf(buf, "%c%d,%d,%d",
3321                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
3322
3323         ui->hx = ui->hy = -1;
3324
3325         return dupstr(buf);
3326     }
3327
3328     return NULL;
3329 }
3330
3331 static game_state *execute_move(game_state *from, char *move)
3332 {
3333     int cr = from->cr;
3334     game_state *ret;
3335     int x, y, n;
3336
3337     if (move[0] == 'S') {
3338         char *p;
3339
3340         ret = dup_game(from);
3341         ret->completed = ret->cheated = TRUE;
3342
3343         p = move+1;
3344         for (n = 0; n < cr*cr; n++) {
3345             ret->grid[n] = atoi(p);
3346
3347             if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
3348                 free_game(ret);
3349                 return NULL;
3350             }
3351
3352             while (*p && isdigit((unsigned char)*p)) p++;
3353             if (*p == ',') p++;
3354         }
3355
3356         return ret;
3357     } else if ((move[0] == 'P' || move[0] == 'R') &&
3358         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
3359         x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
3360
3361         ret = dup_game(from);
3362         if (move[0] == 'P' && n > 0) {
3363             int index = (y*cr+x) * cr + (n-1);
3364             ret->pencil[index] = !ret->pencil[index];
3365         } else {
3366             ret->grid[y*cr+x] = n;
3367             memset(ret->pencil + (y*cr+x)*cr, 0, cr);
3368
3369             /*
3370              * We've made a real change to the grid. Check to see
3371              * if the game has been completed.
3372              */
3373             if (!ret->completed && check_valid(cr, ret->blocks, ret->xtype,
3374                                                ret->grid)) {
3375                 ret->completed = TRUE;
3376             }
3377         }
3378         return ret;
3379     } else
3380         return NULL;                   /* couldn't parse move string */
3381 }
3382
3383 /* ----------------------------------------------------------------------
3384  * Drawing routines.
3385  */
3386
3387 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3388 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3389
3390 static void game_compute_size(game_params *params, int tilesize,
3391                               int *x, int *y)
3392 {
3393     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3394     struct { int tilesize; } ads, *ds = &ads;
3395     ads.tilesize = tilesize;
3396
3397     *x = SIZE(params->c * params->r);
3398     *y = SIZE(params->c * params->r);
3399 }
3400
3401 static void game_set_size(drawing *dr, game_drawstate *ds,
3402                           game_params *params, int tilesize)
3403 {
3404     ds->tilesize = tilesize;
3405 }
3406
3407 static float *game_colours(frontend *fe, int *ncolours)
3408 {
3409     float *ret = snewn(3 * NCOLOURS, float);
3410
3411     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
3412
3413     ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
3414     ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
3415     ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
3416
3417     ret[COL_GRID * 3 + 0] = 0.0F;
3418     ret[COL_GRID * 3 + 1] = 0.0F;
3419     ret[COL_GRID * 3 + 2] = 0.0F;
3420
3421     ret[COL_CLUE * 3 + 0] = 0.0F;
3422     ret[COL_CLUE * 3 + 1] = 0.0F;
3423     ret[COL_CLUE * 3 + 2] = 0.0F;
3424
3425     ret[COL_USER * 3 + 0] = 0.0F;
3426     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
3427     ret[COL_USER * 3 + 2] = 0.0F;
3428
3429     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
3430     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
3431     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
3432
3433     ret[COL_ERROR * 3 + 0] = 1.0F;
3434     ret[COL_ERROR * 3 + 1] = 0.0F;
3435     ret[COL_ERROR * 3 + 2] = 0.0F;
3436
3437     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
3438     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
3439     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
3440
3441     *ncolours = NCOLOURS;
3442     return ret;
3443 }
3444
3445 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
3446 {
3447     struct game_drawstate *ds = snew(struct game_drawstate);
3448     int cr = state->cr;
3449
3450     ds->started = FALSE;
3451     ds->cr = cr;
3452     ds->xtype = state->xtype;
3453     ds->grid = snewn(cr*cr, digit);
3454     memset(ds->grid, cr+2, cr*cr);
3455     ds->pencil = snewn(cr*cr*cr, digit);
3456     memset(ds->pencil, 0, cr*cr*cr);
3457     ds->hl = snewn(cr*cr, unsigned char);
3458     memset(ds->hl, 0, cr*cr);
3459     ds->entered_items = snewn(cr*cr, int);
3460     ds->tilesize = 0;                  /* not decided yet */
3461     return ds;
3462 }
3463
3464 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3465 {
3466     sfree(ds->hl);
3467     sfree(ds->pencil);
3468     sfree(ds->grid);
3469     sfree(ds->entered_items);
3470     sfree(ds);
3471 }
3472
3473 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
3474                         int x, int y, int hl)
3475 {
3476     int cr = state->cr;
3477     int tx, ty;
3478     int cx, cy, cw, ch;
3479     char str[2];
3480
3481     if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
3482         ds->hl[y*cr+x] == hl &&
3483         !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
3484         return;                        /* no change required */
3485
3486     tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
3487     ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
3488
3489     cx = tx;
3490     cy = ty;
3491     cw = TILE_SIZE-1-2*GRIDEXTRA;
3492     ch = TILE_SIZE-1-2*GRIDEXTRA;
3493
3494     if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
3495         cx -= GRIDEXTRA, cw += GRIDEXTRA;
3496     if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
3497         cw += GRIDEXTRA;
3498     if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
3499         cy -= GRIDEXTRA, ch += GRIDEXTRA;
3500     if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
3501         ch += GRIDEXTRA;
3502
3503     clip(dr, cx, cy, cw, ch);
3504
3505     /* background needs erasing */
3506     draw_rect(dr, cx, cy, cw, ch,
3507               ((hl & 15) == 1 ? COL_HIGHLIGHT :
3508                (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
3509                COL_BACKGROUND));
3510
3511     /*
3512      * Draw the corners of thick lines in corner-adjacent squares,
3513      * which jut into this square by one pixel.
3514      */
3515     if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
3516         draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3517     if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
3518         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3519     if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
3520         draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3521     if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
3522         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3523
3524     /* pencil-mode highlight */
3525     if ((hl & 15) == 2) {
3526         int coords[6];
3527         coords[0] = cx;
3528         coords[1] = cy;
3529         coords[2] = cx+cw/2;
3530         coords[3] = cy;
3531         coords[4] = cx;
3532         coords[5] = cy+ch/2;
3533         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
3534     }
3535
3536     /* new number needs drawing? */
3537     if (state->grid[y*cr+x]) {
3538         str[1] = '\0';
3539         str[0] = state->grid[y*cr+x] + '0';
3540         if (str[0] > '9')
3541             str[0] += 'a' - ('9'+1);
3542         draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
3543                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
3544                   state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
3545     } else {
3546         int i, j, npencil;
3547         int pw, ph, pmax, fontsize;
3548
3549         /* count the pencil marks required */
3550         for (i = npencil = 0; i < cr; i++)
3551             if (state->pencil[(y*cr+x)*cr+i])
3552                 npencil++;
3553
3554         /*
3555          * It's not sensible to arrange pencil marks in the same
3556          * layout as the squares within a block, because this leads
3557          * to the font being too small. Instead, we arrange pencil
3558          * marks in the nearest thing we can to a square layout,
3559          * and we adjust the square layout depending on the number
3560          * of pencil marks in the square.
3561          */
3562         for (pw = 1; pw * pw < npencil; pw++);
3563         if (pw < 3) pw = 3;            /* otherwise it just looks _silly_ */
3564         ph = (npencil + pw - 1) / pw;
3565         if (ph < 2) ph = 2;            /* likewise */
3566         pmax = max(pw, ph);
3567         fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
3568
3569         for (i = j = 0; i < cr; i++)
3570             if (state->pencil[(y*cr+x)*cr+i]) {
3571                 int dx = j % pw, dy = j / pw;
3572
3573                 str[1] = '\0';
3574                 str[0] = i + '1';
3575                 if (str[0] > '9')
3576                     str[0] += 'a' - ('9'+1);
3577                 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
3578                           ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
3579                           FONT_VARIABLE, fontsize,
3580                           ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
3581                 j++;
3582             }
3583     }
3584
3585     unclip(dr);
3586
3587     draw_update(dr, cx, cy, cw, ch);
3588
3589     ds->grid[y*cr+x] = state->grid[y*cr+x];
3590     memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
3591     ds->hl[y*cr+x] = hl;
3592 }
3593
3594 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3595                         game_state *state, int dir, game_ui *ui,
3596                         float animtime, float flashtime)
3597 {
3598     int cr = state->cr;
3599     int x, y;
3600
3601     if (!ds->started) {
3602         /*
3603          * The initial contents of the window are not guaranteed
3604          * and can vary with front ends. To be on the safe side,
3605          * all games should start by drawing a big
3606          * background-colour rectangle covering the whole window.
3607          */
3608         draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
3609
3610         /*
3611          * Draw the grid. We draw it as a big thick rectangle of
3612          * COL_GRID initially; individual calls to draw_number()
3613          * will poke the right-shaped holes in it.
3614          */
3615         draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
3616                   cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
3617                   COL_GRID);
3618     }
3619
3620     /*
3621      * This array is used to keep track of rows, columns and boxes
3622      * which contain a number more than once.
3623      */
3624     for (x = 0; x < cr * cr; x++)
3625         ds->entered_items[x] = 0;
3626     for (x = 0; x < cr; x++)
3627         for (y = 0; y < cr; y++) {
3628             digit d = state->grid[y*cr+x];
3629             if (d) {
3630                 int box = state->blocks->whichblock[y*cr+x];
3631                 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
3632                 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
3633                 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
3634                 if (ds->xtype) {
3635                     if (ondiag0(y*cr+x))
3636                         ds->entered_items[d-1] |= ((ds->entered_items[d-1] & 64) << 1) | 64;
3637                     if (ondiag1(y*cr+x))
3638                         ds->entered_items[cr+d-1] |= ((ds->entered_items[cr+d-1] & 64) << 1) | 64;
3639                 }
3640             }
3641         }
3642
3643     /*
3644      * Draw any numbers which need redrawing.
3645      */
3646     for (x = 0; x < cr; x++) {
3647         for (y = 0; y < cr; y++) {
3648             int highlight = 0;
3649             digit d = state->grid[y*cr+x];
3650
3651             if (flashtime > 0 &&
3652                 (flashtime <= FLASH_TIME/3 ||
3653                  flashtime >= FLASH_TIME*2/3))
3654                 highlight = 1;
3655
3656             /* Highlight active input areas. */
3657             if (x == ui->hx && y == ui->hy)
3658                 highlight = ui->hpencil ? 2 : 1;
3659
3660             /* Mark obvious errors (ie, numbers which occur more than once
3661              * in a single row, column, or box). */
3662             if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
3663                       (ds->entered_items[y*cr+d-1] & 8) ||
3664                       (ds->entered_items[state->blocks->whichblock[y*cr+x]*cr+d-1] & 32) ||
3665                       (ds->xtype && ((ondiag0(y*cr+x) && (ds->entered_items[d-1] & 128)) ||
3666                                      (ondiag1(y*cr+x) && (ds->entered_items[cr+d-1] & 128))))))
3667                 highlight |= 16;
3668
3669             draw_number(dr, ds, state, x, y, highlight);
3670         }
3671     }
3672
3673     /*
3674      * Update the _entire_ grid if necessary.
3675      */
3676     if (!ds->started) {
3677         draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
3678         ds->started = TRUE;
3679     }
3680 }
3681
3682 static float game_anim_length(game_state *oldstate, game_state *newstate,
3683                               int dir, game_ui *ui)
3684 {
3685     return 0.0F;
3686 }
3687
3688 static float game_flash_length(game_state *oldstate, game_state *newstate,
3689                                int dir, game_ui *ui)
3690 {
3691     if (!oldstate->completed && newstate->completed &&
3692         !oldstate->cheated && !newstate->cheated)
3693         return FLASH_TIME;
3694     return 0.0F;
3695 }
3696
3697 static int game_timing_state(game_state *state, game_ui *ui)
3698 {
3699     return TRUE;
3700 }
3701
3702 static void game_print_size(game_params *params, float *x, float *y)
3703 {
3704     int pw, ph;
3705
3706     /*
3707      * I'll use 9mm squares by default. They should be quite big
3708      * for this game, because players will want to jot down no end
3709      * of pencil marks in the squares.
3710      */
3711     game_compute_size(params, 900, &pw, &ph);
3712     *x = pw / 100.0;
3713     *y = ph / 100.0;
3714 }
3715
3716 static void game_print(drawing *dr, game_state *state, int tilesize)
3717 {
3718     int cr = state->cr;
3719     int ink = print_mono_colour(dr, 0);
3720     int x, y;
3721
3722     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3723     game_drawstate ads, *ds = &ads;
3724     game_set_size(dr, ds, NULL, tilesize);
3725
3726     /*
3727      * Border.
3728      */
3729     print_line_width(dr, 3 * TILE_SIZE / 40);
3730     draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
3731
3732     /*
3733      * Highlight X-diagonal squares.
3734      */
3735     if (state->xtype) {
3736         int i;
3737         int xhighlight = print_grey_colour(dr, 0.90F);
3738
3739         for (i = 0; i < cr; i++)
3740             draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
3741                       TILE_SIZE, TILE_SIZE, xhighlight);
3742         for (i = 0; i < cr; i++)
3743             if (i*2 != cr-1)  /* avoid redoing centre square, just for fun */
3744                 draw_rect(dr, BORDER + i*TILE_SIZE,
3745                           BORDER + (cr-1-i)*TILE_SIZE,
3746                           TILE_SIZE, TILE_SIZE, xhighlight);
3747     }
3748
3749     /*
3750      * Main grid.
3751      */
3752     for (x = 1; x < cr; x++) {
3753         print_line_width(dr, TILE_SIZE / 40);
3754         draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
3755                   BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
3756     }
3757     for (y = 1; y < cr; y++) {
3758         print_line_width(dr, TILE_SIZE / 40);
3759         draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
3760                   BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
3761     }
3762
3763     /*
3764      * Thick lines between cells. In order to do this using the
3765      * line-drawing rather than rectangle-drawing API (so as to
3766      * get line thicknesses to scale correctly) and yet have
3767      * correctly mitred joins between lines, we must do this by
3768      * tracing the boundary of each sub-block and drawing it in
3769      * one go as a single polygon.
3770      */
3771     {
3772         int *coords;
3773         int bi, i, n;
3774         int x, y, dx, dy, sx, sy, sdx, sdy;
3775
3776         print_line_width(dr, 3 * TILE_SIZE / 40);
3777
3778         /*
3779          * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3780          * with k unconnected squares, with total perimeter 4k.
3781          * Now repeatedly join two disconnected components
3782          * together into a larger one; every time you do so you
3783          * remove at least two unit edges, and you require k-1 of
3784          * these operations to create a single connected piece, so
3785          * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3786          * afterwards.)
3787          */
3788         coords = snewn(4*cr+4, int);   /* 2k+2 points, 2 coords per point */
3789
3790         /*
3791          * Iterate over all the blocks.
3792          */
3793         for (bi = 0; bi < cr; bi++) {
3794
3795             /*
3796              * For each block, find a starting square within it
3797              * which has a boundary at the left.
3798              */
3799             for (i = 0; i < cr; i++) {
3800                 int j = state->blocks->blocks[bi][i];
3801                 if (j % cr == 0 || state->blocks->whichblock[j-1] != bi)
3802                     break;
3803             }
3804             assert(i < cr); /* every block must have _some_ leftmost square */
3805             x = state->blocks->blocks[bi][i] % cr;
3806             y = state->blocks->blocks[bi][i] / cr;
3807             dx = -1;
3808             dy = 0;
3809
3810             /*
3811              * Now begin tracing round the perimeter. At all
3812              * times, (x,y) describes some square within the
3813              * block, and (x+dx,y+dy) is some adjacent square
3814              * outside it; so the edge between those two squares
3815              * is always an edge of the block.
3816              */
3817             sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
3818             n = 0;
3819             do {
3820                 int cx, cy, tx, ty, nin;
3821
3822                 /*
3823                  * To begin with, record the point at one end of
3824                  * the edge. To do this, we translate (x,y) down
3825                  * and right by half a unit (so they're describing
3826                  * a point in the _centre_ of the square) and then
3827                  * translate back again in a manner rotated by dy
3828                  * and dx.
3829                  */
3830                 assert(n < 2*cr+2);
3831                 cx = ((2*x+1) + dy + dx) / 2;
3832                 cy = ((2*y+1) - dx + dy) / 2;
3833                 coords[2*n+0] = BORDER + cx * TILE_SIZE;
3834                 coords[2*n+1] = BORDER + cy * TILE_SIZE;
3835                 n++;
3836
3837                 /*
3838                  * Now advance to the next edge, by looking at the
3839                  * two squares beyond it. If they're both outside
3840                  * the block, we turn right (by leaving x,y the
3841                  * same and rotating dx,dy clockwise); if they're
3842                  * both inside, we turn left (by rotating dx,dy
3843                  * anticlockwise and contriving to leave x+dx,y+dy
3844                  * unchanged); if one of each, we go straight on
3845                  * (and may enforce by assertion that they're one
3846                  * of each the _right_ way round).
3847                  */
3848                 nin = 0;
3849                 tx = x - dy + dx;
3850                 ty = y + dx + dy;
3851                 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3852                         state->blocks->whichblock[ty*cr+tx] == bi);
3853                 tx = x - dy;
3854                 ty = y + dx;
3855                 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3856                         state->blocks->whichblock[ty*cr+tx] == bi);
3857                 if (nin == 0) {
3858                     /*
3859                      * Turn right.
3860                      */
3861                     int tmp;
3862                     tmp = dx;
3863                     dx = -dy;
3864                     dy = tmp;
3865                 } else if (nin == 2) {
3866                     /*
3867                      * Turn left.
3868                      */
3869                     int tmp;
3870
3871                     x += dx;
3872                     y += dy;
3873                     
3874                     tmp = dx;
3875                     dx = dy;
3876                     dy = -tmp;
3877
3878                     x -= dx;
3879                     y -= dy;
3880                 } else {
3881                     /*
3882                      * Go straight on.
3883                      */
3884                     x -= dy;
3885                     y += dx;
3886                 }
3887
3888                 /*
3889                  * Now enforce by assertion that we ended up
3890                  * somewhere sensible.
3891                  */
3892                 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
3893                        state->blocks->whichblock[y*cr+x] == bi);
3894                 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
3895                        state->blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
3896
3897             } while (x != sx || y != sy || dx != sdx || dy != sdy);
3898
3899             /*
3900              * That's our polygon; now draw it.
3901              */
3902             draw_polygon(dr, coords, n, -1, ink);
3903         }
3904
3905         sfree(coords);
3906     }
3907
3908     /*
3909      * Numbers.
3910      */
3911     for (y = 0; y < cr; y++)
3912         for (x = 0; x < cr; x++)
3913             if (state->grid[y*cr+x]) {
3914                 char str[2];
3915                 str[1] = '\0';
3916                 str[0] = state->grid[y*cr+x] + '0';
3917                 if (str[0] > '9')
3918                     str[0] += 'a' - ('9'+1);
3919                 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
3920                           BORDER + y*TILE_SIZE + TILE_SIZE/2,
3921                           FONT_VARIABLE, TILE_SIZE/2,
3922                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
3923             }
3924 }
3925
3926 #ifdef COMBINED
3927 #define thegame solo
3928 #endif
3929
3930 const struct game thegame = {
3931     "Solo", "games.solo", "solo",
3932     default_params,
3933     game_fetch_preset,
3934     decode_params,
3935     encode_params,
3936     free_params,
3937     dup_params,
3938     TRUE, game_configure, custom_params,
3939     validate_params,
3940     new_game_desc,
3941     validate_desc,
3942     new_game,
3943     dup_game,
3944     free_game,
3945     TRUE, solve_game,
3946     TRUE, game_text_format,
3947     new_ui,
3948     free_ui,
3949     encode_ui,
3950     decode_ui,
3951     game_changed_state,
3952     interpret_move,
3953     execute_move,
3954     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3955     game_colours,
3956     game_new_drawstate,
3957     game_free_drawstate,
3958     game_redraw,
3959     game_anim_length,
3960     game_flash_length,
3961     TRUE, FALSE, game_print_size, game_print,
3962     FALSE,                             /* wants_statusbar */
3963     FALSE, game_timing_state,
3964     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
3965 };
3966
3967 #ifdef STANDALONE_SOLVER
3968
3969 int main(int argc, char **argv)
3970 {
3971     game_params *p;
3972     game_state *s;
3973     char *id = NULL, *desc, *err;
3974     int grade = FALSE;
3975     int ret;
3976
3977     while (--argc > 0) {
3978         char *p = *++argv;
3979         if (!strcmp(p, "-v")) {
3980             solver_show_working = TRUE;
3981         } else if (!strcmp(p, "-g")) {
3982             grade = TRUE;
3983         } else if (*p == '-') {
3984             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3985             return 1;
3986         } else {
3987             id = p;
3988         }
3989     }
3990
3991     if (!id) {
3992         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3993         return 1;
3994     }
3995
3996     desc = strchr(id, ':');
3997     if (!desc) {
3998         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3999         return 1;
4000     }
4001     *desc++ = '\0';
4002
4003     p = default_params();
4004     decode_params(p, id);
4005     err = validate_desc(p, desc);
4006     if (err) {
4007         fprintf(stderr, "%s: %s\n", argv[0], err);
4008         return 1;
4009     }
4010     s = new_game(NULL, p, desc);
4011
4012     ret = solver(s->cr, s->blocks, s->xtype, s->grid, DIFF_RECURSIVE);
4013     if (grade) {
4014         printf("Difficulty rating: %s\n",
4015                ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
4016                ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
4017                ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
4018                ret==DIFF_SET ? "Advanced (set elimination required)":
4019                ret==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
4020                ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
4021                ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
4022                ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
4023                "INTERNAL ERROR: unrecognised difficulty code");
4024     } else {
4025         printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
4026     }
4027
4028     return 0;
4029 }
4030
4031 #endif