chiark / gitweb /
Backspace and Delete keys now function like Space in Solo.
[sgt-puzzles.git] / solo.c
1 /*
2  * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3  *
4  * TODO:
5  *
6  *  - reports from users are that `Trivial'-mode puzzles are still
7  *    rather hard compared to newspapers' easy ones, so some better
8  *    low-end difficulty grading would be nice
9  *     + it's possible that really easy puzzles always have
10  *       _several_ things you can do, so don't make you hunt too
11  *       hard for the one deduction you can currently make
12  *     + it's also possible that easy puzzles require fewer
13  *       cross-eliminations: perhaps there's a higher incidence of
14  *       things you can deduce by looking only at (say) rows,
15  *       rather than things you have to check both rows and columns
16  *       for
17  *     + but really, what I need to do is find some really easy
18  *       puzzles and _play_ them, to see what's actually easy about
19  *       them
20  *     + while I'm revamping this area, filling in the _last_
21  *       number in a nearly-full row or column should certainly be
22  *       permitted even at the lowest difficulty level.
23  *     + also Owen noticed that `Basic' grids requiring numeric
24  *       elimination are actually very hard, so I wonder if a
25  *       difficulty gradation between that and positional-
26  *       elimination-only might be in order
27  *     + but it's not good to have _too_ many difficulty levels, or
28  *       it'll take too long to randomly generate a given level.
29  * 
30  *  - it might still be nice to do some prioritisation on the
31  *    removal of numbers from the grid
32  *     + one possibility is to try to minimise the maximum number
33  *       of filled squares in any block, which in particular ought
34  *       to enforce never leaving a completely filled block in the
35  *       puzzle as presented.
36  *
37  *  - alternative interface modes
38  *     + sudoku.com's Windows program has a palette of possible
39  *       entries; you select a palette entry first and then click
40  *       on the square you want it to go in, thus enabling
41  *       mouse-only play. Useful for PDAs! I don't think it's
42  *       actually incompatible with the current highlight-then-type
43  *       approach: you _either_ highlight a palette entry and then
44  *       click, _or_ you highlight a square and then type. At most
45  *       one thing is ever highlighted at a time, so there's no way
46  *       to confuse the two.
47  *     + then again, I don't actually like sudoku.com's interface;
48  *       it's too much like a paint package whereas I prefer to
49  *       think of Solo as a text editor.
50  *     + another PDA-friendly possibility is a drag interface:
51  *       _drag_ numbers from the palette into the grid squares.
52  *       Thought experiments suggest I'd prefer that to the
53  *       sudoku.com approach, but I haven't actually tried it.
54  */
55
56 /*
57  * Solo puzzles need to be square overall (since each row and each
58  * column must contain one of every digit), but they need not be
59  * subdivided the same way internally. I am going to adopt a
60  * convention whereby I _always_ refer to `r' as the number of rows
61  * of _big_ divisions, and `c' as the number of columns of _big_
62  * divisions. Thus, a 2c by 3r puzzle looks something like this:
63  *
64  *   4 5 1 | 2 6 3
65  *   6 3 2 | 5 4 1
66  *   ------+------     (Of course, you can't subdivide it the other way
67  *   1 4 5 | 6 3 2     or you'll get clashes; observe that the 4 in the
68  *   3 2 6 | 4 1 5     top left would conflict with the 4 in the second
69  *   ------+------     box down on the left-hand side.)
70  *   5 1 4 | 3 2 6
71  *   2 6 3 | 1 5 4
72  *
73  * The need for a strong naming convention should now be clear:
74  * each small box is two rows of digits by three columns, while the
75  * overall puzzle has three rows of small boxes by two columns. So
76  * I will (hopefully) consistently use `r' to denote the number of
77  * rows _of small boxes_ (here 3), which is also the number of
78  * columns of digits in each small box; and `c' vice versa (here
79  * 2).
80  *
81  * I'm also going to choose arbitrarily to list c first wherever
82  * possible: the above is a 2x3 puzzle, not a 3x2 one.
83  */
84
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <assert.h>
89 #include <ctype.h>
90 #include <math.h>
91
92 #ifdef STANDALONE_SOLVER
93 #include <stdarg.h>
94 int solver_show_working, solver_recurse_depth;
95 #endif
96
97 #include "puzzles.h"
98
99 /*
100  * To save space, I store digits internally as unsigned char. This
101  * imposes a hard limit of 255 on the order of the puzzle. Since
102  * even a 5x5 takes unacceptably long to generate, I don't see this
103  * as a serious limitation unless something _really_ impressive
104  * happens in computing technology; but here's a typedef anyway for
105  * general good practice.
106  */
107 typedef unsigned char digit;
108 #define ORDER_MAX 255
109
110 #define PREFERRED_TILE_SIZE 32
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113
114 #define FLASH_TIME 0.4F
115
116 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
117        SYMM_REF4D, SYMM_REF8 };
118
119 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_NEIGHBOUR,
120        DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
121
122 enum {
123     COL_BACKGROUND,
124     COL_GRID,
125     COL_CLUE,
126     COL_USER,
127     COL_HIGHLIGHT,
128     COL_ERROR,
129     COL_PENCIL,
130     NCOLOURS
131 };
132
133 struct game_params {
134     int c, r, symm, diff;
135 };
136
137 struct game_state {
138     int c, r;
139     digit *grid;
140     unsigned char *pencil;             /* c*r*c*r elements */
141     unsigned char *immutable;          /* marks which digits are clues */
142     int completed, cheated;
143 };
144
145 static game_params *default_params(void)
146 {
147     game_params *ret = snew(game_params);
148
149     ret->c = ret->r = 3;
150     ret->symm = SYMM_ROT2;             /* a plausible default */
151     ret->diff = DIFF_BLOCK;            /* so is this */
152
153     return ret;
154 }
155
156 static void free_params(game_params *params)
157 {
158     sfree(params);
159 }
160
161 static game_params *dup_params(game_params *params)
162 {
163     game_params *ret = snew(game_params);
164     *ret = *params;                    /* structure copy */
165     return ret;
166 }
167
168 static int game_fetch_preset(int i, char **name, game_params **params)
169 {
170     static struct {
171         char *title;
172         game_params params;
173     } presets[] = {
174         { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK } },
175         { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE } },
176         { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK } },
177         { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE } },
178         { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT } },
179         { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET } },
180         { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_NEIGHBOUR } },
181         { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE } },
182 #ifndef SLOW_SYSTEM
183         { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE } },
184         { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE } },
185 #endif
186     };
187
188     if (i < 0 || i >= lenof(presets))
189         return FALSE;
190
191     *name = dupstr(presets[i].title);
192     *params = dup_params(&presets[i].params);
193
194     return TRUE;
195 }
196
197 static void decode_params(game_params *ret, char const *string)
198 {
199     ret->c = ret->r = atoi(string);
200     while (*string && isdigit((unsigned char)*string)) string++;
201     if (*string == 'x') {
202         string++;
203         ret->r = atoi(string);
204         while (*string && isdigit((unsigned char)*string)) string++;
205     }
206     while (*string) {
207         if (*string == 'r' || *string == 'm' || *string == 'a') {
208             int sn, sc, sd;
209             sc = *string++;
210             if (*string == 'd') {
211                 sd = TRUE;
212                 string++;
213             } else {
214                 sd = FALSE;
215             }
216             sn = atoi(string);
217             while (*string && isdigit((unsigned char)*string)) string++;
218             if (sc == 'm' && sn == 8)
219                 ret->symm = SYMM_REF8;
220             if (sc == 'm' && sn == 4)
221                 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
222             if (sc == 'm' && sn == 2)
223                 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
224             if (sc == 'r' && sn == 4)
225                 ret->symm = SYMM_ROT4;
226             if (sc == 'r' && sn == 2)
227                 ret->symm = SYMM_ROT2;
228             if (sc == 'a')
229                 ret->symm = SYMM_NONE;
230         } else if (*string == 'd') {
231             string++;
232             if (*string == 't')        /* trivial */
233                 string++, ret->diff = DIFF_BLOCK;
234             else if (*string == 'b')   /* basic */
235                 string++, ret->diff = DIFF_SIMPLE;
236             else if (*string == 'i')   /* intermediate */
237                 string++, ret->diff = DIFF_INTERSECT;
238             else if (*string == 'a')   /* advanced */
239                 string++, ret->diff = DIFF_SET;
240             else if (*string == 'e')   /* extreme */
241                 string++, ret->diff = DIFF_NEIGHBOUR;
242             else if (*string == 'u')   /* unreasonable */
243                 string++, ret->diff = DIFF_RECURSIVE;
244         } else
245             string++;                  /* eat unknown character */
246     }
247 }
248
249 static char *encode_params(game_params *params, int full)
250 {
251     char str[80];
252
253     sprintf(str, "%dx%d", params->c, params->r);
254     if (full) {
255         switch (params->symm) {
256           case SYMM_REF8: strcat(str, "m8"); break;
257           case SYMM_REF4: strcat(str, "m4"); break;
258           case SYMM_REF4D: strcat(str, "md4"); break;
259           case SYMM_REF2: strcat(str, "m2"); break;
260           case SYMM_REF2D: strcat(str, "md2"); break;
261           case SYMM_ROT4: strcat(str, "r4"); break;
262           /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
263           case SYMM_NONE: strcat(str, "a"); break;
264         }
265         switch (params->diff) {
266           /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
267           case DIFF_SIMPLE: strcat(str, "db"); break;
268           case DIFF_INTERSECT: strcat(str, "di"); break;
269           case DIFF_SET: strcat(str, "da"); break;
270           case DIFF_NEIGHBOUR: strcat(str, "de"); break;
271           case DIFF_RECURSIVE: strcat(str, "du"); break;
272         }
273     }
274     return dupstr(str);
275 }
276
277 static config_item *game_configure(game_params *params)
278 {
279     config_item *ret;
280     char buf[80];
281
282     ret = snewn(5, config_item);
283
284     ret[0].name = "Columns of sub-blocks";
285     ret[0].type = C_STRING;
286     sprintf(buf, "%d", params->c);
287     ret[0].sval = dupstr(buf);
288     ret[0].ival = 0;
289
290     ret[1].name = "Rows of sub-blocks";
291     ret[1].type = C_STRING;
292     sprintf(buf, "%d", params->r);
293     ret[1].sval = dupstr(buf);
294     ret[1].ival = 0;
295
296     ret[2].name = "Symmetry";
297     ret[2].type = C_CHOICES;
298     ret[2].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
299         "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
300         "8-way mirror";
301     ret[2].ival = params->symm;
302
303     ret[3].name = "Difficulty";
304     ret[3].type = C_CHOICES;
305     ret[3].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
306     ret[3].ival = params->diff;
307
308     ret[4].name = NULL;
309     ret[4].type = C_END;
310     ret[4].sval = NULL;
311     ret[4].ival = 0;
312
313     return ret;
314 }
315
316 static game_params *custom_params(config_item *cfg)
317 {
318     game_params *ret = snew(game_params);
319
320     ret->c = atoi(cfg[0].sval);
321     ret->r = atoi(cfg[1].sval);
322     ret->symm = cfg[2].ival;
323     ret->diff = cfg[3].ival;
324
325     return ret;
326 }
327
328 static char *validate_params(game_params *params, int full)
329 {
330     if (params->c < 2 || params->r < 2)
331         return "Both dimensions must be at least 2";
332     if (params->c > ORDER_MAX || params->r > ORDER_MAX)
333         return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
334     if ((params->c * params->r) > 36)
335         return "Unable to support more than 36 distinct symbols in a puzzle";
336     return NULL;
337 }
338
339 /* ----------------------------------------------------------------------
340  * Solver.
341  * 
342  * This solver is used for two purposes:
343  *  + to check solubility of a grid as we gradually remove numbers
344  *    from it
345  *  + to solve an externally generated puzzle when the user selects
346  *    `Solve'.
347  * 
348  * It supports a variety of specific modes of reasoning. By
349  * enabling or disabling subsets of these modes we can arrange a
350  * range of difficulty levels.
351  */
352
353 /*
354  * Modes of reasoning currently supported:
355  *
356  *  - Positional elimination: a number must go in a particular
357  *    square because all the other empty squares in a given
358  *    row/col/blk are ruled out.
359  *
360  *  - Numeric elimination: a square must have a particular number
361  *    in because all the other numbers that could go in it are
362  *    ruled out.
363  *
364  *  - Intersectional analysis: given two domains which overlap
365  *    (hence one must be a block, and the other can be a row or
366  *    col), if the possible locations for a particular number in
367  *    one of the domains can be narrowed down to the overlap, then
368  *    that number can be ruled out everywhere but the overlap in
369  *    the other domain too.
370  *
371  *  - Set elimination: if there is a subset of the empty squares
372  *    within a domain such that the union of the possible numbers
373  *    in that subset has the same size as the subset itself, then
374  *    those numbers can be ruled out everywhere else in the domain.
375  *    (For example, if there are five empty squares and the
376  *    possible numbers in each are 12, 23, 13, 134 and 1345, then
377  *    the first three empty squares form such a subset: the numbers
378  *    1, 2 and 3 _must_ be in those three squares in some
379  *    permutation, and hence we can deduce none of them can be in
380  *    the fourth or fifth squares.)
381  *     + You can also see this the other way round, concentrating
382  *       on numbers rather than squares: if there is a subset of
383  *       the unplaced numbers within a domain such that the union
384  *       of all their possible positions has the same size as the
385  *       subset itself, then all other numbers can be ruled out for
386  *       those positions. However, it turns out that this is
387  *       exactly equivalent to the first formulation at all times:
388  *       there is a 1-1 correspondence between suitable subsets of
389  *       the unplaced numbers and suitable subsets of the unfilled
390  *       places, found by taking the _complement_ of the union of
391  *       the numbers' possible positions (or the spaces' possible
392  *       contents).
393  * 
394  *  - Mutual neighbour elimination: find two squares A,B and a
395  *    number N in the possible set of A, such that putting N in A
396  *    would rule out enough possibilities from the mutual
397  *    neighbours of A and B that there would be no possibilities
398  *    left for B. Thereby rule out N in A.
399  *     + The simplest case of this is if B has two possibilities
400  *       (wlog {1,2}), and there are two mutual neighbours of A and
401  *       B which have possibilities {1,3} and {2,3}. Thus, if A
402  *       were to be 3, then those neighbours would contain 1 and 2,
403  *       and hence there would be nothing left which could go in B.
404  *     + There can be more complex cases of it too: if A and B are
405  *       in the same column of large blocks, then they can have
406  *       more than two mutual neighbours, some of which can also be
407  *       neighbours of one another. Suppose, for example, that B
408  *       has possibilities {1,2,3}; there's one square P in the
409  *       same column as B and the same block as A, with
410  *       possibilities {1,4}; and there are _two_ squares Q,R in
411  *       the same column as A and the same block as B with
412  *       possibilities {2,3,4}. Then if A contained 4, P would
413  *       contain 1, and Q and R would have to contain 2 and 3 in
414  *       _some_ order; therefore, once again, B would have no
415  *       remaining possibilities.
416  * 
417  *  - Recursion. If all else fails, we pick one of the currently
418  *    most constrained empty squares and take a random guess at its
419  *    contents, then continue solving on that basis and see if we
420  *    get any further.
421  */
422
423 /*
424  * Within this solver, I'm going to transform all y-coordinates by
425  * inverting the significance of the block number and the position
426  * within the block. That is, we will start with the top row of
427  * each block in order, then the second row of each block in order,
428  * etc.
429  * 
430  * This transformation has the enormous advantage that it means
431  * every row, column _and_ block is described by an arithmetic
432  * progression of coordinates within the cubic array, so that I can
433  * use the same very simple function to do blockwise, row-wise and
434  * column-wise elimination.
435  */
436 #define YTRANS(y) (((y)%c)*r+(y)/c)
437 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
438
439 struct solver_usage {
440     int c, r, cr;
441     /*
442      * We set up a cubic array, indexed by x, y and digit; each
443      * element of this array is TRUE or FALSE according to whether
444      * or not that digit _could_ in principle go in that position.
445      *
446      * The way to index this array is cube[(x*cr+y)*cr+n-1].
447      * y-coordinates in here are transformed.
448      */
449     unsigned char *cube;
450     /*
451      * This is the grid in which we write down our final
452      * deductions. y-coordinates in here are _not_ transformed.
453      */
454     digit *grid;
455     /*
456      * Now we keep track, at a slightly higher level, of what we
457      * have yet to work out, to prevent doing the same deduction
458      * many times.
459      */
460     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
461     unsigned char *row;
462     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
463     unsigned char *col;
464     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
465     unsigned char *blk;
466 };
467 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
468 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
469
470 /*
471  * Function called when we are certain that a particular square has
472  * a particular number in it. The y-coordinate passed in here is
473  * transformed.
474  */
475 static void solver_place(struct solver_usage *usage, int x, int y, int n)
476 {
477     int c = usage->c, r = usage->r, cr = usage->cr;
478     int i, j, bx, by;
479
480     assert(cube(x,y,n));
481
482     /*
483      * Rule out all other numbers in this square.
484      */
485     for (i = 1; i <= cr; i++)
486         if (i != n)
487             cube(x,y,i) = FALSE;
488
489     /*
490      * Rule out this number in all other positions in the row.
491      */
492     for (i = 0; i < cr; i++)
493         if (i != y)
494             cube(x,i,n) = FALSE;
495
496     /*
497      * Rule out this number in all other positions in the column.
498      */
499     for (i = 0; i < cr; i++)
500         if (i != x)
501             cube(i,y,n) = FALSE;
502
503     /*
504      * Rule out this number in all other positions in the block.
505      */
506     bx = (x/r)*r;
507     by = y % r;
508     for (i = 0; i < r; i++)
509         for (j = 0; j < c; j++)
510             if (bx+i != x || by+j*r != y)
511                 cube(bx+i,by+j*r,n) = FALSE;
512
513     /*
514      * Enter the number in the result grid.
515      */
516     usage->grid[YUNTRANS(y)*cr+x] = n;
517
518     /*
519      * Cross out this number from the list of numbers left to place
520      * in its row, its column and its block.
521      */
522     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
523         usage->blk[((y%r)*c+(x/r))*cr+n-1] = TRUE;
524 }
525
526 static int solver_elim(struct solver_usage *usage, int start, int step
527 #ifdef STANDALONE_SOLVER
528                        , char *fmt, ...
529 #endif
530                        )
531 {
532     int c = usage->c, r = usage->r, cr = c*r;
533     int fpos, m, i;
534
535     /*
536      * Count the number of set bits within this section of the
537      * cube.
538      */
539     m = 0;
540     fpos = -1;
541     for (i = 0; i < cr; i++)
542         if (usage->cube[start+i*step]) {
543             fpos = start+i*step;
544             m++;
545         }
546
547     if (m == 1) {
548         int x, y, n;
549         assert(fpos >= 0);
550
551         n = 1 + fpos % cr;
552         y = fpos / cr;
553         x = y / cr;
554         y %= cr;
555
556         if (!usage->grid[YUNTRANS(y)*cr+x]) {
557 #ifdef STANDALONE_SOLVER
558             if (solver_show_working) {
559                 va_list ap;
560                 printf("%*s", solver_recurse_depth*4, "");
561                 va_start(ap, fmt);
562                 vprintf(fmt, ap);
563                 va_end(ap);
564                 printf(":\n%*s  placing %d at (%d,%d)\n",
565                        solver_recurse_depth*4, "", n, 1+x, 1+YUNTRANS(y));
566             }
567 #endif
568             solver_place(usage, x, y, n);
569             return +1;
570         }
571     } else if (m == 0) {
572 #ifdef STANDALONE_SOLVER
573         if (solver_show_working) {
574             va_list ap;
575             printf("%*s", solver_recurse_depth*4, "");
576             va_start(ap, fmt);
577             vprintf(fmt, ap);
578             va_end(ap);
579             printf(":\n%*s  no possibilities available\n",
580                    solver_recurse_depth*4, "");
581         }
582 #endif
583         return -1;
584     }
585
586     return 0;
587 }
588
589 static int solver_intersect(struct solver_usage *usage,
590                             int start1, int step1, int start2, int step2
591 #ifdef STANDALONE_SOLVER
592                             , char *fmt, ...
593 #endif
594                             )
595 {
596     int c = usage->c, r = usage->r, cr = c*r;
597     int ret, i;
598
599     /*
600      * Loop over the first domain and see if there's any set bit
601      * not also in the second.
602      */
603     for (i = 0; i < cr; i++) {
604         int p = start1+i*step1;
605         if (usage->cube[p] &&
606             !(p >= start2 && p < start2+cr*step2 &&
607               (p - start2) % step2 == 0))
608             return 0;                  /* there is, so we can't deduce */
609     }
610
611     /*
612      * We have determined that all set bits in the first domain are
613      * within its overlap with the second. So loop over the second
614      * domain and remove all set bits that aren't also in that
615      * overlap; return +1 iff we actually _did_ anything.
616      */
617     ret = 0;
618     for (i = 0; i < cr; i++) {
619         int p = start2+i*step2;
620         if (usage->cube[p] &&
621             !(p >= start1 && p < start1+cr*step1 && (p - start1) % step1 == 0))
622         {
623 #ifdef STANDALONE_SOLVER
624             if (solver_show_working) {
625                 int px, py, pn;
626
627                 if (!ret) {
628                     va_list ap;
629                     printf("%*s", solver_recurse_depth*4, "");
630                     va_start(ap, fmt);
631                     vprintf(fmt, ap);
632                     va_end(ap);
633                     printf(":\n");
634                 }
635
636                 pn = 1 + p % cr;
637                 py = p / cr;
638                 px = py / cr;
639                 py %= cr;
640
641                 printf("%*s  ruling out %d at (%d,%d)\n",
642                        solver_recurse_depth*4, "", pn, 1+px, 1+YUNTRANS(py));
643             }
644 #endif
645             ret = +1;                  /* we did something */
646             usage->cube[p] = 0;
647         }
648     }
649
650     return ret;
651 }
652
653 struct solver_scratch {
654     unsigned char *grid, *rowidx, *colidx, *set;
655     int *mne;
656 };
657
658 static int solver_set(struct solver_usage *usage,
659                       struct solver_scratch *scratch,
660                       int start, int step1, int step2
661 #ifdef STANDALONE_SOLVER
662                       , char *fmt, ...
663 #endif
664                       )
665 {
666     int c = usage->c, r = usage->r, cr = c*r;
667     int i, j, n, count;
668     unsigned char *grid = scratch->grid;
669     unsigned char *rowidx = scratch->rowidx;
670     unsigned char *colidx = scratch->colidx;
671     unsigned char *set = scratch->set;
672
673     /*
674      * We are passed a cr-by-cr matrix of booleans. Our first job
675      * is to winnow it by finding any definite placements - i.e.
676      * any row with a solitary 1 - and discarding that row and the
677      * column containing the 1.
678      */
679     memset(rowidx, TRUE, cr);
680     memset(colidx, TRUE, cr);
681     for (i = 0; i < cr; i++) {
682         int count = 0, first = -1;
683         for (j = 0; j < cr; j++)
684             if (usage->cube[start+i*step1+j*step2])
685                 first = j, count++;
686
687         /*
688          * If count == 0, then there's a row with no 1s at all and
689          * the puzzle is internally inconsistent. However, we ought
690          * to have caught this already during the simpler reasoning
691          * methods, so we can safely fail an assertion if we reach
692          * this point here.
693          */
694         assert(count > 0);
695         if (count == 1)
696             rowidx[i] = colidx[first] = FALSE;
697     }
698
699     /*
700      * Convert each of rowidx/colidx from a list of 0s and 1s to a
701      * list of the indices of the 1s.
702      */
703     for (i = j = 0; i < cr; i++)
704         if (rowidx[i])
705             rowidx[j++] = i;
706     n = j;
707     for (i = j = 0; i < cr; i++)
708         if (colidx[i])
709             colidx[j++] = i;
710     assert(n == j);
711
712     /*
713      * And create the smaller matrix.
714      */
715     for (i = 0; i < n; i++)
716         for (j = 0; j < n; j++)
717             grid[i*cr+j] = usage->cube[start+rowidx[i]*step1+colidx[j]*step2];
718
719     /*
720      * Having done that, we now have a matrix in which every row
721      * has at least two 1s in. Now we search to see if we can find
722      * a rectangle of zeroes (in the set-theoretic sense of
723      * `rectangle', i.e. a subset of rows crossed with a subset of
724      * columns) whose width and height add up to n.
725      */
726
727     memset(set, 0, n);
728     count = 0;
729     while (1) {
730         /*
731          * We have a candidate set. If its size is <=1 or >=n-1
732          * then we move on immediately.
733          */
734         if (count > 1 && count < n-1) {
735             /*
736              * The number of rows we need is n-count. See if we can
737              * find that many rows which each have a zero in all
738              * the positions listed in `set'.
739              */
740             int rows = 0;
741             for (i = 0; i < n; i++) {
742                 int ok = TRUE;
743                 for (j = 0; j < n; j++)
744                     if (set[j] && grid[i*cr+j]) {
745                         ok = FALSE;
746                         break;
747                     }
748                 if (ok)
749                     rows++;
750             }
751
752             /*
753              * We expect never to be able to get _more_ than
754              * n-count suitable rows: this would imply that (for
755              * example) there are four numbers which between them
756              * have at most three possible positions, and hence it
757              * indicates a faulty deduction before this point or
758              * even a bogus clue.
759              */
760             if (rows > n - count) {
761 #ifdef STANDALONE_SOLVER
762                 if (solver_show_working) {
763                     va_list ap;
764                     printf("%*s", solver_recurse_depth*4,
765                            "");
766                     va_start(ap, fmt);
767                     vprintf(fmt, ap);
768                     va_end(ap);
769                     printf(":\n%*s  contradiction reached\n",
770                            solver_recurse_depth*4, "");
771                 }
772 #endif
773                 return -1;
774             }
775
776             if (rows >= n - count) {
777                 int progress = FALSE;
778
779                 /*
780                  * We've got one! Now, for each row which _doesn't_
781                  * satisfy the criterion, eliminate all its set
782                  * bits in the positions _not_ listed in `set'.
783                  * Return +1 (meaning progress has been made) if we
784                  * successfully eliminated anything at all.
785                  * 
786                  * This involves referring back through
787                  * rowidx/colidx in order to work out which actual
788                  * positions in the cube to meddle with.
789                  */
790                 for (i = 0; i < n; i++) {
791                     int ok = TRUE;
792                     for (j = 0; j < n; j++)
793                         if (set[j] && grid[i*cr+j]) {
794                             ok = FALSE;
795                             break;
796                         }
797                     if (!ok) {
798                         for (j = 0; j < n; j++)
799                             if (!set[j] && grid[i*cr+j]) {
800                                 int fpos = (start+rowidx[i]*step1+
801                                             colidx[j]*step2);
802 #ifdef STANDALONE_SOLVER
803                                 if (solver_show_working) {
804                                     int px, py, pn;
805
806                                     if (!progress) {
807                                         va_list ap;
808                                         printf("%*s", solver_recurse_depth*4,
809                                                "");
810                                         va_start(ap, fmt);
811                                         vprintf(fmt, ap);
812                                         va_end(ap);
813                                         printf(":\n");
814                                     }
815
816                                     pn = 1 + fpos % cr;
817                                     py = fpos / cr;
818                                     px = py / cr;
819                                     py %= cr;
820
821                                     printf("%*s  ruling out %d at (%d,%d)\n",
822                                            solver_recurse_depth*4, "",
823                                            pn, 1+px, 1+YUNTRANS(py));
824                                 }
825 #endif
826                                 progress = TRUE;
827                                 usage->cube[fpos] = FALSE;
828                             }
829                     }
830                 }
831
832                 if (progress) {
833                     return +1;
834                 }
835             }
836         }
837
838         /*
839          * Binary increment: change the rightmost 0 to a 1, and
840          * change all 1s to the right of it to 0s.
841          */
842         i = n;
843         while (i > 0 && set[i-1])
844             set[--i] = 0, count--;
845         if (i > 0)
846             set[--i] = 1, count++;
847         else
848             break;                     /* done */
849     }
850
851     return 0;
852 }
853
854 /*
855  * Try to find a number in the possible set of (x1,y1) which can be
856  * ruled out because it would leave no possibilities for (x2,y2).
857  */
858 static int solver_mne(struct solver_usage *usage,
859                       struct solver_scratch *scratch,
860                       int x1, int y1, int x2, int y2)
861 {
862     int c = usage->c, r = usage->r, cr = c*r;
863     int *nb[2];
864     unsigned char *set = scratch->set;
865     unsigned char *numbers = scratch->rowidx;
866     unsigned char *numbersleft = scratch->colidx;
867     int nnb, count;
868     int i, j, n, nbi;
869
870     nb[0] = scratch->mne;
871     nb[1] = scratch->mne + cr;
872
873     /*
874      * First, work out the mutual neighbour squares of the two. We
875      * can assert that they're not actually in the same block,
876      * which leaves two possibilities: they're in different block
877      * rows _and_ different block columns (thus their mutual
878      * neighbours are precisely the other two corners of the
879      * rectangle), or they're in the same row (WLOG) and different
880      * columns, in which case their mutual neighbours are the
881      * column of each block aligned with the other square.
882      * 
883      * We divide the mutual neighbours into two separate subsets
884      * nb[0] and nb[1]; squares in the same subset are not only
885      * adjacent to both our key squares, but are also always
886      * adjacent to one another.
887      */
888     if (x1 / r != x2 / r && y1 % r != y2 % r) {
889         /* Corners of the rectangle. */
890         nnb = 1;
891         nb[0][0] = cubepos(x2, y1, 1);
892         nb[1][0] = cubepos(x1, y2, 1);
893     } else if (x1 / r != x2 / r) {
894         /* Same row of blocks; different blocks within that row. */
895         int x1b = x1 - (x1 % r);
896         int x2b = x2 - (x2 % r);
897
898         nnb = r;
899         for (i = 0; i < r; i++) {
900             nb[0][i] = cubepos(x2b+i, y1, 1);
901             nb[1][i] = cubepos(x1b+i, y2, 1);
902         }
903     } else {
904         /* Same column of blocks; different blocks within that column. */
905         int y1b = y1 % r;
906         int y2b = y2 % r;
907
908         assert(y1 % r != y2 % r);
909
910         nnb = c;
911         for (i = 0; i < c; i++) {
912             nb[0][i] = cubepos(x2, y1b+i*r, 1);
913             nb[1][i] = cubepos(x1, y2b+i*r, 1);
914         }
915     }
916
917     /*
918      * Right. Now loop over each possible number.
919      */
920     for (n = 1; n <= cr; n++) {
921         if (!cube(x1, y1, n))
922             continue;
923         for (j = 0; j < cr; j++)
924             numbersleft[j] = cube(x2, y2, j+1);
925
926         /*
927          * Go over every possible subset of each neighbour list,
928          * and see if its union of possible numbers minus n has the
929          * same size as the subset. If so, add the numbers in that
930          * subset to the set of things which would be ruled out
931          * from (x2,y2) if n were placed at (x1,y1).
932          */
933         memset(set, 0, nnb);
934         count = 0;
935         while (1) {
936             /*
937              * Binary increment: change the rightmost 0 to a 1, and
938              * change all 1s to the right of it to 0s.
939              */
940             i = nnb;
941             while (i > 0 && set[i-1])
942                 set[--i] = 0, count--;
943             if (i > 0)
944                 set[--i] = 1, count++;
945             else
946                 break;                 /* done */
947
948             /*
949              * Examine this subset of each neighbour set.
950              */
951             for (nbi = 0; nbi < 2; nbi++) {
952                 int *nbs = nb[nbi];
953                 
954                 memset(numbers, 0, cr);
955
956                 for (i = 0; i < nnb; i++)
957                     if (set[i])
958                         for (j = 0; j < cr; j++)
959                             if (j != n-1 && usage->cube[nbs[i] + j])
960                                 numbers[j] = 1;
961
962                 for (i = j = 0; j < cr; j++)
963                     i += numbers[j];
964
965                 if (i == count) {
966                     /*
967                      * Got one. This subset of nbs, in the absence
968                      * of n, would definitely contain all the
969                      * numbers listed in `numbers'. Rule them out
970                      * of `numbersleft'.
971                      */
972                     for (j = 0; j < cr; j++)
973                         if (numbers[j])
974                             numbersleft[j] = 0;
975                 }
976             }
977         }
978
979         /*
980          * If we've got nothing left in `numbersleft', we have a
981          * successful mutual neighbour elimination.
982          */
983         for (j = 0; j < cr; j++)
984             if (numbersleft[j])
985                 break;
986
987         if (j == cr) {
988 #ifdef STANDALONE_SOLVER
989             if (solver_show_working) {
990                 printf("%*smutual neighbour elimination, (%d,%d) vs (%d,%d):\n",
991                        solver_recurse_depth*4, "",
992                        1+x1, 1+YUNTRANS(y1), 1+x2, 1+YUNTRANS(y2));
993                 printf("%*s  ruling out %d at (%d,%d)\n",
994                        solver_recurse_depth*4, "",
995                        n, 1+x1, 1+YUNTRANS(y1));
996             }
997 #endif
998             cube(x1, y1, n) = FALSE;
999             return +1;
1000         }
1001     }
1002
1003     return 0;                          /* nothing found */
1004 }
1005
1006 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1007 {
1008     struct solver_scratch *scratch = snew(struct solver_scratch);
1009     int cr = usage->cr;
1010     scratch->grid = snewn(cr*cr, unsigned char);
1011     scratch->rowidx = snewn(cr, unsigned char);
1012     scratch->colidx = snewn(cr, unsigned char);
1013     scratch->set = snewn(cr, unsigned char);
1014     scratch->mne = snewn(2*cr, int);
1015     return scratch;
1016 }
1017
1018 static void solver_free_scratch(struct solver_scratch *scratch)
1019 {
1020     sfree(scratch->mne);
1021     sfree(scratch->set);
1022     sfree(scratch->colidx);
1023     sfree(scratch->rowidx);
1024     sfree(scratch->grid);
1025     sfree(scratch);
1026 }
1027
1028 static int solver(int c, int r, digit *grid, int maxdiff)
1029 {
1030     struct solver_usage *usage;
1031     struct solver_scratch *scratch;
1032     int cr = c*r;
1033     int x, y, x2, y2, n, ret;
1034     int diff = DIFF_BLOCK;
1035
1036     /*
1037      * Set up a usage structure as a clean slate (everything
1038      * possible).
1039      */
1040     usage = snew(struct solver_usage);
1041     usage->c = c;
1042     usage->r = r;
1043     usage->cr = cr;
1044     usage->cube = snewn(cr*cr*cr, unsigned char);
1045     usage->grid = grid;                /* write straight back to the input */
1046     memset(usage->cube, TRUE, cr*cr*cr);
1047
1048     usage->row = snewn(cr * cr, unsigned char);
1049     usage->col = snewn(cr * cr, unsigned char);
1050     usage->blk = snewn(cr * cr, unsigned char);
1051     memset(usage->row, FALSE, cr * cr);
1052     memset(usage->col, FALSE, cr * cr);
1053     memset(usage->blk, FALSE, cr * cr);
1054
1055     scratch = solver_new_scratch(usage);
1056
1057     /*
1058      * Place all the clue numbers we are given.
1059      */
1060     for (x = 0; x < cr; x++)
1061         for (y = 0; y < cr; y++)
1062             if (grid[y*cr+x])
1063                 solver_place(usage, x, YTRANS(y), grid[y*cr+x]);
1064
1065     /*
1066      * Now loop over the grid repeatedly trying all permitted modes
1067      * of reasoning. The loop terminates if we complete an
1068      * iteration without making any progress; we then return
1069      * failure or success depending on whether the grid is full or
1070      * not.
1071      */
1072     while (1) {
1073         /*
1074          * I'd like to write `continue;' inside each of the
1075          * following loops, so that the solver returns here after
1076          * making some progress. However, I can't specify that I
1077          * want to continue an outer loop rather than the innermost
1078          * one, so I'm apologetically resorting to a goto.
1079          */
1080         cont:
1081
1082         /*
1083          * Blockwise positional elimination.
1084          */
1085         for (x = 0; x < cr; x += r)
1086             for (y = 0; y < r; y++)
1087                 for (n = 1; n <= cr; n++)
1088                     if (!usage->blk[(y*c+(x/r))*cr+n-1]) {
1089                         ret = solver_elim(usage, cubepos(x,y,n), r*cr
1090 #ifdef STANDALONE_SOLVER
1091                                           , "positional elimination,"
1092                                           " %d in block (%d,%d)", n, 1+x/r, 1+y
1093 #endif
1094                                           );
1095                         if (ret < 0) {
1096                             diff = DIFF_IMPOSSIBLE;
1097                             goto got_result;
1098                         } else if (ret > 0) {
1099                             diff = max(diff, DIFF_BLOCK);
1100                             goto cont;
1101                         }
1102                     }
1103
1104         if (maxdiff <= DIFF_BLOCK)
1105             break;
1106
1107         /*
1108          * Row-wise positional elimination.
1109          */
1110         for (y = 0; y < cr; y++)
1111             for (n = 1; n <= cr; n++)
1112                 if (!usage->row[y*cr+n-1]) {
1113                     ret = solver_elim(usage, cubepos(0,y,n), cr*cr
1114 #ifdef STANDALONE_SOLVER
1115                                       , "positional elimination,"
1116                                       " %d in row %d", n, 1+YUNTRANS(y)
1117 #endif
1118                                       );
1119                     if (ret < 0) {
1120                         diff = DIFF_IMPOSSIBLE;
1121                         goto got_result;
1122                     } else if (ret > 0) {
1123                         diff = max(diff, DIFF_SIMPLE);
1124                         goto cont;
1125                     }
1126                 }
1127         /*
1128          * Column-wise positional elimination.
1129          */
1130         for (x = 0; x < cr; x++)
1131             for (n = 1; n <= cr; n++)
1132                 if (!usage->col[x*cr+n-1]) {
1133                     ret = solver_elim(usage, cubepos(x,0,n), cr
1134 #ifdef STANDALONE_SOLVER
1135                                       , "positional elimination,"
1136                                       " %d in column %d", n, 1+x
1137 #endif
1138                                       );
1139                     if (ret < 0) {
1140                         diff = DIFF_IMPOSSIBLE;
1141                         goto got_result;
1142                     } else if (ret > 0) {
1143                         diff = max(diff, DIFF_SIMPLE);
1144                         goto cont;
1145                     }
1146                 }
1147
1148         /*
1149          * Numeric elimination.
1150          */
1151         for (x = 0; x < cr; x++)
1152             for (y = 0; y < cr; y++)
1153                 if (!usage->grid[YUNTRANS(y)*cr+x]) {
1154                     ret = solver_elim(usage, cubepos(x,y,1), 1
1155 #ifdef STANDALONE_SOLVER
1156                                       , "numeric elimination at (%d,%d)", 1+x,
1157                                       1+YUNTRANS(y)
1158 #endif
1159                                       );
1160                     if (ret < 0) {
1161                         diff = DIFF_IMPOSSIBLE;
1162                         goto got_result;
1163                     } else if (ret > 0) {
1164                         diff = max(diff, DIFF_SIMPLE);
1165                         goto cont;
1166                     }
1167                 }
1168
1169         if (maxdiff <= DIFF_SIMPLE)
1170             break;
1171
1172         /*
1173          * Intersectional analysis, rows vs blocks.
1174          */
1175         for (y = 0; y < cr; y++)
1176             for (x = 0; x < cr; x += r)
1177                 for (n = 1; n <= cr; n++)
1178                     /*
1179                      * solver_intersect() never returns -1.
1180                      */
1181                     if (!usage->row[y*cr+n-1] &&
1182                         !usage->blk[((y%r)*c+(x/r))*cr+n-1] &&
1183                         (solver_intersect(usage, cubepos(0,y,n), cr*cr,
1184                                           cubepos(x,y%r,n), r*cr
1185 #ifdef STANDALONE_SOLVER
1186                                           , "intersectional analysis,"
1187                                           " %d in row %d vs block (%d,%d)",
1188                                           n, 1+YUNTRANS(y), 1+x/r, 1+y%r
1189 #endif
1190                                           ) ||
1191                          solver_intersect(usage, cubepos(x,y%r,n), r*cr,
1192                                           cubepos(0,y,n), cr*cr
1193 #ifdef STANDALONE_SOLVER
1194                                           , "intersectional analysis,"
1195                                           " %d in block (%d,%d) vs row %d",
1196                                           n, 1+x/r, 1+y%r, 1+YUNTRANS(y)
1197 #endif
1198                                           ))) {
1199                         diff = max(diff, DIFF_INTERSECT);
1200                         goto cont;
1201                     }
1202
1203         /*
1204          * Intersectional analysis, columns vs blocks.
1205          */
1206         for (x = 0; x < cr; x++)
1207             for (y = 0; y < r; y++)
1208                 for (n = 1; n <= cr; n++)
1209                     if (!usage->col[x*cr+n-1] &&
1210                         !usage->blk[(y*c+(x/r))*cr+n-1] &&
1211                         (solver_intersect(usage, cubepos(x,0,n), cr,
1212                                           cubepos((x/r)*r,y,n), r*cr
1213 #ifdef STANDALONE_SOLVER
1214                                           , "intersectional analysis,"
1215                                           " %d in column %d vs block (%d,%d)",
1216                                           n, 1+x, 1+x/r, 1+y
1217 #endif
1218                                           ) ||
1219                          solver_intersect(usage, cubepos((x/r)*r,y,n), r*cr,
1220                                           cubepos(x,0,n), cr
1221 #ifdef STANDALONE_SOLVER
1222                                           , "intersectional analysis,"
1223                                           " %d in block (%d,%d) vs column %d",
1224                                           n, 1+x/r, 1+y, 1+x
1225 #endif
1226                                           ))) {
1227                         diff = max(diff, DIFF_INTERSECT);
1228                         goto cont;
1229                     }
1230
1231         if (maxdiff <= DIFF_INTERSECT)
1232             break;
1233
1234         /*
1235          * Blockwise set elimination.
1236          */
1237         for (x = 0; x < cr; x += r)
1238             for (y = 0; y < r; y++) {
1239                 ret = solver_set(usage, scratch, cubepos(x,y,1), r*cr, 1
1240 #ifdef STANDALONE_SOLVER
1241                                  , "set elimination, block (%d,%d)", 1+x/r, 1+y
1242 #endif
1243                                  );
1244                 if (ret < 0) {
1245                     diff = DIFF_IMPOSSIBLE;
1246                     goto got_result;
1247                 } else if (ret > 0) {
1248                     diff = max(diff, DIFF_SET);
1249                     goto cont;
1250                 }
1251             }
1252
1253         /*
1254          * Row-wise set elimination.
1255          */
1256         for (y = 0; y < cr; y++) {
1257             ret = solver_set(usage, scratch, cubepos(0,y,1), cr*cr, 1
1258 #ifdef STANDALONE_SOLVER
1259                              , "set elimination, row %d", 1+YUNTRANS(y)
1260 #endif
1261                              );
1262             if (ret < 0) {
1263                 diff = DIFF_IMPOSSIBLE;
1264                 goto got_result;
1265             } else if (ret > 0) {
1266                 diff = max(diff, DIFF_SET);
1267                 goto cont;
1268             }
1269         }
1270
1271         /*
1272          * Column-wise set elimination.
1273          */
1274         for (x = 0; x < cr; x++) {
1275             ret = solver_set(usage, scratch, cubepos(x,0,1), cr, 1
1276 #ifdef STANDALONE_SOLVER
1277                              , "set elimination, column %d", 1+x
1278 #endif
1279                              );
1280             if (ret < 0) {
1281                 diff = DIFF_IMPOSSIBLE;
1282                 goto got_result;
1283             } else if (ret > 0) {
1284                 diff = max(diff, DIFF_SET);
1285                 goto cont;
1286             }
1287         }
1288
1289         /*
1290          * Mutual neighbour elimination.
1291          */
1292         for (y = 0; y+1 < cr; y++) {
1293             for (x = 0; x+1 < cr; x++) {
1294                 for (y2 = y+1; y2 < cr; y2++) {
1295                     for (x2 = x+1; x2 < cr; x2++) {
1296                         /*
1297                          * Can't do mutual neighbour elimination
1298                          * between elements of the same actual
1299                          * block.
1300                          */
1301                         if (x/r == x2/r && y%r == y2%r)
1302                             continue;
1303
1304                         /*
1305                          * Otherwise, try (x,y) vs (x2,y2) in both
1306                          * directions, and likewise (x2,y) vs
1307                          * (x,y2).
1308                          */
1309                         if (!usage->grid[YUNTRANS(y)*cr+x] &&
1310                             !usage->grid[YUNTRANS(y2)*cr+x2] &&
1311                             (solver_mne(usage, scratch, x, y, x2, y2) ||
1312                              solver_mne(usage, scratch, x2, y2, x, y))) {
1313                             diff = max(diff, DIFF_NEIGHBOUR);
1314                             goto cont;
1315                         }
1316                         if (!usage->grid[YUNTRANS(y)*cr+x2] &&
1317                             !usage->grid[YUNTRANS(y2)*cr+x] &&
1318                             (solver_mne(usage, scratch, x2, y, x, y2) ||
1319                              solver_mne(usage, scratch, x, y2, x2, y))) {
1320                             diff = max(diff, DIFF_NEIGHBOUR);
1321                             goto cont;
1322                         }
1323                     }
1324                 }
1325             }
1326         }
1327
1328         /*
1329          * If we reach here, we have made no deductions in this
1330          * iteration, so the algorithm terminates.
1331          */
1332         break;
1333     }
1334
1335     /*
1336      * Last chance: if we haven't fully solved the puzzle yet, try
1337      * recursing based on guesses for a particular square. We pick
1338      * one of the most constrained empty squares we can find, which
1339      * has the effect of pruning the search tree as much as
1340      * possible.
1341      */
1342     if (maxdiff >= DIFF_RECURSIVE) {
1343         int best, bestcount;
1344
1345         best = -1;
1346         bestcount = cr+1;
1347
1348         for (y = 0; y < cr; y++)
1349             for (x = 0; x < cr; x++)
1350                 if (!grid[y*cr+x]) {
1351                     int count;
1352
1353                     /*
1354                      * An unfilled square. Count the number of
1355                      * possible digits in it.
1356                      */
1357                     count = 0;
1358                     for (n = 1; n <= cr; n++)
1359                         if (cube(x,YTRANS(y),n))
1360                             count++;
1361
1362                     /*
1363                      * We should have found any impossibilities
1364                      * already, so this can safely be an assert.
1365                      */
1366                     assert(count > 1);
1367
1368                     if (count < bestcount) {
1369                         bestcount = count;
1370                         best = y*cr+x;
1371                     }
1372                 }
1373
1374         if (best != -1) {
1375             int i, j;
1376             digit *list, *ingrid, *outgrid;
1377
1378             diff = DIFF_IMPOSSIBLE;    /* no solution found yet */
1379
1380             /*
1381              * Attempt recursion.
1382              */
1383             y = best / cr;
1384             x = best % cr;
1385
1386             list = snewn(cr, digit);
1387             ingrid = snewn(cr * cr, digit);
1388             outgrid = snewn(cr * cr, digit);
1389             memcpy(ingrid, grid, cr * cr);
1390
1391             /* Make a list of the possible digits. */
1392             for (j = 0, n = 1; n <= cr; n++)
1393                 if (cube(x,YTRANS(y),n))
1394                     list[j++] = n;
1395
1396 #ifdef STANDALONE_SOLVER
1397             if (solver_show_working) {
1398                 char *sep = "";
1399                 printf("%*srecursing on (%d,%d) [",
1400                        solver_recurse_depth*4, "", x, y);
1401                 for (i = 0; i < j; i++) {
1402                     printf("%s%d", sep, list[i]);
1403                     sep = " or ";
1404                 }
1405                 printf("]\n");
1406             }
1407 #endif
1408
1409             /*
1410              * And step along the list, recursing back into the
1411              * main solver at every stage.
1412              */
1413             for (i = 0; i < j; i++) {
1414                 int ret;
1415
1416                 memcpy(outgrid, ingrid, cr * cr);
1417                 outgrid[y*cr+x] = list[i];
1418
1419 #ifdef STANDALONE_SOLVER
1420                 if (solver_show_working)
1421                     printf("%*sguessing %d at (%d,%d)\n",
1422                            solver_recurse_depth*4, "", list[i], x, y);
1423                 solver_recurse_depth++;
1424 #endif
1425
1426                 ret = solver(c, r, outgrid, maxdiff);
1427
1428 #ifdef STANDALONE_SOLVER
1429                 solver_recurse_depth--;
1430                 if (solver_show_working) {
1431                     printf("%*sretracting %d at (%d,%d)\n",
1432                            solver_recurse_depth*4, "", list[i], x, y);
1433                 }
1434 #endif
1435
1436                 /*
1437                  * If we have our first solution, copy it into the
1438                  * grid we will return.
1439                  */
1440                 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1441                     memcpy(grid, outgrid, cr*cr);
1442
1443                 if (ret == DIFF_AMBIGUOUS)
1444                     diff = DIFF_AMBIGUOUS;
1445                 else if (ret == DIFF_IMPOSSIBLE)
1446                     /* do not change our return value */;
1447                 else {
1448                     /* the recursion turned up exactly one solution */
1449                     if (diff == DIFF_IMPOSSIBLE)
1450                         diff = DIFF_RECURSIVE;
1451                     else
1452                         diff = DIFF_AMBIGUOUS;
1453                 }
1454
1455                 /*
1456                  * As soon as we've found more than one solution,
1457                  * give up immediately.
1458                  */
1459                 if (diff == DIFF_AMBIGUOUS)
1460                     break;
1461             }
1462
1463             sfree(outgrid);
1464             sfree(ingrid);
1465             sfree(list);
1466         }
1467
1468     } else {
1469         /*
1470          * We're forbidden to use recursion, so we just see whether
1471          * our grid is fully solved, and return DIFF_IMPOSSIBLE
1472          * otherwise.
1473          */
1474         for (y = 0; y < cr; y++)
1475             for (x = 0; x < cr; x++)
1476                 if (!grid[y*cr+x])
1477                     diff = DIFF_IMPOSSIBLE;
1478     }
1479
1480     got_result:;
1481
1482 #ifdef STANDALONE_SOLVER
1483     if (solver_show_working)
1484         printf("%*s%s found\n",
1485                solver_recurse_depth*4, "",
1486                diff == DIFF_IMPOSSIBLE ? "no solution" :
1487                diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1488                "one solution");
1489 #endif
1490
1491     sfree(usage->cube);
1492     sfree(usage->row);
1493     sfree(usage->col);
1494     sfree(usage->blk);
1495     sfree(usage);
1496
1497     solver_free_scratch(scratch);
1498
1499     return diff;
1500 }
1501
1502 /* ----------------------------------------------------------------------
1503  * End of solver code.
1504  */
1505
1506 /* ----------------------------------------------------------------------
1507  * Solo filled-grid generator.
1508  *
1509  * This grid generator works by essentially trying to solve a grid
1510  * starting from no clues, and not worrying that there's more than
1511  * one possible solution. Unfortunately, it isn't computationally
1512  * feasible to do this by calling the above solver with an empty
1513  * grid, because that one needs to allocate a lot of scratch space
1514  * at every recursion level. Instead, I have a much simpler
1515  * algorithm which I shamelessly copied from a Python solver
1516  * written by Andrew Wilkinson (which is GPLed, but I've reused
1517  * only ideas and no code). It mostly just does the obvious
1518  * recursive thing: pick an empty square, put one of the possible
1519  * digits in it, recurse until all squares are filled, backtrack
1520  * and change some choices if necessary.
1521  *
1522  * The clever bit is that every time it chooses which square to
1523  * fill in next, it does so by counting the number of _possible_
1524  * numbers that can go in each square, and it prioritises so that
1525  * it picks a square with the _lowest_ number of possibilities. The
1526  * idea is that filling in lots of the obvious bits (particularly
1527  * any squares with only one possibility) will cut down on the list
1528  * of possibilities for other squares and hence reduce the enormous
1529  * search space as much as possible as early as possible.
1530  */
1531
1532 /*
1533  * Internal data structure used in gridgen to keep track of
1534  * progress.
1535  */
1536 struct gridgen_coord { int x, y, r; };
1537 struct gridgen_usage {
1538     int c, r, cr;                      /* cr == c*r */
1539     /* grid is a copy of the input grid, modified as we go along */
1540     digit *grid;
1541     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1542     unsigned char *row;
1543     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1544     unsigned char *col;
1545     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1546     unsigned char *blk;
1547     /* This lists all the empty spaces remaining in the grid. */
1548     struct gridgen_coord *spaces;
1549     int nspaces;
1550     /* If we need randomisation in the solve, this is our random state. */
1551     random_state *rs;
1552 };
1553
1554 /*
1555  * The real recursive step in the generating function.
1556  */
1557 static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1558 {
1559     int c = usage->c, r = usage->r, cr = usage->cr;
1560     int i, j, n, sx, sy, bestm, bestr, ret;
1561     int *digits;
1562
1563     /*
1564      * Firstly, check for completion! If there are no spaces left
1565      * in the grid, we have a solution.
1566      */
1567     if (usage->nspaces == 0) {
1568         memcpy(grid, usage->grid, cr * cr);
1569         return TRUE;
1570     }
1571
1572     /*
1573      * Otherwise, there must be at least one space. Find the most
1574      * constrained space, using the `r' field as a tie-breaker.
1575      */
1576     bestm = cr+1;                      /* so that any space will beat it */
1577     bestr = 0;
1578     i = sx = sy = -1;
1579     for (j = 0; j < usage->nspaces; j++) {
1580         int x = usage->spaces[j].x, y = usage->spaces[j].y;
1581         int m;
1582
1583         /*
1584          * Find the number of digits that could go in this space.
1585          */
1586         m = 0;
1587         for (n = 0; n < cr; n++)
1588             if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1589                 !usage->blk[((y/c)*c+(x/r))*cr+n])
1590                 m++;
1591
1592         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1593             bestm = m;
1594             bestr = usage->spaces[j].r;
1595             sx = x;
1596             sy = y;
1597             i = j;
1598         }
1599     }
1600
1601     /*
1602      * Swap that square into the final place in the spaces array,
1603      * so that decrementing nspaces will remove it from the list.
1604      */
1605     if (i != usage->nspaces-1) {
1606         struct gridgen_coord t;
1607         t = usage->spaces[usage->nspaces-1];
1608         usage->spaces[usage->nspaces-1] = usage->spaces[i];
1609         usage->spaces[i] = t;
1610     }
1611
1612     /*
1613      * Now we've decided which square to start our recursion at,
1614      * simply go through all possible values, shuffling them
1615      * randomly first if necessary.
1616      */
1617     digits = snewn(bestm, int);
1618     j = 0;
1619     for (n = 0; n < cr; n++)
1620         if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1621             !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
1622             digits[j++] = n+1;
1623         }
1624
1625     if (usage->rs)
1626         shuffle(digits, j, sizeof(*digits), usage->rs);
1627
1628     /* And finally, go through the digit list and actually recurse. */
1629     ret = FALSE;
1630     for (i = 0; i < j; i++) {
1631         n = digits[i];
1632
1633         /* Update the usage structure to reflect the placing of this digit. */
1634         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1635             usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
1636         usage->grid[sy*cr+sx] = n;
1637         usage->nspaces--;
1638
1639         /* Call the solver recursively. Stop when we find a solution. */
1640         if (gridgen_real(usage, grid))
1641             ret = TRUE;
1642
1643         /* Revert the usage structure. */
1644         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1645             usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
1646         usage->grid[sy*cr+sx] = 0;
1647         usage->nspaces++;
1648
1649         if (ret)
1650             break;
1651     }
1652
1653     sfree(digits);
1654     return ret;
1655 }
1656
1657 /*
1658  * Entry point to generator. You give it dimensions and a starting
1659  * grid, which is simply an array of cr*cr digits.
1660  */
1661 static void gridgen(int c, int r, digit *grid, random_state *rs)
1662 {
1663     struct gridgen_usage *usage;
1664     int x, y, cr = c*r;
1665
1666     /*
1667      * Clear the grid to start with.
1668      */
1669     memset(grid, 0, cr*cr);
1670
1671     /*
1672      * Create a gridgen_usage structure.
1673      */
1674     usage = snew(struct gridgen_usage);
1675
1676     usage->c = c;
1677     usage->r = r;
1678     usage->cr = cr;
1679
1680     usage->grid = snewn(cr * cr, digit);
1681     memcpy(usage->grid, grid, cr * cr);
1682
1683     usage->row = snewn(cr * cr, unsigned char);
1684     usage->col = snewn(cr * cr, unsigned char);
1685     usage->blk = snewn(cr * cr, unsigned char);
1686     memset(usage->row, FALSE, cr * cr);
1687     memset(usage->col, FALSE, cr * cr);
1688     memset(usage->blk, FALSE, cr * cr);
1689
1690     usage->spaces = snewn(cr * cr, struct gridgen_coord);
1691     usage->nspaces = 0;
1692
1693     usage->rs = rs;
1694
1695     /*
1696      * Initialise the list of grid spaces.
1697      */
1698     for (y = 0; y < cr; y++) {
1699         for (x = 0; x < cr; x++) {
1700             usage->spaces[usage->nspaces].x = x;
1701             usage->spaces[usage->nspaces].y = y;
1702             usage->spaces[usage->nspaces].r = random_bits(rs, 31);
1703             usage->nspaces++;
1704         }
1705     }
1706
1707     /*
1708      * Run the real generator function.
1709      */
1710     gridgen_real(usage, grid);
1711
1712     /*
1713      * Clean up the usage structure now we have our answer.
1714      */
1715     sfree(usage->spaces);
1716     sfree(usage->blk);
1717     sfree(usage->col);
1718     sfree(usage->row);
1719     sfree(usage->grid);
1720     sfree(usage);
1721 }
1722
1723 /* ----------------------------------------------------------------------
1724  * End of grid generator code.
1725  */
1726
1727 /*
1728  * Check whether a grid contains a valid complete puzzle.
1729  */
1730 static int check_valid(int c, int r, digit *grid)
1731 {
1732     int cr = c*r;
1733     unsigned char *used;
1734     int x, y, n;
1735
1736     used = snewn(cr, unsigned char);
1737
1738     /*
1739      * Check that each row contains precisely one of everything.
1740      */
1741     for (y = 0; y < cr; y++) {
1742         memset(used, FALSE, cr);
1743         for (x = 0; x < cr; x++)
1744             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1745                 used[grid[y*cr+x]-1] = TRUE;
1746         for (n = 0; n < cr; n++)
1747             if (!used[n]) {
1748                 sfree(used);
1749                 return FALSE;
1750             }
1751     }
1752
1753     /*
1754      * Check that each column contains precisely one of everything.
1755      */
1756     for (x = 0; x < cr; x++) {
1757         memset(used, FALSE, cr);
1758         for (y = 0; y < cr; y++)
1759             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1760                 used[grid[y*cr+x]-1] = TRUE;
1761         for (n = 0; n < cr; n++)
1762             if (!used[n]) {
1763                 sfree(used);
1764                 return FALSE;
1765             }
1766     }
1767
1768     /*
1769      * Check that each block contains precisely one of everything.
1770      */
1771     for (x = 0; x < cr; x += r) {
1772         for (y = 0; y < cr; y += c) {
1773             int xx, yy;
1774             memset(used, FALSE, cr);
1775             for (xx = x; xx < x+r; xx++)
1776                 for (yy = 0; yy < y+c; yy++)
1777                     if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
1778                         used[grid[yy*cr+xx]-1] = TRUE;
1779             for (n = 0; n < cr; n++)
1780                 if (!used[n]) {
1781                     sfree(used);
1782                     return FALSE;
1783                 }
1784         }
1785     }
1786
1787     sfree(used);
1788     return TRUE;
1789 }
1790
1791 static int symmetries(game_params *params, int x, int y, int *output, int s)
1792 {
1793     int c = params->c, r = params->r, cr = c*r;
1794     int i = 0;
1795
1796 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
1797
1798     ADD(x, y);
1799
1800     switch (s) {
1801       case SYMM_NONE:
1802         break;                         /* just x,y is all we need */
1803       case SYMM_ROT2:
1804         ADD(cr - 1 - x, cr - 1 - y);
1805         break;
1806       case SYMM_ROT4:
1807         ADD(cr - 1 - y, x);
1808         ADD(y, cr - 1 - x);
1809         ADD(cr - 1 - x, cr - 1 - y);
1810         break;
1811       case SYMM_REF2:
1812         ADD(cr - 1 - x, y);
1813         break;
1814       case SYMM_REF2D:
1815         ADD(y, x);
1816         break;
1817       case SYMM_REF4:
1818         ADD(cr - 1 - x, y);
1819         ADD(x, cr - 1 - y);
1820         ADD(cr - 1 - x, cr - 1 - y);
1821         break;
1822       case SYMM_REF4D:
1823         ADD(y, x);
1824         ADD(cr - 1 - x, cr - 1 - y);
1825         ADD(cr - 1 - y, cr - 1 - x);
1826         break;
1827       case SYMM_REF8:
1828         ADD(cr - 1 - x, y);
1829         ADD(x, cr - 1 - y);
1830         ADD(cr - 1 - x, cr - 1 - y);
1831         ADD(y, x);
1832         ADD(y, cr - 1 - x);
1833         ADD(cr - 1 - y, x);
1834         ADD(cr - 1 - y, cr - 1 - x);
1835         break;
1836     }
1837
1838 #undef ADD
1839
1840     return i;
1841 }
1842
1843 static char *encode_solve_move(int cr, digit *grid)
1844 {
1845     int i, len;
1846     char *ret, *p, *sep;
1847
1848     /*
1849      * It's surprisingly easy to work out _exactly_ how long this
1850      * string needs to be. To decimal-encode all the numbers from 1
1851      * to n:
1852      * 
1853      *  - every number has a units digit; total is n.
1854      *  - all numbers above 9 have a tens digit; total is max(n-9,0).
1855      *  - all numbers above 99 have a hundreds digit; total is max(n-99,0).
1856      *  - and so on.
1857      */
1858     len = 0;
1859     for (i = 1; i <= cr; i *= 10)
1860         len += max(cr - i + 1, 0);
1861     len += cr;                 /* don't forget the commas */
1862     len *= cr;                 /* there are cr rows of these */
1863
1864     /*
1865      * Now len is one bigger than the total size of the
1866      * comma-separated numbers (because we counted an
1867      * additional leading comma). We need to have a leading S
1868      * and a trailing NUL, so we're off by one in total.
1869      */
1870     len++;
1871
1872     ret = snewn(len, char);
1873     p = ret;
1874     *p++ = 'S';
1875     sep = "";
1876     for (i = 0; i < cr*cr; i++) {
1877         p += sprintf(p, "%s%d", sep, grid[i]);
1878         sep = ",";
1879     }
1880     *p++ = '\0';
1881     assert(p - ret == len);
1882
1883     return ret;
1884 }
1885
1886 static char *new_game_desc(game_params *params, random_state *rs,
1887                            char **aux, int interactive)
1888 {
1889     int c = params->c, r = params->r, cr = c*r;
1890     int area = cr*cr;
1891     digit *grid, *grid2;
1892     struct xy { int x, y; } *locs;
1893     int nlocs;
1894     char *desc;
1895     int coords[16], ncoords;
1896     int maxdiff;
1897     int x, y, i, j;
1898
1899     /*
1900      * Adjust the maximum difficulty level to be consistent with
1901      * the puzzle size: all 2x2 puzzles appear to be Trivial
1902      * (DIFF_BLOCK) so we cannot hold out for even a Basic
1903      * (DIFF_SIMPLE) one.
1904      */
1905     maxdiff = params->diff;
1906     if (c == 2 && r == 2)
1907         maxdiff = DIFF_BLOCK;
1908
1909     grid = snewn(area, digit);
1910     locs = snewn(area, struct xy);
1911     grid2 = snewn(area, digit);
1912
1913     /*
1914      * Loop until we get a grid of the required difficulty. This is
1915      * nasty, but it seems to be unpleasantly hard to generate
1916      * difficult grids otherwise.
1917      */
1918     do {
1919         /*
1920          * Generate a random solved state.
1921          */
1922         gridgen(c, r, grid, rs);
1923         assert(check_valid(c, r, grid));
1924
1925         /*
1926          * Save the solved grid in aux.
1927          */
1928         {
1929             /*
1930              * We might already have written *aux the last time we
1931              * went round this loop, in which case we should free
1932              * the old aux before overwriting it with the new one.
1933              */
1934             if (*aux) {
1935                 sfree(*aux);
1936             }
1937
1938             *aux = encode_solve_move(cr, grid);
1939         }
1940
1941         /*
1942          * Now we have a solved grid, start removing things from it
1943          * while preserving solubility.
1944          */
1945
1946         /*
1947          * Find the set of equivalence classes of squares permitted
1948          * by the selected symmetry. We do this by enumerating all
1949          * the grid squares which have no symmetric companion
1950          * sorting lower than themselves.
1951          */
1952         nlocs = 0;
1953         for (y = 0; y < cr; y++)
1954             for (x = 0; x < cr; x++) {
1955                 int i = y*cr+x;
1956                 int j;
1957
1958                 ncoords = symmetries(params, x, y, coords, params->symm);
1959                 for (j = 0; j < ncoords; j++)
1960                     if (coords[2*j+1]*cr+coords[2*j] < i)
1961                         break;
1962                 if (j == ncoords) {
1963                     locs[nlocs].x = x;
1964                     locs[nlocs].y = y;
1965                     nlocs++;
1966                 }
1967             }
1968
1969         /*
1970          * Now shuffle that list.
1971          */
1972         shuffle(locs, nlocs, sizeof(*locs), rs);
1973
1974         /*
1975          * Now loop over the shuffled list and, for each element,
1976          * see whether removing that element (and its reflections)
1977          * from the grid will still leave the grid soluble.
1978          */
1979         for (i = 0; i < nlocs; i++) {
1980             int ret;
1981
1982             x = locs[i].x;
1983             y = locs[i].y;
1984
1985             memcpy(grid2, grid, area);
1986             ncoords = symmetries(params, x, y, coords, params->symm);
1987             for (j = 0; j < ncoords; j++)
1988                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1989
1990             ret = solver(c, r, grid2, maxdiff);
1991             if (ret != DIFF_IMPOSSIBLE && ret != DIFF_AMBIGUOUS) {
1992                 for (j = 0; j < ncoords; j++)
1993                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1994             }
1995         }
1996
1997         memcpy(grid2, grid, area);
1998     } while (solver(c, r, grid2, maxdiff) < maxdiff);
1999
2000     sfree(grid2);
2001     sfree(locs);
2002
2003     /*
2004      * Now we have the grid as it will be presented to the user.
2005      * Encode it in a game desc.
2006      */
2007     {
2008         char *p;
2009         int run, i;
2010
2011         desc = snewn(5 * area, char);
2012         p = desc;
2013         run = 0;
2014         for (i = 0; i <= area; i++) {
2015             int n = (i < area ? grid[i] : -1);
2016
2017             if (!n)
2018                 run++;
2019             else {
2020                 if (run) {
2021                     while (run > 0) {
2022                         int c = 'a' - 1 + run;
2023                         if (run > 26)
2024                             c = 'z';
2025                         *p++ = c;
2026                         run -= c - ('a' - 1);
2027                     }
2028                 } else {
2029                     /*
2030                      * If there's a number in the very top left or
2031                      * bottom right, there's no point putting an
2032                      * unnecessary _ before or after it.
2033                      */
2034                     if (p > desc && n > 0)
2035                         *p++ = '_';
2036                 }
2037                 if (n > 0)
2038                     p += sprintf(p, "%d", n);
2039                 run = 0;
2040             }
2041         }
2042         assert(p - desc < 5 * area);
2043         *p++ = '\0';
2044         desc = sresize(desc, p - desc, char);
2045     }
2046
2047     sfree(grid);
2048
2049     return desc;
2050 }
2051
2052 static char *validate_desc(game_params *params, char *desc)
2053 {
2054     int area = params->r * params->r * params->c * params->c;
2055     int squares = 0;
2056
2057     while (*desc) {
2058         int n = *desc++;
2059         if (n >= 'a' && n <= 'z') {
2060             squares += n - 'a' + 1;
2061         } else if (n == '_') {
2062             /* do nothing */;
2063         } else if (n > '0' && n <= '9') {
2064             squares++;
2065             while (*desc >= '0' && *desc <= '9')
2066                 desc++;
2067         } else
2068             return "Invalid character in game description";
2069     }
2070
2071     if (squares < area)
2072         return "Not enough data to fill grid";
2073
2074     if (squares > area)
2075         return "Too much data to fit in grid";
2076
2077     return NULL;
2078 }
2079
2080 static game_state *new_game(midend *me, game_params *params, char *desc)
2081 {
2082     game_state *state = snew(game_state);
2083     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2084     int i;
2085
2086     state->c = params->c;
2087     state->r = params->r;
2088
2089     state->grid = snewn(area, digit);
2090     state->pencil = snewn(area * cr, unsigned char);
2091     memset(state->pencil, 0, area * cr);
2092     state->immutable = snewn(area, unsigned char);
2093     memset(state->immutable, FALSE, area);
2094
2095     state->completed = state->cheated = FALSE;
2096
2097     i = 0;
2098     while (*desc) {
2099         int n = *desc++;
2100         if (n >= 'a' && n <= 'z') {
2101             int run = n - 'a' + 1;
2102             assert(i + run <= area);
2103             while (run-- > 0)
2104                 state->grid[i++] = 0;
2105         } else if (n == '_') {
2106             /* do nothing */;
2107         } else if (n > '0' && n <= '9') {
2108             assert(i < area);
2109             state->immutable[i] = TRUE;
2110             state->grid[i++] = atoi(desc-1);
2111             while (*desc >= '0' && *desc <= '9')
2112                 desc++;
2113         } else {
2114             assert(!"We can't get here");
2115         }
2116     }
2117     assert(i == area);
2118
2119     return state;
2120 }
2121
2122 static game_state *dup_game(game_state *state)
2123 {
2124     game_state *ret = snew(game_state);
2125     int c = state->c, r = state->r, cr = c*r, area = cr * cr;
2126
2127     ret->c = state->c;
2128     ret->r = state->r;
2129
2130     ret->grid = snewn(area, digit);
2131     memcpy(ret->grid, state->grid, area);
2132
2133     ret->pencil = snewn(area * cr, unsigned char);
2134     memcpy(ret->pencil, state->pencil, area * cr);
2135
2136     ret->immutable = snewn(area, unsigned char);
2137     memcpy(ret->immutable, state->immutable, area);
2138
2139     ret->completed = state->completed;
2140     ret->cheated = state->cheated;
2141
2142     return ret;
2143 }
2144
2145 static void free_game(game_state *state)
2146 {
2147     sfree(state->immutable);
2148     sfree(state->pencil);
2149     sfree(state->grid);
2150     sfree(state);
2151 }
2152
2153 static char *solve_game(game_state *state, game_state *currstate,
2154                         char *ai, char **error)
2155 {
2156     int c = state->c, r = state->r, cr = c*r;
2157     char *ret;
2158     digit *grid;
2159     int solve_ret;
2160
2161     /*
2162      * If we already have the solution in ai, save ourselves some
2163      * time.
2164      */
2165     if (ai)
2166         return dupstr(ai);
2167
2168     grid = snewn(cr*cr, digit);
2169     memcpy(grid, state->grid, cr*cr);
2170     solve_ret = solver(c, r, grid, DIFF_RECURSIVE);
2171
2172     *error = NULL;
2173
2174     if (solve_ret == DIFF_IMPOSSIBLE)
2175         *error = "No solution exists for this puzzle";
2176     else if (solve_ret == DIFF_AMBIGUOUS)
2177         *error = "Multiple solutions exist for this puzzle";
2178
2179     if (*error) {
2180         sfree(grid);
2181         return NULL;
2182     }
2183
2184     ret = encode_solve_move(cr, grid);
2185
2186     sfree(grid);
2187
2188     return ret;
2189 }
2190
2191 static char *grid_text_format(int c, int r, digit *grid)
2192 {
2193     int cr = c*r;
2194     int x, y;
2195     int maxlen;
2196     char *ret, *p;
2197
2198     /*
2199      * There are cr lines of digits, plus r-1 lines of block
2200      * separators. Each line contains cr digits, cr-1 separating
2201      * spaces, and c-1 two-character block separators. Thus, the
2202      * total length of a line is 2*cr+2*c-3 (not counting the
2203      * newline), and there are cr+r-1 of them.
2204      */
2205     maxlen = (cr+r-1) * (2*cr+2*c-2);
2206     ret = snewn(maxlen+1, char);
2207     p = ret;
2208
2209     for (y = 0; y < cr; y++) {
2210         for (x = 0; x < cr; x++) {
2211             int ch = grid[y * cr + x];
2212             if (ch == 0)
2213                 ch = ' ';
2214             else if (ch <= 9)
2215                 ch = '0' + ch;
2216             else
2217                 ch = 'a' + ch-10;
2218             *p++ = ch;
2219             if (x+1 < cr) {
2220                 *p++ = ' ';
2221                 if ((x+1) % r == 0) {
2222                     *p++ = '|';
2223                     *p++ = ' ';
2224                 }
2225             }
2226         }
2227         *p++ = '\n';
2228         if (y+1 < cr && (y+1) % c == 0) {
2229             for (x = 0; x < cr; x++) {
2230                 *p++ = '-';
2231                 if (x+1 < cr) {
2232                     *p++ = '-';
2233                     if ((x+1) % r == 0) {
2234                         *p++ = '+';
2235                         *p++ = '-';
2236                     }
2237                 }
2238             }
2239             *p++ = '\n';
2240         }
2241     }
2242
2243     assert(p - ret == maxlen);
2244     *p = '\0';
2245     return ret;
2246 }
2247
2248 static char *game_text_format(game_state *state)
2249 {
2250     return grid_text_format(state->c, state->r, state->grid);
2251 }
2252
2253 struct game_ui {
2254     /*
2255      * These are the coordinates of the currently highlighted
2256      * square on the grid, or -1,-1 if there isn't one. When there
2257      * is, pressing a valid number or letter key or Space will
2258      * enter that number or letter in the grid.
2259      */
2260     int hx, hy;
2261     /*
2262      * This indicates whether the current highlight is a
2263      * pencil-mark one or a real one.
2264      */
2265     int hpencil;
2266 };
2267
2268 static game_ui *new_ui(game_state *state)
2269 {
2270     game_ui *ui = snew(game_ui);
2271
2272     ui->hx = ui->hy = -1;
2273     ui->hpencil = 0;
2274
2275     return ui;
2276 }
2277
2278 static void free_ui(game_ui *ui)
2279 {
2280     sfree(ui);
2281 }
2282
2283 static char *encode_ui(game_ui *ui)
2284 {
2285     return NULL;
2286 }
2287
2288 static void decode_ui(game_ui *ui, char *encoding)
2289 {
2290 }
2291
2292 static void game_changed_state(game_ui *ui, game_state *oldstate,
2293                                game_state *newstate)
2294 {
2295     int c = newstate->c, r = newstate->r, cr = c*r;
2296     /*
2297      * We prevent pencil-mode highlighting of a filled square. So
2298      * if the user has just filled in a square which we had a
2299      * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
2300      * then we cancel the highlight.
2301      */
2302     if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
2303         newstate->grid[ui->hy * cr + ui->hx] != 0) {
2304         ui->hx = ui->hy = -1;
2305     }
2306 }
2307
2308 struct game_drawstate {
2309     int started;
2310     int c, r, cr;
2311     int tilesize;
2312     digit *grid;
2313     unsigned char *pencil;
2314     unsigned char *hl;
2315     /* This is scratch space used within a single call to game_redraw. */
2316     int *entered_items;
2317 };
2318
2319 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2320                             int x, int y, int button)
2321 {
2322     int c = state->c, r = state->r, cr = c*r;
2323     int tx, ty;
2324     char buf[80];
2325
2326     button &= ~MOD_MASK;
2327
2328     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2329     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2330
2331     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
2332         if (button == LEFT_BUTTON) {
2333             if (state->immutable[ty*cr+tx]) {
2334                 ui->hx = ui->hy = -1;
2335             } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
2336                 ui->hx = ui->hy = -1;
2337             } else {
2338                 ui->hx = tx;
2339                 ui->hy = ty;
2340                 ui->hpencil = 0;
2341             }
2342             return "";                 /* UI activity occurred */
2343         }
2344         if (button == RIGHT_BUTTON) {
2345             /*
2346              * Pencil-mode highlighting for non filled squares.
2347              */
2348             if (state->grid[ty*cr+tx] == 0) {
2349                 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
2350                     ui->hx = ui->hy = -1;
2351                 } else {
2352                     ui->hpencil = 1;
2353                     ui->hx = tx;
2354                     ui->hy = ty;
2355                 }
2356             } else {
2357                 ui->hx = ui->hy = -1;
2358             }
2359             return "";                 /* UI activity occurred */
2360         }
2361     }
2362
2363     if (ui->hx != -1 && ui->hy != -1 &&
2364         ((button >= '1' && button <= '9' && button - '0' <= cr) ||
2365          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
2366          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
2367          button == ' ' || button == '\010' || button == '\177')) {
2368         int n = button - '0';
2369         if (button >= 'A' && button <= 'Z')
2370             n = button - 'A' + 10;
2371         if (button >= 'a' && button <= 'z')
2372             n = button - 'a' + 10;
2373         if (button == ' ' || button == '\010' || button == '\177')
2374             n = 0;
2375
2376         /*
2377          * Can't overwrite this square. In principle this shouldn't
2378          * happen anyway because we should never have even been
2379          * able to highlight the square, but it never hurts to be
2380          * careful.
2381          */
2382         if (state->immutable[ui->hy*cr+ui->hx])
2383             return NULL;
2384
2385         /*
2386          * Can't make pencil marks in a filled square. In principle
2387          * this shouldn't happen anyway because we should never
2388          * have even been able to pencil-highlight the square, but
2389          * it never hurts to be careful.
2390          */
2391         if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
2392             return NULL;
2393
2394         sprintf(buf, "%c%d,%d,%d",
2395                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
2396
2397         ui->hx = ui->hy = -1;
2398
2399         return dupstr(buf);
2400     }
2401
2402     return NULL;
2403 }
2404
2405 static game_state *execute_move(game_state *from, char *move)
2406 {
2407     int c = from->c, r = from->r, cr = c*r;
2408     game_state *ret;
2409     int x, y, n;
2410
2411     if (move[0] == 'S') {
2412         char *p;
2413
2414         ret = dup_game(from);
2415         ret->completed = ret->cheated = TRUE;
2416
2417         p = move+1;
2418         for (n = 0; n < cr*cr; n++) {
2419             ret->grid[n] = atoi(p);
2420
2421             if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
2422                 free_game(ret);
2423                 return NULL;
2424             }
2425
2426             while (*p && isdigit((unsigned char)*p)) p++;
2427             if (*p == ',') p++;
2428         }
2429
2430         return ret;
2431     } else if ((move[0] == 'P' || move[0] == 'R') &&
2432         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
2433         x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
2434
2435         ret = dup_game(from);
2436         if (move[0] == 'P' && n > 0) {
2437             int index = (y*cr+x) * cr + (n-1);
2438             ret->pencil[index] = !ret->pencil[index];
2439         } else {
2440             ret->grid[y*cr+x] = n;
2441             memset(ret->pencil + (y*cr+x)*cr, 0, cr);
2442
2443             /*
2444              * We've made a real change to the grid. Check to see
2445              * if the game has been completed.
2446              */
2447             if (!ret->completed && check_valid(c, r, ret->grid)) {
2448                 ret->completed = TRUE;
2449             }
2450         }
2451         return ret;
2452     } else
2453         return NULL;                   /* couldn't parse move string */
2454 }
2455
2456 /* ----------------------------------------------------------------------
2457  * Drawing routines.
2458  */
2459
2460 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
2461 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
2462
2463 static void game_compute_size(game_params *params, int tilesize,
2464                               int *x, int *y)
2465 {
2466     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2467     struct { int tilesize; } ads, *ds = &ads;
2468     ads.tilesize = tilesize;
2469
2470     *x = SIZE(params->c * params->r);
2471     *y = SIZE(params->c * params->r);
2472 }
2473
2474 static void game_set_size(drawing *dr, game_drawstate *ds,
2475                           game_params *params, int tilesize)
2476 {
2477     ds->tilesize = tilesize;
2478 }
2479
2480 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2481 {
2482     float *ret = snewn(3 * NCOLOURS, float);
2483
2484     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2485
2486     ret[COL_GRID * 3 + 0] = 0.0F;
2487     ret[COL_GRID * 3 + 1] = 0.0F;
2488     ret[COL_GRID * 3 + 2] = 0.0F;
2489
2490     ret[COL_CLUE * 3 + 0] = 0.0F;
2491     ret[COL_CLUE * 3 + 1] = 0.0F;
2492     ret[COL_CLUE * 3 + 2] = 0.0F;
2493
2494     ret[COL_USER * 3 + 0] = 0.0F;
2495     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
2496     ret[COL_USER * 3 + 2] = 0.0F;
2497
2498     ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
2499     ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
2500     ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
2501
2502     ret[COL_ERROR * 3 + 0] = 1.0F;
2503     ret[COL_ERROR * 3 + 1] = 0.0F;
2504     ret[COL_ERROR * 3 + 2] = 0.0F;
2505
2506     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2507     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2508     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
2509
2510     *ncolours = NCOLOURS;
2511     return ret;
2512 }
2513
2514 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2515 {
2516     struct game_drawstate *ds = snew(struct game_drawstate);
2517     int c = state->c, r = state->r, cr = c*r;
2518
2519     ds->started = FALSE;
2520     ds->c = c;
2521     ds->r = r;
2522     ds->cr = cr;
2523     ds->grid = snewn(cr*cr, digit);
2524     memset(ds->grid, 0, cr*cr);
2525     ds->pencil = snewn(cr*cr*cr, digit);
2526     memset(ds->pencil, 0, cr*cr*cr);
2527     ds->hl = snewn(cr*cr, unsigned char);
2528     memset(ds->hl, 0, cr*cr);
2529     ds->entered_items = snewn(cr*cr, int);
2530     ds->tilesize = 0;                  /* not decided yet */
2531     return ds;
2532 }
2533
2534 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2535 {
2536     sfree(ds->hl);
2537     sfree(ds->pencil);
2538     sfree(ds->grid);
2539     sfree(ds->entered_items);
2540     sfree(ds);
2541 }
2542
2543 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
2544                         int x, int y, int hl)
2545 {
2546     int c = state->c, r = state->r, cr = c*r;
2547     int tx, ty;
2548     int cx, cy, cw, ch;
2549     char str[2];
2550
2551     if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
2552         ds->hl[y*cr+x] == hl &&
2553         !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
2554         return;                        /* no change required */
2555
2556     tx = BORDER + x * TILE_SIZE + 2;
2557     ty = BORDER + y * TILE_SIZE + 2;
2558
2559     cx = tx;
2560     cy = ty;
2561     cw = TILE_SIZE-3;
2562     ch = TILE_SIZE-3;
2563
2564     if (x % r)
2565         cx--, cw++;
2566     if ((x+1) % r)
2567         cw++;
2568     if (y % c)
2569         cy--, ch++;
2570     if ((y+1) % c)
2571         ch++;
2572
2573     clip(dr, cx, cy, cw, ch);
2574
2575     /* background needs erasing */
2576     draw_rect(dr, cx, cy, cw, ch, (hl & 15) == 1 ? COL_HIGHLIGHT : COL_BACKGROUND);
2577
2578     /* pencil-mode highlight */
2579     if ((hl & 15) == 2) {
2580         int coords[6];
2581         coords[0] = cx;
2582         coords[1] = cy;
2583         coords[2] = cx+cw/2;
2584         coords[3] = cy;
2585         coords[4] = cx;
2586         coords[5] = cy+ch/2;
2587         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
2588     }
2589
2590     /* new number needs drawing? */
2591     if (state->grid[y*cr+x]) {
2592         str[1] = '\0';
2593         str[0] = state->grid[y*cr+x] + '0';
2594         if (str[0] > '9')
2595             str[0] += 'a' - ('9'+1);
2596         draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
2597                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
2598                   state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
2599     } else {
2600         int i, j, npencil;
2601         int pw, ph, pmax, fontsize;
2602
2603         /* count the pencil marks required */
2604         for (i = npencil = 0; i < cr; i++)
2605             if (state->pencil[(y*cr+x)*cr+i])
2606                 npencil++;
2607
2608         /*
2609          * It's not sensible to arrange pencil marks in the same
2610          * layout as the squares within a block, because this leads
2611          * to the font being too small. Instead, we arrange pencil
2612          * marks in the nearest thing we can to a square layout,
2613          * and we adjust the square layout depending on the number
2614          * of pencil marks in the square.
2615          */
2616         for (pw = 1; pw * pw < npencil; pw++);
2617         if (pw < 3) pw = 3;            /* otherwise it just looks _silly_ */
2618         ph = (npencil + pw - 1) / pw;
2619         if (ph < 2) ph = 2;            /* likewise */
2620         pmax = max(pw, ph);
2621         fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
2622
2623         for (i = j = 0; i < cr; i++)
2624             if (state->pencil[(y*cr+x)*cr+i]) {
2625                 int dx = j % pw, dy = j / pw;
2626
2627                 str[1] = '\0';
2628                 str[0] = i + '1';
2629                 if (str[0] > '9')
2630                     str[0] += 'a' - ('9'+1);
2631                 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
2632                           ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
2633                           FONT_VARIABLE, fontsize,
2634                           ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
2635                 j++;
2636             }
2637     }
2638
2639     unclip(dr);
2640
2641     draw_update(dr, cx, cy, cw, ch);
2642
2643     ds->grid[y*cr+x] = state->grid[y*cr+x];
2644     memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
2645     ds->hl[y*cr+x] = hl;
2646 }
2647
2648 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2649                         game_state *state, int dir, game_ui *ui,
2650                         float animtime, float flashtime)
2651 {
2652     int c = state->c, r = state->r, cr = c*r;
2653     int x, y;
2654
2655     if (!ds->started) {
2656         /*
2657          * The initial contents of the window are not guaranteed
2658          * and can vary with front ends. To be on the safe side,
2659          * all games should start by drawing a big
2660          * background-colour rectangle covering the whole window.
2661          */
2662         draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
2663
2664         /*
2665          * Draw the grid.
2666          */
2667         for (x = 0; x <= cr; x++) {
2668             int thick = (x % r ? 0 : 1);
2669             draw_rect(dr, BORDER + x*TILE_SIZE - thick, BORDER-1,
2670                       1+2*thick, cr*TILE_SIZE+3, COL_GRID);
2671         }
2672         for (y = 0; y <= cr; y++) {
2673             int thick = (y % c ? 0 : 1);
2674             draw_rect(dr, BORDER-1, BORDER + y*TILE_SIZE - thick,
2675                       cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
2676         }
2677     }
2678
2679     /*
2680      * This array is used to keep track of rows, columns and boxes
2681      * which contain a number more than once.
2682      */
2683     for (x = 0; x < cr * cr; x++)
2684         ds->entered_items[x] = 0;
2685     for (x = 0; x < cr; x++)
2686         for (y = 0; y < cr; y++) {
2687             digit d = state->grid[y*cr+x];
2688             if (d) {
2689                 int box = (x/r)+(y/c)*c;
2690                 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
2691                 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
2692                 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
2693             }
2694         }
2695
2696     /*
2697      * Draw any numbers which need redrawing.
2698      */
2699     for (x = 0; x < cr; x++) {
2700         for (y = 0; y < cr; y++) {
2701             int highlight = 0;
2702             digit d = state->grid[y*cr+x];
2703
2704             if (flashtime > 0 &&
2705                 (flashtime <= FLASH_TIME/3 ||
2706                  flashtime >= FLASH_TIME*2/3))
2707                 highlight = 1;
2708
2709             /* Highlight active input areas. */
2710             if (x == ui->hx && y == ui->hy)
2711                 highlight = ui->hpencil ? 2 : 1;
2712
2713             /* Mark obvious errors (ie, numbers which occur more than once
2714              * in a single row, column, or box). */
2715             if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
2716                       (ds->entered_items[y*cr+d-1] & 8) ||
2717                       (ds->entered_items[((x/r)+(y/c)*c)*cr+d-1] & 32)))
2718                 highlight |= 16;
2719
2720             draw_number(dr, ds, state, x, y, highlight);
2721         }
2722     }
2723
2724     /*
2725      * Update the _entire_ grid if necessary.
2726      */
2727     if (!ds->started) {
2728         draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
2729         ds->started = TRUE;
2730     }
2731 }
2732
2733 static float game_anim_length(game_state *oldstate, game_state *newstate,
2734                               int dir, game_ui *ui)
2735 {
2736     return 0.0F;
2737 }
2738
2739 static float game_flash_length(game_state *oldstate, game_state *newstate,
2740                                int dir, game_ui *ui)
2741 {
2742     if (!oldstate->completed && newstate->completed &&
2743         !oldstate->cheated && !newstate->cheated)
2744         return FLASH_TIME;
2745     return 0.0F;
2746 }
2747
2748 static int game_wants_statusbar(void)
2749 {
2750     return FALSE;
2751 }
2752
2753 static int game_timing_state(game_state *state, game_ui *ui)
2754 {
2755     return TRUE;
2756 }
2757
2758 static void game_print_size(game_params *params, float *x, float *y)
2759 {
2760     int pw, ph;
2761
2762     /*
2763      * I'll use 9mm squares by default. They should be quite big
2764      * for this game, because players will want to jot down no end
2765      * of pencil marks in the squares.
2766      */
2767     game_compute_size(params, 900, &pw, &ph);
2768     *x = pw / 100.0;
2769     *y = ph / 100.0;
2770 }
2771
2772 static void game_print(drawing *dr, game_state *state, int tilesize)
2773 {
2774     int c = state->c, r = state->r, cr = c*r;
2775     int ink = print_mono_colour(dr, 0);
2776     int x, y;
2777
2778     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2779     game_drawstate ads, *ds = &ads;
2780     ads.tilesize = tilesize;
2781
2782     /*
2783      * Border.
2784      */
2785     print_line_width(dr, 3 * TILE_SIZE / 40);
2786     draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
2787
2788     /*
2789      * Grid.
2790      */
2791     for (x = 1; x < cr; x++) {
2792         print_line_width(dr, (x % r ? 1 : 3) * TILE_SIZE / 40);
2793         draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
2794                   BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
2795     }
2796     for (y = 1; y < cr; y++) {
2797         print_line_width(dr, (y % c ? 1 : 3) * TILE_SIZE / 40);
2798         draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
2799                   BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
2800     }
2801
2802     /*
2803      * Numbers.
2804      */
2805     for (y = 0; y < cr; y++)
2806         for (x = 0; x < cr; x++)
2807             if (state->grid[y*cr+x]) {
2808                 char str[2];
2809                 str[1] = '\0';
2810                 str[0] = state->grid[y*cr+x] + '0';
2811                 if (str[0] > '9')
2812                     str[0] += 'a' - ('9'+1);
2813                 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
2814                           BORDER + y*TILE_SIZE + TILE_SIZE/2,
2815                           FONT_VARIABLE, TILE_SIZE/2,
2816                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2817             }
2818 }
2819
2820 #ifdef COMBINED
2821 #define thegame solo
2822 #endif
2823
2824 const struct game thegame = {
2825     "Solo", "games.solo",
2826     default_params,
2827     game_fetch_preset,
2828     decode_params,
2829     encode_params,
2830     free_params,
2831     dup_params,
2832     TRUE, game_configure, custom_params,
2833     validate_params,
2834     new_game_desc,
2835     validate_desc,
2836     new_game,
2837     dup_game,
2838     free_game,
2839     TRUE, solve_game,
2840     TRUE, game_text_format,
2841     new_ui,
2842     free_ui,
2843     encode_ui,
2844     decode_ui,
2845     game_changed_state,
2846     interpret_move,
2847     execute_move,
2848     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2849     game_colours,
2850     game_new_drawstate,
2851     game_free_drawstate,
2852     game_redraw,
2853     game_anim_length,
2854     game_flash_length,
2855     TRUE, FALSE, game_print_size, game_print,
2856     game_wants_statusbar,
2857     FALSE, game_timing_state,
2858     0,                                 /* mouse_priorities */
2859 };
2860
2861 #ifdef STANDALONE_SOLVER
2862
2863 /*
2864  * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2865  */
2866
2867 void frontend_default_colour(frontend *fe, float *output) {}
2868 void draw_text(drawing *dr, int x, int y, int fonttype, int fontsize,
2869                int align, int colour, char *text) {}
2870 void draw_rect(drawing *dr, int x, int y, int w, int h, int colour) {}
2871 void draw_rect_outline(drawing *dr, int x, int y, int w, int h, int colour) {}
2872 void draw_line(drawing *dr, int x1, int y1, int x2, int y2, int colour) {}
2873 void draw_polygon(drawing *dr, int *coords, int npoints,
2874                   int fillcolour, int outlinecolour) {}
2875 void clip(drawing *dr, int x, int y, int w, int h) {}
2876 void unclip(drawing *dr) {}
2877 void start_draw(drawing *dr) {}
2878 void draw_update(drawing *dr, int x, int y, int w, int h) {}
2879 void end_draw(drawing *dr) {}
2880 int print_mono_colour(drawing *dr, int grey) { return 0; }
2881 void print_line_width(drawing *dr, int width) {}
2882 unsigned long random_bits(random_state *state, int bits)
2883 { assert(!"Shouldn't get randomness"); return 0; }
2884 unsigned long random_upto(random_state *state, unsigned long limit)
2885 { assert(!"Shouldn't get randomness"); return 0; }
2886 void shuffle(void *array, int nelts, int eltsize, random_state *rs)
2887 { assert(!"Shouldn't get randomness"); }
2888
2889 void fatal(char *fmt, ...)
2890 {
2891     va_list ap;
2892
2893     fprintf(stderr, "fatal error: ");
2894
2895     va_start(ap, fmt);
2896     vfprintf(stderr, fmt, ap);
2897     va_end(ap);
2898
2899     fprintf(stderr, "\n");
2900     exit(1);
2901 }
2902
2903 int main(int argc, char **argv)
2904 {
2905     game_params *p;
2906     game_state *s;
2907     char *id = NULL, *desc, *err;
2908     int grade = FALSE;
2909     int ret;
2910
2911     while (--argc > 0) {
2912         char *p = *++argv;
2913         if (!strcmp(p, "-v")) {
2914             solver_show_working = TRUE;
2915         } else if (!strcmp(p, "-g")) {
2916             grade = TRUE;
2917         } else if (*p == '-') {
2918             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2919             return 1;
2920         } else {
2921             id = p;
2922         }
2923     }
2924
2925     if (!id) {
2926         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2927         return 1;
2928     }
2929
2930     desc = strchr(id, ':');
2931     if (!desc) {
2932         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2933         return 1;
2934     }
2935     *desc++ = '\0';
2936
2937     p = default_params();
2938     decode_params(p, id);
2939     err = validate_desc(p, desc);
2940     if (err) {
2941         fprintf(stderr, "%s: %s\n", argv[0], err);
2942         return 1;
2943     }
2944     s = new_game(NULL, p, desc);
2945
2946     ret = solver(p->c, p->r, s->grid, DIFF_RECURSIVE);
2947     if (grade) {
2948         printf("Difficulty rating: %s\n",
2949                ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
2950                ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
2951                ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
2952                ret==DIFF_SET ? "Advanced (set elimination required)":
2953                ret==DIFF_NEIGHBOUR ? "Extreme (mutual neighbour elimination required)":
2954                ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
2955                ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
2956                ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
2957                "INTERNAL ERROR: unrecognised difficulty code");
2958     } else {
2959         printf("%s\n", grid_text_format(p->c, p->r, s->grid));
2960     }
2961
2962     return 0;
2963 }
2964
2965 #endif