chiark / gitweb /
Tents: mark squares as non-tents with {Shift,Control}-cursor keys.
[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 48
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113 #define GRIDEXTRA max((TILE_SIZE / 32),1)
114
115 #define FLASH_TIME 0.4F
116
117 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
118        SYMM_REF4D, SYMM_REF8 };
119
120 enum { DIFF_BLOCK,
121        DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME, DIFF_RECURSIVE,
122        DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
123
124 enum { DIFF_KSINGLE, DIFF_KMINMAX, DIFF_KSUMS, DIFF_KINTERSECT };
125
126 enum {
127     COL_BACKGROUND,
128     COL_XDIAGONALS,
129     COL_GRID,
130     COL_CLUE,
131     COL_USER,
132     COL_HIGHLIGHT,
133     COL_ERROR,
134     COL_PENCIL,
135     COL_KILLER,
136     NCOLOURS
137 };
138
139 /*
140  * To determine all possible ways to reach a given sum by adding two or
141  * three numbers from 1..9, each of which occurs exactly once in the sum,
142  * these arrays contain a list of bitmasks for each sum value, where if
143  * bit N is set, it means that N occurs in the sum.  Each list is
144  * terminated by a zero if it is shorter than the size of the array.
145  */
146 #define MAX_2SUMS 5
147 #define MAX_3SUMS 8
148 #define MAX_4SUMS 12
149 unsigned long sum_bits2[18][MAX_2SUMS];
150 unsigned long sum_bits3[25][MAX_3SUMS];
151 unsigned long sum_bits4[31][MAX_4SUMS];
152
153 static int find_sum_bits(unsigned long *array, int idx, int value_left,
154                          int addends_left, int min_addend,
155                          unsigned long bitmask_so_far)
156 {
157     int i;
158     assert(addends_left >= 2);
159
160     for (i = min_addend; i < value_left; i++) {
161         unsigned long new_bitmask = bitmask_so_far | (1L << i);
162         assert(bitmask_so_far != new_bitmask);
163
164         if (addends_left == 2) {
165             int j = value_left - i;
166             if (j <= i)
167                 break;
168             if (j > 9)
169                 continue;
170             array[idx++] = new_bitmask | (1L << j);
171         } else
172             idx = find_sum_bits(array, idx, value_left - i,
173                                 addends_left - 1, i + 1,
174                                 new_bitmask);
175     }
176     return idx;
177 }
178
179 static void precompute_sum_bits(void)
180 {
181     int i;
182     for (i = 3; i < 31; i++) {
183         int j;
184         if (i < 18) {
185             j = find_sum_bits(sum_bits2[i], 0, i, 2, 1, 0);
186             assert (j <= MAX_2SUMS);
187             if (j < MAX_2SUMS)
188                 sum_bits2[i][j] = 0;
189         }
190         if (i < 25) {
191             j = find_sum_bits(sum_bits3[i], 0, i, 3, 1, 0);
192             assert (j <= MAX_3SUMS);
193             if (j < MAX_3SUMS)
194                 sum_bits3[i][j] = 0;
195         }
196         j = find_sum_bits(sum_bits4[i], 0, i, 4, 1, 0);
197         assert (j <= MAX_4SUMS);
198         if (j < MAX_4SUMS)
199             sum_bits4[i][j] = 0;
200     }
201 }
202
203 struct game_params {
204     /*
205      * For a square puzzle, `c' and `r' indicate the puzzle
206      * parameters as described above.
207      * 
208      * A jigsaw-style puzzle is indicated by r==1, in which case c
209      * can be whatever it likes (there is no constraint on
210      * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
211      */
212     int c, r, symm, diff, kdiff;
213     int xtype;                         /* require all digits in X-diagonals */
214     int killer;
215 };
216
217 struct block_structure {
218     int refcount;
219
220     /*
221      * For text formatting, we do need c and r here.
222      */
223     int c, r, area;
224
225     /*
226      * For any square index, whichblock[i] gives its block index.
227      *
228      * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
229      * square in block b.  nr_squares[b] gives the number of squares
230      * in block b (also the number of valid elements in blocks[b]).
231      *
232      * blocks_data holds the data pointed to by blocks.
233      *
234      * nr_squares may be NULL for block structures where all blocks are
235      * the same size.
236      */
237     int *whichblock, **blocks, *nr_squares, *blocks_data;
238     int nr_blocks, max_nr_squares;
239
240 #ifdef STANDALONE_SOLVER
241     /*
242      * Textual descriptions of each block. For normal Sudoku these
243      * are of the form "(1,3)"; for jigsaw they are "starting at
244      * (5,7)". So the sensible usage in both cases is to say
245      * "elimination within block %s" with one of these strings.
246      * 
247      * Only blocknames itself needs individually freeing; it's all
248      * one block.
249      */
250     char **blocknames;
251 #endif
252 };
253
254 struct game_state {
255     /*
256      * For historical reasons, I use `cr' to denote the overall
257      * width/height of the puzzle. It was a natural notation when
258      * all puzzles were divided into blocks in a grid, but doesn't
259      * really make much sense given jigsaw puzzles. However, the
260      * obvious `n' is heavily used in the solver to describe the
261      * index of a number being placed, so `cr' will have to stay.
262      */
263     int cr;
264     struct block_structure *blocks;
265     struct block_structure *kblocks;   /* Blocks for killer puzzles.  */
266     int xtype, killer;
267     digit *grid, *kgrid;
268     unsigned char *pencil;             /* c*r*c*r elements */
269     unsigned char *immutable;          /* marks which digits are clues */
270     int completed, cheated;
271 };
272
273 static game_params *default_params(void)
274 {
275     game_params *ret = snew(game_params);
276
277     ret->c = ret->r = 3;
278     ret->xtype = FALSE;
279     ret->killer = FALSE;
280     ret->symm = SYMM_ROT2;             /* a plausible default */
281     ret->diff = DIFF_BLOCK;            /* so is this */
282     ret->kdiff = DIFF_KINTERSECT;      /* so is this */
283
284     return ret;
285 }
286
287 static void free_params(game_params *params)
288 {
289     sfree(params);
290 }
291
292 static game_params *dup_params(const game_params *params)
293 {
294     game_params *ret = snew(game_params);
295     *ret = *params;                    /* structure copy */
296     return ret;
297 }
298
299 static int game_fetch_preset(int i, char **name, game_params **params)
300 {
301     static struct {
302         char *title;
303         game_params params;
304     } presets[] = {
305         { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
306         { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
307         { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
308         { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
309         { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
310         { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, DIFF_KMINMAX, FALSE, FALSE } },
311         { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
312         { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, TRUE } },
313         { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, DIFF_KMINMAX, FALSE, FALSE } },
314         { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, DIFF_KMINMAX, FALSE, FALSE } },
315         { "3x3 Killer", { 3, 3, SYMM_NONE, DIFF_BLOCK, DIFF_KINTERSECT, FALSE, TRUE } },
316         { "9 Jigsaw Basic", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
317         { "9 Jigsaw Basic X", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
318         { "9 Jigsaw Advanced", { 9, 1, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
319 #ifndef SLOW_SYSTEM
320         { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
321         { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
322 #endif
323     };
324
325     if (i < 0 || i >= lenof(presets))
326         return FALSE;
327
328     *name = dupstr(presets[i].title);
329     *params = dup_params(&presets[i].params);
330
331     return TRUE;
332 }
333
334 static void decode_params(game_params *ret, char const *string)
335 {
336     int seen_r = FALSE;
337
338     ret->c = ret->r = atoi(string);
339     ret->xtype = FALSE;
340     ret->killer = FALSE;
341     while (*string && isdigit((unsigned char)*string)) string++;
342     if (*string == 'x') {
343         string++;
344         ret->r = atoi(string);
345         seen_r = TRUE;
346         while (*string && isdigit((unsigned char)*string)) string++;
347     }
348     while (*string) {
349         if (*string == 'j') {
350             string++;
351             if (seen_r)
352                 ret->c *= ret->r;
353             ret->r = 1;
354         } else if (*string == 'x') {
355             string++;
356             ret->xtype = TRUE;
357         } else if (*string == 'k') {
358             string++;
359             ret->killer = TRUE;
360         } else if (*string == 'r' || *string == 'm' || *string == 'a') {
361             int sn, sc, sd;
362             sc = *string++;
363             if (sc == 'm' && *string == 'd') {
364                 sd = TRUE;
365                 string++;
366             } else {
367                 sd = FALSE;
368             }
369             sn = atoi(string);
370             while (*string && isdigit((unsigned char)*string)) string++;
371             if (sc == 'm' && sn == 8)
372                 ret->symm = SYMM_REF8;
373             if (sc == 'm' && sn == 4)
374                 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
375             if (sc == 'm' && sn == 2)
376                 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
377             if (sc == 'r' && sn == 4)
378                 ret->symm = SYMM_ROT4;
379             if (sc == 'r' && sn == 2)
380                 ret->symm = SYMM_ROT2;
381             if (sc == 'a')
382                 ret->symm = SYMM_NONE;
383         } else if (*string == 'd') {
384             string++;
385             if (*string == 't')        /* trivial */
386                 string++, ret->diff = DIFF_BLOCK;
387             else if (*string == 'b')   /* basic */
388                 string++, ret->diff = DIFF_SIMPLE;
389             else if (*string == 'i')   /* intermediate */
390                 string++, ret->diff = DIFF_INTERSECT;
391             else if (*string == 'a')   /* advanced */
392                 string++, ret->diff = DIFF_SET;
393             else if (*string == 'e')   /* extreme */
394                 string++, ret->diff = DIFF_EXTREME;
395             else if (*string == 'u')   /* unreasonable */
396                 string++, ret->diff = DIFF_RECURSIVE;
397         } else
398             string++;                  /* eat unknown character */
399     }
400 }
401
402 static char *encode_params(const game_params *params, int full)
403 {
404     char str[80];
405
406     if (params->r > 1)
407         sprintf(str, "%dx%d", params->c, params->r);
408     else
409         sprintf(str, "%dj", params->c);
410     if (params->xtype)
411         strcat(str, "x");
412     if (params->killer)
413         strcat(str, "k");
414
415     if (full) {
416         switch (params->symm) {
417           case SYMM_REF8: strcat(str, "m8"); break;
418           case SYMM_REF4: strcat(str, "m4"); break;
419           case SYMM_REF4D: strcat(str, "md4"); break;
420           case SYMM_REF2: strcat(str, "m2"); break;
421           case SYMM_REF2D: strcat(str, "md2"); break;
422           case SYMM_ROT4: strcat(str, "r4"); break;
423           /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
424           case SYMM_NONE: strcat(str, "a"); break;
425         }
426         switch (params->diff) {
427           /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
428           case DIFF_SIMPLE: strcat(str, "db"); break;
429           case DIFF_INTERSECT: strcat(str, "di"); break;
430           case DIFF_SET: strcat(str, "da"); break;
431           case DIFF_EXTREME: strcat(str, "de"); break;
432           case DIFF_RECURSIVE: strcat(str, "du"); break;
433         }
434     }
435     return dupstr(str);
436 }
437
438 static config_item *game_configure(const game_params *params)
439 {
440     config_item *ret;
441     char buf[80];
442
443     ret = snewn(8, config_item);
444
445     ret[0].name = "Columns of sub-blocks";
446     ret[0].type = C_STRING;
447     sprintf(buf, "%d", params->c);
448     ret[0].sval = dupstr(buf);
449     ret[0].ival = 0;
450
451     ret[1].name = "Rows of sub-blocks";
452     ret[1].type = C_STRING;
453     sprintf(buf, "%d", params->r);
454     ret[1].sval = dupstr(buf);
455     ret[1].ival = 0;
456
457     ret[2].name = "\"X\" (require every number in each main diagonal)";
458     ret[2].type = C_BOOLEAN;
459     ret[2].sval = NULL;
460     ret[2].ival = params->xtype;
461
462     ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
463     ret[3].type = C_BOOLEAN;
464     ret[3].sval = NULL;
465     ret[3].ival = (params->r == 1);
466
467     ret[4].name = "Killer (digit sums)";
468     ret[4].type = C_BOOLEAN;
469     ret[4].sval = NULL;
470     ret[4].ival = params->killer;
471
472     ret[5].name = "Symmetry";
473     ret[5].type = C_CHOICES;
474     ret[5].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
475         "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
476         "8-way mirror";
477     ret[5].ival = params->symm;
478
479     ret[6].name = "Difficulty";
480     ret[6].type = C_CHOICES;
481     ret[6].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
482     ret[6].ival = params->diff;
483
484     ret[7].name = NULL;
485     ret[7].type = C_END;
486     ret[7].sval = NULL;
487     ret[7].ival = 0;
488
489     return ret;
490 }
491
492 static game_params *custom_params(const config_item *cfg)
493 {
494     game_params *ret = snew(game_params);
495
496     ret->c = atoi(cfg[0].sval);
497     ret->r = atoi(cfg[1].sval);
498     ret->xtype = cfg[2].ival;
499     if (cfg[3].ival) {
500         ret->c *= ret->r;
501         ret->r = 1;
502     }
503     ret->killer = cfg[4].ival;
504     ret->symm = cfg[5].ival;
505     ret->diff = cfg[6].ival;
506     ret->kdiff = DIFF_KINTERSECT;
507
508     return ret;
509 }
510
511 static char *validate_params(const game_params *params, int full)
512 {
513     if (params->c < 2)
514         return "Both dimensions must be at least 2";
515     if (params->c > ORDER_MAX || params->r > ORDER_MAX)
516         return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
517     if ((params->c * params->r) > 31)
518         return "Unable to support more than 31 distinct symbols in a puzzle";
519     if (params->killer && params->c * params->r > 9)
520         return "Killer puzzle dimensions must be smaller than 10.";
521     return NULL;
522 }
523
524 /*
525  * ----------------------------------------------------------------------
526  * Block structure functions.
527  */
528
529 static struct block_structure *alloc_block_structure(int c, int r, int area,
530                                                      int max_nr_squares,
531                                                      int nr_blocks)
532 {
533     int i;
534     struct block_structure *b = snew(struct block_structure);
535
536     b->refcount = 1;
537     b->nr_blocks = nr_blocks;
538     b->max_nr_squares = max_nr_squares;
539     b->c = c; b->r = r; b->area = area;
540     b->whichblock = snewn(area, int);
541     b->blocks_data = snewn(nr_blocks * max_nr_squares, int);
542     b->blocks = snewn(nr_blocks, int *);
543     b->nr_squares = snewn(nr_blocks, int);
544
545     for (i = 0; i < nr_blocks; i++)
546         b->blocks[i] = b->blocks_data + i*max_nr_squares;
547
548 #ifdef STANDALONE_SOLVER
549     b->blocknames = (char **)smalloc(c*r*(sizeof(char *)+80));
550     for (i = 0; i < c * r; i++)
551         b->blocknames[i] = NULL;
552 #endif
553     return b;
554 }
555
556 static void free_block_structure(struct block_structure *b)
557 {
558     if (--b->refcount == 0) {
559         sfree(b->whichblock);
560         sfree(b->blocks);
561         sfree(b->blocks_data);
562 #ifdef STANDALONE_SOLVER
563         sfree(b->blocknames);
564 #endif
565         sfree(b->nr_squares);
566         sfree(b);
567     }
568 }
569
570 static struct block_structure *dup_block_structure(struct block_structure *b)
571 {
572     struct block_structure *nb;
573     int i;
574
575     nb = alloc_block_structure(b->c, b->r, b->area, b->max_nr_squares,
576                                b->nr_blocks);
577     memcpy(nb->nr_squares, b->nr_squares, b->nr_blocks * sizeof *b->nr_squares);
578     memcpy(nb->whichblock, b->whichblock, b->area * sizeof *b->whichblock);
579     memcpy(nb->blocks_data, b->blocks_data,
580            b->nr_blocks * b->max_nr_squares * sizeof *b->blocks_data);
581     for (i = 0; i < b->nr_blocks; i++)
582         nb->blocks[i] = nb->blocks_data + i*nb->max_nr_squares;
583
584 #ifdef STANDALONE_SOLVER
585     memcpy(nb->blocknames, b->blocknames, b->c * b->r *(sizeof(char *)+80));
586     {
587         int i;
588         for (i = 0; i < b->c * b->r; i++)
589             if (b->blocknames[i] == NULL)
590                 nb->blocknames[i] = NULL;
591             else
592                 nb->blocknames[i] = ((char *)nb->blocknames) + (b->blocknames[i] - (char *)b->blocknames);
593     }
594 #endif
595     return nb;
596 }
597
598 static void split_block(struct block_structure *b, int *squares, int nr_squares)
599 {
600     int i, j;
601     int previous_block = b->whichblock[squares[0]];
602     int newblock = b->nr_blocks;
603
604     assert(b->max_nr_squares >= nr_squares);
605     assert(b->nr_squares[previous_block] > nr_squares);
606
607     b->nr_blocks++;
608     b->blocks_data = sresize(b->blocks_data,
609                              b->nr_blocks * b->max_nr_squares, int);
610     b->nr_squares = sresize(b->nr_squares, b->nr_blocks, int);
611     sfree(b->blocks);
612     b->blocks = snewn(b->nr_blocks, int *);
613     for (i = 0; i < b->nr_blocks; i++)
614         b->blocks[i] = b->blocks_data + i*b->max_nr_squares;
615     for (i = 0; i < nr_squares; i++) {
616         assert(b->whichblock[squares[i]] == previous_block);
617         b->whichblock[squares[i]] = newblock;
618         b->blocks[newblock][i] = squares[i];
619     }
620     for (i = j = 0; i < b->nr_squares[previous_block]; i++) {
621         int k;
622         int sq = b->blocks[previous_block][i];
623         for (k = 0; k < nr_squares; k++)
624             if (squares[k] == sq)
625                 break;
626         if (k == nr_squares)
627             b->blocks[previous_block][j++] = sq;
628     }
629     b->nr_squares[previous_block] -= nr_squares;
630     b->nr_squares[newblock] = nr_squares;
631 }
632
633 static void remove_from_block(struct block_structure *blocks, int b, int n)
634 {
635     int i, j;
636     blocks->whichblock[n] = -1;
637     for (i = j = 0; i < blocks->nr_squares[b]; i++)
638         if (blocks->blocks[b][i] != n)
639             blocks->blocks[b][j++] = blocks->blocks[b][i];
640     assert(j+1 == i);
641     blocks->nr_squares[b]--;
642 }
643
644 /* ----------------------------------------------------------------------
645  * Solver.
646  * 
647  * This solver is used for two purposes:
648  *  + to check solubility of a grid as we gradually remove numbers
649  *    from it
650  *  + to solve an externally generated puzzle when the user selects
651  *    `Solve'.
652  * 
653  * It supports a variety of specific modes of reasoning. By
654  * enabling or disabling subsets of these modes we can arrange a
655  * range of difficulty levels.
656  */
657
658 /*
659  * Modes of reasoning currently supported:
660  *
661  *  - Positional elimination: a number must go in a particular
662  *    square because all the other empty squares in a given
663  *    row/col/blk are ruled out.
664  *
665  *  - Killer minmax elimination: for killer-type puzzles, a number
666  *    is impossible if choosing it would cause the sum in a killer
667  *    region to be guaranteed to be too large or too small.
668  *
669  *  - Numeric elimination: a square must have a particular number
670  *    in because all the other numbers that could go in it are
671  *    ruled out.
672  *
673  *  - Intersectional analysis: given two domains which overlap
674  *    (hence one must be a block, and the other can be a row or
675  *    col), if the possible locations for a particular number in
676  *    one of the domains can be narrowed down to the overlap, then
677  *    that number can be ruled out everywhere but the overlap in
678  *    the other domain too.
679  *
680  *  - Set elimination: if there is a subset of the empty squares
681  *    within a domain such that the union of the possible numbers
682  *    in that subset has the same size as the subset itself, then
683  *    those numbers can be ruled out everywhere else in the domain.
684  *    (For example, if there are five empty squares and the
685  *    possible numbers in each are 12, 23, 13, 134 and 1345, then
686  *    the first three empty squares form such a subset: the numbers
687  *    1, 2 and 3 _must_ be in those three squares in some
688  *    permutation, and hence we can deduce none of them can be in
689  *    the fourth or fifth squares.)
690  *     + You can also see this the other way round, concentrating
691  *       on numbers rather than squares: if there is a subset of
692  *       the unplaced numbers within a domain such that the union
693  *       of all their possible positions has the same size as the
694  *       subset itself, then all other numbers can be ruled out for
695  *       those positions. However, it turns out that this is
696  *       exactly equivalent to the first formulation at all times:
697  *       there is a 1-1 correspondence between suitable subsets of
698  *       the unplaced numbers and suitable subsets of the unfilled
699  *       places, found by taking the _complement_ of the union of
700  *       the numbers' possible positions (or the spaces' possible
701  *       contents).
702  * 
703  *  - Forcing chains (see comment for solver_forcing().)
704  * 
705  *  - Recursion. If all else fails, we pick one of the currently
706  *    most constrained empty squares and take a random guess at its
707  *    contents, then continue solving on that basis and see if we
708  *    get any further.
709  */
710
711 struct solver_usage {
712     int cr;
713     struct block_structure *blocks, *kblocks, *extra_cages;
714     /*
715      * We set up a cubic array, indexed by x, y and digit; each
716      * element of this array is TRUE or FALSE according to whether
717      * or not that digit _could_ in principle go in that position.
718      *
719      * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
720      * are macros below to help with this.
721      */
722     unsigned char *cube;
723     /*
724      * This is the grid in which we write down our final
725      * deductions. y-coordinates in here are _not_ transformed.
726      */
727     digit *grid;
728     /*
729      * For killer-type puzzles, kclues holds the secondary clue for
730      * each cage.  For derived cages, the clue is in extra_clues.
731      */
732     digit *kclues, *extra_clues;
733     /*
734      * Now we keep track, at a slightly higher level, of what we
735      * have yet to work out, to prevent doing the same deduction
736      * many times.
737      */
738     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
739     unsigned char *row;
740     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
741     unsigned char *col;
742     /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
743     unsigned char *blk;
744     /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
745     unsigned char *diag;               /* diag 0 is \, 1 is / */
746
747     int *regions;
748     int nr_regions;
749     int **sq2region;
750 };
751 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
752 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
753 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
754 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
755
756 #define ondiag0(xy) ((xy) % (cr+1) == 0)
757 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
758 #define diag0(i) ((i) * (cr+1))
759 #define diag1(i) ((i+1) * (cr-1))
760
761 /*
762  * Function called when we are certain that a particular square has
763  * a particular number in it. The y-coordinate passed in here is
764  * transformed.
765  */
766 static void solver_place(struct solver_usage *usage, int x, int y, int n)
767 {
768     int cr = usage->cr;
769     int sqindex = y*cr+x;
770     int i, bi;
771
772     assert(cube(x,y,n));
773
774     /*
775      * Rule out all other numbers in this square.
776      */
777     for (i = 1; i <= cr; i++)
778         if (i != n)
779             cube(x,y,i) = FALSE;
780
781     /*
782      * Rule out this number in all other positions in the row.
783      */
784     for (i = 0; i < cr; i++)
785         if (i != y)
786             cube(x,i,n) = FALSE;
787
788     /*
789      * Rule out this number in all other positions in the column.
790      */
791     for (i = 0; i < cr; i++)
792         if (i != x)
793             cube(i,y,n) = FALSE;
794
795     /*
796      * Rule out this number in all other positions in the block.
797      */
798     bi = usage->blocks->whichblock[sqindex];
799     for (i = 0; i < cr; i++) {
800         int bp = usage->blocks->blocks[bi][i];
801         if (bp != sqindex)
802             cube2(bp,n) = FALSE;
803     }
804
805     /*
806      * Enter the number in the result grid.
807      */
808     usage->grid[sqindex] = n;
809
810     /*
811      * Cross out this number from the list of numbers left to place
812      * in its row, its column and its block.
813      */
814     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
815         usage->blk[bi*cr+n-1] = TRUE;
816
817     if (usage->diag) {
818         if (ondiag0(sqindex)) {
819             for (i = 0; i < cr; i++)
820                 if (diag0(i) != sqindex)
821                     cube2(diag0(i),n) = FALSE;
822             usage->diag[n-1] = TRUE;
823         }
824         if (ondiag1(sqindex)) {
825             for (i = 0; i < cr; i++)
826                 if (diag1(i) != sqindex)
827                     cube2(diag1(i),n) = FALSE;
828             usage->diag[cr+n-1] = TRUE;
829         }
830     }
831 }
832
833 #if defined STANDALONE_SOLVER && defined __GNUC__
834 /*
835  * Forward-declare the functions taking printf-like format arguments
836  * with __attribute__((format)) so as to ensure the argument syntax
837  * gets debugged.
838  */
839 struct solver_scratch;
840 static int solver_elim(struct solver_usage *usage, int *indices,
841                        char *fmt, ...) __attribute__((format(printf,3,4)));
842 static int solver_intersect(struct solver_usage *usage,
843                             int *indices1, int *indices2, char *fmt, ...)
844     __attribute__((format(printf,4,5)));
845 static int solver_set(struct solver_usage *usage,
846                       struct solver_scratch *scratch,
847                       int *indices, char *fmt, ...)
848     __attribute__((format(printf,4,5)));
849 #endif
850
851 static int solver_elim(struct solver_usage *usage, int *indices
852 #ifdef STANDALONE_SOLVER
853                        , char *fmt, ...
854 #endif
855                        )
856 {
857     int cr = usage->cr;
858     int fpos, m, i;
859
860     /*
861      * Count the number of set bits within this section of the
862      * cube.
863      */
864     m = 0;
865     fpos = -1;
866     for (i = 0; i < cr; i++)
867         if (usage->cube[indices[i]]) {
868             fpos = indices[i];
869             m++;
870         }
871
872     if (m == 1) {
873         int x, y, n;
874         assert(fpos >= 0);
875
876         n = 1 + fpos % cr;
877         x = fpos / cr;
878         y = x / cr;
879         x %= cr;
880
881         if (!usage->grid[y*cr+x]) {
882 #ifdef STANDALONE_SOLVER
883             if (solver_show_working) {
884                 va_list ap;
885                 printf("%*s", solver_recurse_depth*4, "");
886                 va_start(ap, fmt);
887                 vprintf(fmt, ap);
888                 va_end(ap);
889                 printf(":\n%*s  placing %d at (%d,%d)\n",
890                        solver_recurse_depth*4, "", n, 1+x, 1+y);
891             }
892 #endif
893             solver_place(usage, x, y, n);
894             return +1;
895         }
896     } else if (m == 0) {
897 #ifdef STANDALONE_SOLVER
898         if (solver_show_working) {
899             va_list ap;
900             printf("%*s", solver_recurse_depth*4, "");
901             va_start(ap, fmt);
902             vprintf(fmt, ap);
903             va_end(ap);
904             printf(":\n%*s  no possibilities available\n",
905                    solver_recurse_depth*4, "");
906         }
907 #endif
908         return -1;
909     }
910
911     return 0;
912 }
913
914 static int solver_intersect(struct solver_usage *usage,
915                             int *indices1, int *indices2
916 #ifdef STANDALONE_SOLVER
917                             , char *fmt, ...
918 #endif
919                             )
920 {
921     int cr = usage->cr;
922     int ret, i, j;
923
924     /*
925      * Loop over the first domain and see if there's any set bit
926      * not also in the second.
927      */
928     for (i = j = 0; i < cr; i++) {
929         int p = indices1[i];
930         while (j < cr && indices2[j] < p)
931             j++;
932         if (usage->cube[p]) {
933             if (j < cr && indices2[j] == p)
934                 continue;              /* both domains contain this index */
935             else
936                 return 0;              /* there is, so we can't deduce */
937         }
938     }
939
940     /*
941      * We have determined that all set bits in the first domain are
942      * within its overlap with the second. So loop over the second
943      * domain and remove all set bits that aren't also in that
944      * overlap; return +1 iff we actually _did_ anything.
945      */
946     ret = 0;
947     for (i = j = 0; i < cr; i++) {
948         int p = indices2[i];
949         while (j < cr && indices1[j] < p)
950             j++;
951         if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
952 #ifdef STANDALONE_SOLVER
953             if (solver_show_working) {
954                 int px, py, pn;
955
956                 if (!ret) {
957                     va_list ap;
958                     printf("%*s", solver_recurse_depth*4, "");
959                     va_start(ap, fmt);
960                     vprintf(fmt, ap);
961                     va_end(ap);
962                     printf(":\n");
963                 }
964
965                 pn = 1 + p % cr;
966                 px = p / cr;
967                 py = px / cr;
968                 px %= cr;
969
970                 printf("%*s  ruling out %d at (%d,%d)\n",
971                        solver_recurse_depth*4, "", pn, 1+px, 1+py);
972             }
973 #endif
974             ret = +1;                  /* we did something */
975             usage->cube[p] = 0;
976         }
977     }
978
979     return ret;
980 }
981
982 struct solver_scratch {
983     unsigned char *grid, *rowidx, *colidx, *set;
984     int *neighbours, *bfsqueue;
985     int *indexlist, *indexlist2;
986 #ifdef STANDALONE_SOLVER
987     int *bfsprev;
988 #endif
989 };
990
991 static int solver_set(struct solver_usage *usage,
992                       struct solver_scratch *scratch,
993                       int *indices
994 #ifdef STANDALONE_SOLVER
995                       , char *fmt, ...
996 #endif
997                       )
998 {
999     int cr = usage->cr;
1000     int i, j, n, count;
1001     unsigned char *grid = scratch->grid;
1002     unsigned char *rowidx = scratch->rowidx;
1003     unsigned char *colidx = scratch->colidx;
1004     unsigned char *set = scratch->set;
1005
1006     /*
1007      * We are passed a cr-by-cr matrix of booleans. Our first job
1008      * is to winnow it by finding any definite placements - i.e.
1009      * any row with a solitary 1 - and discarding that row and the
1010      * column containing the 1.
1011      */
1012     memset(rowidx, TRUE, cr);
1013     memset(colidx, TRUE, cr);
1014     for (i = 0; i < cr; i++) {
1015         int count = 0, first = -1;
1016         for (j = 0; j < cr; j++)
1017             if (usage->cube[indices[i*cr+j]])
1018                 first = j, count++;
1019
1020         /*
1021          * If count == 0, then there's a row with no 1s at all and
1022          * the puzzle is internally inconsistent. However, we ought
1023          * to have caught this already during the simpler reasoning
1024          * methods, so we can safely fail an assertion if we reach
1025          * this point here.
1026          */
1027         assert(count > 0);
1028         if (count == 1)
1029             rowidx[i] = colidx[first] = FALSE;
1030     }
1031
1032     /*
1033      * Convert each of rowidx/colidx from a list of 0s and 1s to a
1034      * list of the indices of the 1s.
1035      */
1036     for (i = j = 0; i < cr; i++)
1037         if (rowidx[i])
1038             rowidx[j++] = i;
1039     n = j;
1040     for (i = j = 0; i < cr; i++)
1041         if (colidx[i])
1042             colidx[j++] = i;
1043     assert(n == j);
1044
1045     /*
1046      * And create the smaller matrix.
1047      */
1048     for (i = 0; i < n; i++)
1049         for (j = 0; j < n; j++)
1050             grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
1051
1052     /*
1053      * Having done that, we now have a matrix in which every row
1054      * has at least two 1s in. Now we search to see if we can find
1055      * a rectangle of zeroes (in the set-theoretic sense of
1056      * `rectangle', i.e. a subset of rows crossed with a subset of
1057      * columns) whose width and height add up to n.
1058      */
1059
1060     memset(set, 0, n);
1061     count = 0;
1062     while (1) {
1063         /*
1064          * We have a candidate set. If its size is <=1 or >=n-1
1065          * then we move on immediately.
1066          */
1067         if (count > 1 && count < n-1) {
1068             /*
1069              * The number of rows we need is n-count. See if we can
1070              * find that many rows which each have a zero in all
1071              * the positions listed in `set'.
1072              */
1073             int rows = 0;
1074             for (i = 0; i < n; i++) {
1075                 int ok = TRUE;
1076                 for (j = 0; j < n; j++)
1077                     if (set[j] && grid[i*cr+j]) {
1078                         ok = FALSE;
1079                         break;
1080                     }
1081                 if (ok)
1082                     rows++;
1083             }
1084
1085             /*
1086              * We expect never to be able to get _more_ than
1087              * n-count suitable rows: this would imply that (for
1088              * example) there are four numbers which between them
1089              * have at most three possible positions, and hence it
1090              * indicates a faulty deduction before this point or
1091              * even a bogus clue.
1092              */
1093             if (rows > n - count) {
1094 #ifdef STANDALONE_SOLVER
1095                 if (solver_show_working) {
1096                     va_list ap;
1097                     printf("%*s", solver_recurse_depth*4,
1098                            "");
1099                     va_start(ap, fmt);
1100                     vprintf(fmt, ap);
1101                     va_end(ap);
1102                     printf(":\n%*s  contradiction reached\n",
1103                            solver_recurse_depth*4, "");
1104                 }
1105 #endif
1106                 return -1;
1107             }
1108
1109             if (rows >= n - count) {
1110                 int progress = FALSE;
1111
1112                 /*
1113                  * We've got one! Now, for each row which _doesn't_
1114                  * satisfy the criterion, eliminate all its set
1115                  * bits in the positions _not_ listed in `set'.
1116                  * Return +1 (meaning progress has been made) if we
1117                  * successfully eliminated anything at all.
1118                  * 
1119                  * This involves referring back through
1120                  * rowidx/colidx in order to work out which actual
1121                  * positions in the cube to meddle with.
1122                  */
1123                 for (i = 0; i < n; i++) {
1124                     int ok = TRUE;
1125                     for (j = 0; j < n; j++)
1126                         if (set[j] && grid[i*cr+j]) {
1127                             ok = FALSE;
1128                             break;
1129                         }
1130                     if (!ok) {
1131                         for (j = 0; j < n; j++)
1132                             if (!set[j] && grid[i*cr+j]) {
1133                                 int fpos = indices[rowidx[i]*cr+colidx[j]];
1134 #ifdef STANDALONE_SOLVER
1135                                 if (solver_show_working) {
1136                                     int px, py, pn;
1137
1138                                     if (!progress) {
1139                                         va_list ap;
1140                                         printf("%*s", solver_recurse_depth*4,
1141                                                "");
1142                                         va_start(ap, fmt);
1143                                         vprintf(fmt, ap);
1144                                         va_end(ap);
1145                                         printf(":\n");
1146                                     }
1147
1148                                     pn = 1 + fpos % cr;
1149                                     px = fpos / cr;
1150                                     py = px / cr;
1151                                     px %= cr;
1152
1153                                     printf("%*s  ruling out %d at (%d,%d)\n",
1154                                            solver_recurse_depth*4, "",
1155                                            pn, 1+px, 1+py);
1156                                 }
1157 #endif
1158                                 progress = TRUE;
1159                                 usage->cube[fpos] = FALSE;
1160                             }
1161                     }
1162                 }
1163
1164                 if (progress) {
1165                     return +1;
1166                 }
1167             }
1168         }
1169
1170         /*
1171          * Binary increment: change the rightmost 0 to a 1, and
1172          * change all 1s to the right of it to 0s.
1173          */
1174         i = n;
1175         while (i > 0 && set[i-1])
1176             set[--i] = 0, count--;
1177         if (i > 0)
1178             set[--i] = 1, count++;
1179         else
1180             break;                     /* done */
1181     }
1182
1183     return 0;
1184 }
1185
1186 /*
1187  * Look for forcing chains. A forcing chain is a path of
1188  * pairwise-exclusive squares (i.e. each pair of adjacent squares
1189  * in the path are in the same row, column or block) with the
1190  * following properties:
1191  *
1192  *  (a) Each square on the path has precisely two possible numbers.
1193  *
1194  *  (b) Each pair of squares which are adjacent on the path share
1195  *      at least one possible number in common.
1196  *
1197  *  (c) Each square in the middle of the path shares _both_ of its
1198  *      numbers with at least one of its neighbours (not the same
1199  *      one with both neighbours).
1200  *
1201  * These together imply that at least one of the possible number
1202  * choices at one end of the path forces _all_ the rest of the
1203  * numbers along the path. In order to make real use of this, we
1204  * need further properties:
1205  *
1206  *  (c) Ruling out some number N from the square at one end of the
1207  *      path forces the square at the other end to take the same
1208  *      number N.
1209  *
1210  *  (d) The two end squares are both in line with some third
1211  *      square.
1212  *
1213  *  (e) That third square currently has N as a possibility.
1214  *
1215  * If we can find all of that lot, we can deduce that at least one
1216  * of the two ends of the forcing chain has number N, and that
1217  * therefore the mutually adjacent third square does not.
1218  *
1219  * To find forcing chains, we're going to start a bfs at each
1220  * suitable square, once for each of its two possible numbers.
1221  */
1222 static int solver_forcing(struct solver_usage *usage,
1223                           struct solver_scratch *scratch)
1224 {
1225     int cr = usage->cr;
1226     int *bfsqueue = scratch->bfsqueue;
1227 #ifdef STANDALONE_SOLVER
1228     int *bfsprev = scratch->bfsprev;
1229 #endif
1230     unsigned char *number = scratch->grid;
1231     int *neighbours = scratch->neighbours;
1232     int x, y;
1233
1234     for (y = 0; y < cr; y++)
1235         for (x = 0; x < cr; x++) {
1236             int count, t, n;
1237
1238             /*
1239              * If this square doesn't have exactly two candidate
1240              * numbers, don't try it.
1241              * 
1242              * In this loop we also sum the candidate numbers,
1243              * which is a nasty hack to allow us to quickly find
1244              * `the other one' (since we will shortly know there
1245              * are exactly two).
1246              */
1247             for (count = t = 0, n = 1; n <= cr; n++)
1248                 if (cube(x, y, n))
1249                     count++, t += n;
1250             if (count != 2)
1251                 continue;
1252
1253             /*
1254              * Now attempt a bfs for each candidate.
1255              */
1256             for (n = 1; n <= cr; n++)
1257                 if (cube(x, y, n)) {
1258                     int orign, currn, head, tail;
1259
1260                     /*
1261                      * Begin a bfs.
1262                      */
1263                     orign = n;
1264
1265                     memset(number, cr+1, cr*cr);
1266                     head = tail = 0;
1267                     bfsqueue[tail++] = y*cr+x;
1268 #ifdef STANDALONE_SOLVER
1269                     bfsprev[y*cr+x] = -1;
1270 #endif
1271                     number[y*cr+x] = t - n;
1272
1273                     while (head < tail) {
1274                         int xx, yy, nneighbours, xt, yt, i;
1275
1276                         xx = bfsqueue[head++];
1277                         yy = xx / cr;
1278                         xx %= cr;
1279
1280                         currn = number[yy*cr+xx];
1281
1282                         /*
1283                          * Find neighbours of yy,xx.
1284                          */
1285                         nneighbours = 0;
1286                         for (yt = 0; yt < cr; yt++)
1287                             neighbours[nneighbours++] = yt*cr+xx;
1288                         for (xt = 0; xt < cr; xt++)
1289                             neighbours[nneighbours++] = yy*cr+xt;
1290                         xt = usage->blocks->whichblock[yy*cr+xx];
1291                         for (yt = 0; yt < cr; yt++)
1292                             neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1293                         if (usage->diag) {
1294                             int sqindex = yy*cr+xx;
1295                             if (ondiag0(sqindex)) {
1296                                 for (i = 0; i < cr; i++)
1297                                     neighbours[nneighbours++] = diag0(i);
1298                             }
1299                             if (ondiag1(sqindex)) {
1300                                 for (i = 0; i < cr; i++)
1301                                     neighbours[nneighbours++] = diag1(i);
1302                             }
1303                         }
1304
1305                         /*
1306                          * Try visiting each of those neighbours.
1307                          */
1308                         for (i = 0; i < nneighbours; i++) {
1309                             int cc, tt, nn;
1310
1311                             xt = neighbours[i] % cr;
1312                             yt = neighbours[i] / cr;
1313
1314                             /*
1315                              * We need this square to not be
1316                              * already visited, and to include
1317                              * currn as a possible number.
1318                              */
1319                             if (number[yt*cr+xt] <= cr)
1320                                 continue;
1321                             if (!cube(xt, yt, currn))
1322                                 continue;
1323
1324                             /*
1325                              * Don't visit _this_ square a second
1326                              * time!
1327                              */
1328                             if (xt == xx && yt == yy)
1329                                 continue;
1330
1331                             /*
1332                              * To continue with the bfs, we need
1333                              * this square to have exactly two
1334                              * possible numbers.
1335                              */
1336                             for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1337                                 if (cube(xt, yt, nn))
1338                                     cc++, tt += nn;
1339                             if (cc == 2) {
1340                                 bfsqueue[tail++] = yt*cr+xt;
1341 #ifdef STANDALONE_SOLVER
1342                                 bfsprev[yt*cr+xt] = yy*cr+xx;
1343 #endif
1344                                 number[yt*cr+xt] = tt - currn;
1345                             }
1346
1347                             /*
1348                              * One other possibility is that this
1349                              * might be the square in which we can
1350                              * make a real deduction: if it's
1351                              * adjacent to x,y, and currn is equal
1352                              * to the original number we ruled out.
1353                              */
1354                             if (currn == orign &&
1355                                 (xt == x || yt == y ||
1356                                  (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1357                                  (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1358                                                   (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1359 #ifdef STANDALONE_SOLVER
1360                                 if (solver_show_working) {
1361                                     char *sep = "";
1362                                     int xl, yl;
1363                                     printf("%*sforcing chain, %d at ends of ",
1364                                            solver_recurse_depth*4, "", orign);
1365                                     xl = xx;
1366                                     yl = yy;
1367                                     while (1) {
1368                                         printf("%s(%d,%d)", sep, 1+xl,
1369                                                1+yl);
1370                                         xl = bfsprev[yl*cr+xl];
1371                                         if (xl < 0)
1372                                             break;
1373                                         yl = xl / cr;
1374                                         xl %= cr;
1375                                         sep = "-";
1376                                     }
1377                                     printf("\n%*s  ruling out %d at (%d,%d)\n",
1378                                            solver_recurse_depth*4, "",
1379                                            orign, 1+xt, 1+yt);
1380                                 }
1381 #endif
1382                                 cube(xt, yt, orign) = FALSE;
1383                                 return 1;
1384                             }
1385                         }
1386                     }
1387                 }
1388         }
1389
1390     return 0;
1391 }
1392
1393 static int solver_killer_minmax(struct solver_usage *usage,
1394                                 struct block_structure *cages, digit *clues,
1395                                 int b
1396 #ifdef STANDALONE_SOLVER
1397                                 , const char *extra
1398 #endif
1399                                 )
1400 {
1401     int cr = usage->cr;
1402     int i;
1403     int ret = 0;
1404     int nsquares = cages->nr_squares[b];
1405
1406     if (clues[b] == 0)
1407         return 0;
1408
1409     for (i = 0; i < nsquares; i++) {
1410         int n, x = cages->blocks[b][i];
1411
1412         for (n = 1; n <= cr; n++)
1413             if (cube2(x, n)) {
1414                 int maxval = 0, minval = 0;
1415                 int j;
1416                 for (j = 0; j < nsquares; j++) {
1417                     int m;
1418                     int y = cages->blocks[b][j];
1419                     if (i == j)
1420                         continue;
1421                     for (m = 1; m <= cr; m++)
1422                         if (cube2(y, m)) {
1423                             minval += m;
1424                             break;
1425                         }
1426                     for (m = cr; m > 0; m--)
1427                         if (cube2(y, m)) {
1428                             maxval += m;
1429                             break;
1430                         }
1431                 }
1432                 if (maxval + n < clues[b]) {
1433                     cube2(x, n) = FALSE;
1434                     ret = 1;
1435 #ifdef STANDALONE_SOLVER
1436                     if (solver_show_working)
1437                         printf("%*s  ruling out %d at (%d,%d) as too low %s\n",
1438                                solver_recurse_depth*4, "killer minmax analysis",
1439                                n, 1 + x%cr, 1 + x/cr, extra);
1440 #endif
1441                 }
1442                 if (minval + n > clues[b]) {
1443                     cube2(x, n) = FALSE;
1444                     ret = 1;
1445 #ifdef STANDALONE_SOLVER
1446                     if (solver_show_working)
1447                         printf("%*s  ruling out %d at (%d,%d) as too high %s\n",
1448                                solver_recurse_depth*4, "killer minmax analysis",
1449                                n, 1 + x%cr, 1 + x/cr, extra);
1450 #endif
1451                 }
1452             }
1453     }
1454     return ret;
1455 }
1456
1457 static int solver_killer_sums(struct solver_usage *usage, int b,
1458                               struct block_structure *cages, int clue,
1459                               int cage_is_region
1460 #ifdef STANDALONE_SOLVER
1461                               , const char *cage_type
1462 #endif
1463                               )
1464 {
1465     int cr = usage->cr;
1466     int i, ret, max_sums;
1467     int nsquares = cages->nr_squares[b];
1468     unsigned long *sumbits, possible_addends;
1469
1470     if (clue == 0) {
1471         assert(nsquares == 0);
1472         return 0;
1473     }
1474     assert(nsquares > 0);
1475
1476     if (nsquares < 2 || nsquares > 4)
1477         return 0;
1478
1479     if (!cage_is_region) {
1480         int known_row = -1, known_col = -1, known_block = -1;
1481         /*
1482          * Verify that the cage lies entirely within one region,
1483          * so that using the precomputed sums is valid.
1484          */
1485         for (i = 0; i < nsquares; i++) {
1486             int x = cages->blocks[b][i];
1487
1488             assert(usage->grid[x] == 0);
1489
1490             if (i == 0) {
1491                 known_row = x/cr;
1492                 known_col = x%cr;
1493                 known_block = usage->blocks->whichblock[x];
1494             } else {
1495                 if (known_row != x/cr)
1496                     known_row = -1;
1497                 if (known_col != x%cr)
1498                     known_col = -1;
1499                 if (known_block != usage->blocks->whichblock[x])
1500                     known_block = -1;
1501             }
1502         }
1503         if (known_block == -1 && known_col == -1 && known_row == -1)
1504             return 0;
1505     }
1506     if (nsquares == 2) {
1507         if (clue < 3 || clue > 17)
1508             return -1;
1509
1510         sumbits = sum_bits2[clue];
1511         max_sums = MAX_2SUMS;
1512     } else if (nsquares == 3) {
1513         if (clue < 6 || clue > 24)
1514             return -1;
1515
1516         sumbits = sum_bits3[clue];
1517         max_sums = MAX_3SUMS;
1518     } else {
1519         if (clue < 10 || clue > 30)
1520             return -1;
1521
1522         sumbits = sum_bits4[clue];
1523         max_sums = MAX_4SUMS;
1524     }
1525     /*
1526      * For every possible way to get the sum, see if there is
1527      * one square in the cage that disallows all the required
1528      * addends.  If we find one such square, this way to compute
1529      * the sum is impossible.
1530      */
1531     possible_addends = 0;
1532     for (i = 0; i < max_sums; i++) {
1533         int j;
1534         unsigned long bits = sumbits[i];
1535
1536         if (bits == 0)
1537             break;
1538
1539         for (j = 0; j < nsquares; j++) {
1540             int n;
1541             unsigned long square_bits = bits;
1542             int x = cages->blocks[b][j];
1543             for (n = 1; n <= cr; n++)
1544                 if (!cube2(x, n))
1545                     square_bits &= ~(1L << n);
1546             if (square_bits == 0) {
1547                 break;
1548             }
1549         }
1550         if (j == nsquares)
1551             possible_addends |= bits;
1552     }
1553     /*
1554      * Now we know which addends can possibly be used to
1555      * compute the sum.  Remove all other digits from the
1556      * set of possibilities.
1557      */
1558     if (possible_addends == 0)
1559         return -1;
1560
1561     ret = 0;
1562     for (i = 0; i < nsquares; i++) {
1563         int n;
1564         int x = cages->blocks[b][i];
1565         for (n = 1; n <= cr; n++) {
1566             if (!cube2(x, n))
1567                 continue;
1568             if ((possible_addends & (1 << n)) == 0) {
1569                 cube2(x, n) = FALSE;
1570                 ret = 1;
1571 #ifdef STANDALONE_SOLVER
1572                 if (solver_show_working) {
1573                     printf("%*s  using %s\n",
1574                            solver_recurse_depth*4, "killer sums analysis",
1575                            cage_type);
1576                     printf("%*s  ruling out %d at (%d,%d) due to impossible %d-sum\n",
1577                            solver_recurse_depth*4, "",
1578                            n, 1 + x%cr, 1 + x/cr, nsquares);
1579                 }
1580 #endif
1581             }
1582         }
1583     }
1584     return ret;
1585 }
1586
1587 static int filter_whole_cages(struct solver_usage *usage, int *squares, int n,
1588                               int *filtered_sum)
1589 {
1590     int b, i, j, off;
1591     *filtered_sum = 0;
1592
1593     /* First, filter squares with a clue.  */
1594     for (i = j = 0; i < n; i++)
1595         if (usage->grid[squares[i]])
1596             *filtered_sum += usage->grid[squares[i]];
1597         else
1598             squares[j++] = squares[i];
1599     n = j;
1600
1601     /*
1602      * Filter all cages that are covered entirely by the list of
1603      * squares.
1604      */
1605     off = 0;
1606     for (b = 0; b < usage->kblocks->nr_blocks && off < n; b++) {
1607         int b_squares = usage->kblocks->nr_squares[b];
1608         int matched = 0;
1609
1610         if (b_squares == 0)
1611             continue;
1612
1613         /*
1614          * Find all squares of block b that lie in our list,
1615          * and make them contiguous at off, which is the current position
1616          * in the output list.
1617          */
1618         for (i = 0; i < b_squares; i++) {
1619             for (j = off; j < n; j++)
1620                 if (squares[j] == usage->kblocks->blocks[b][i]) {
1621                     int t = squares[off + matched];
1622                     squares[off + matched] = squares[j];
1623                     squares[j] = t;
1624                     matched++;
1625                     break;
1626                 }
1627         }
1628         /* If so, filter out all squares of b from the list.  */
1629         if (matched != usage->kblocks->nr_squares[b]) {
1630             off += matched;
1631             continue;
1632         }
1633         memmove(squares + off, squares + off + matched,
1634                 (n - off - matched) * sizeof *squares);
1635         n -= matched;
1636
1637         *filtered_sum += usage->kclues[b];
1638     }
1639     assert(off == n);
1640     return off;
1641 }
1642
1643 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1644 {
1645     struct solver_scratch *scratch = snew(struct solver_scratch);
1646     int cr = usage->cr;
1647     scratch->grid = snewn(cr*cr, unsigned char);
1648     scratch->rowidx = snewn(cr, unsigned char);
1649     scratch->colidx = snewn(cr, unsigned char);
1650     scratch->set = snewn(cr, unsigned char);
1651     scratch->neighbours = snewn(5*cr, int);
1652     scratch->bfsqueue = snewn(cr*cr, int);
1653 #ifdef STANDALONE_SOLVER
1654     scratch->bfsprev = snewn(cr*cr, int);
1655 #endif
1656     scratch->indexlist = snewn(cr*cr, int);   /* used for set elimination */
1657     scratch->indexlist2 = snewn(cr, int);   /* only used for intersect() */
1658     return scratch;
1659 }
1660
1661 static void solver_free_scratch(struct solver_scratch *scratch)
1662 {
1663 #ifdef STANDALONE_SOLVER
1664     sfree(scratch->bfsprev);
1665 #endif
1666     sfree(scratch->bfsqueue);
1667     sfree(scratch->neighbours);
1668     sfree(scratch->set);
1669     sfree(scratch->colidx);
1670     sfree(scratch->rowidx);
1671     sfree(scratch->grid);
1672     sfree(scratch->indexlist);
1673     sfree(scratch->indexlist2);
1674     sfree(scratch);
1675 }
1676
1677 /*
1678  * Used for passing information about difficulty levels between the solver
1679  * and its callers.
1680  */
1681 struct difficulty {
1682     /* Maximum levels allowed.  */
1683     int maxdiff, maxkdiff;
1684     /* Levels reached by the solver.  */
1685     int diff, kdiff;
1686 };
1687
1688 static void solver(int cr, struct block_structure *blocks,
1689                   struct block_structure *kblocks, int xtype,
1690                   digit *grid, digit *kgrid, struct difficulty *dlev)
1691 {
1692     struct solver_usage *usage;
1693     struct solver_scratch *scratch;
1694     int x, y, b, i, n, ret;
1695     int diff = DIFF_BLOCK;
1696     int kdiff = DIFF_KSINGLE;
1697
1698     /*
1699      * Set up a usage structure as a clean slate (everything
1700      * possible).
1701      */
1702     usage = snew(struct solver_usage);
1703     usage->cr = cr;
1704     usage->blocks = blocks;
1705     if (kblocks) {
1706         usage->kblocks = dup_block_structure(kblocks);
1707         usage->extra_cages = alloc_block_structure (kblocks->c, kblocks->r,
1708                                                     cr * cr, cr, cr * cr);
1709         usage->extra_clues = snewn(cr*cr, digit);
1710     } else {
1711         usage->kblocks = usage->extra_cages = NULL;
1712         usage->extra_clues = NULL;
1713     }
1714     usage->cube = snewn(cr*cr*cr, unsigned char);
1715     usage->grid = grid;                /* write straight back to the input */
1716     if (kgrid) {
1717         int nclues;
1718
1719         assert(kblocks);
1720         nclues = kblocks->nr_blocks;
1721         /*
1722          * Allow for expansion of the killer regions, the absolute
1723          * limit is obviously one region per square.
1724          */
1725         usage->kclues = snewn(cr*cr, digit);
1726         for (i = 0; i < nclues; i++) {
1727             for (n = 0; n < kblocks->nr_squares[i]; n++)
1728                 if (kgrid[kblocks->blocks[i][n]] != 0)
1729                     usage->kclues[i] = kgrid[kblocks->blocks[i][n]];
1730             assert(usage->kclues[i] > 0);
1731         }
1732         memset(usage->kclues + nclues, 0, cr*cr - nclues);
1733     } else {
1734         usage->kclues = NULL;
1735     }
1736
1737     memset(usage->cube, TRUE, cr*cr*cr);
1738
1739     usage->row = snewn(cr * cr, unsigned char);
1740     usage->col = snewn(cr * cr, unsigned char);
1741     usage->blk = snewn(cr * cr, unsigned char);
1742     memset(usage->row, FALSE, cr * cr);
1743     memset(usage->col, FALSE, cr * cr);
1744     memset(usage->blk, FALSE, cr * cr);
1745
1746     if (xtype) {
1747         usage->diag = snewn(cr * 2, unsigned char);
1748         memset(usage->diag, FALSE, cr * 2);
1749     } else
1750         usage->diag = NULL; 
1751
1752     usage->nr_regions = cr * 3 + (xtype ? 2 : 0);
1753     usage->regions = snewn(cr * usage->nr_regions, int);
1754     usage->sq2region = snewn(cr * cr * 3, int *);
1755
1756     for (n = 0; n < cr; n++) {
1757         for (i = 0; i < cr; i++) {
1758             x = n*cr+i;
1759             y = i*cr+n;
1760             b = usage->blocks->blocks[n][i];
1761             usage->regions[cr*n*3 + i] = x;
1762             usage->regions[cr*n*3 + cr + i] = y;
1763             usage->regions[cr*n*3 + 2*cr + i] = b;
1764             usage->sq2region[x*3] = usage->regions + cr*n*3;
1765             usage->sq2region[y*3 + 1] = usage->regions + cr*n*3 + cr;
1766             usage->sq2region[b*3 + 2] = usage->regions + cr*n*3 + 2*cr;
1767         }
1768     }
1769
1770     scratch = solver_new_scratch(usage);
1771
1772     /*
1773      * Place all the clue numbers we are given.
1774      */
1775     for (x = 0; x < cr; x++)
1776         for (y = 0; y < cr; y++) {
1777             int n = grid[y*cr+x];
1778             if (n) {
1779                 if (!cube(x,y,n)) {
1780                     diff = DIFF_IMPOSSIBLE;
1781                     goto got_result;
1782                 }
1783                 solver_place(usage, x, y, grid[y*cr+x]);
1784             }
1785         }
1786
1787     /*
1788      * Now loop over the grid repeatedly trying all permitted modes
1789      * of reasoning. The loop terminates if we complete an
1790      * iteration without making any progress; we then return
1791      * failure or success depending on whether the grid is full or
1792      * not.
1793      */
1794     while (1) {
1795         /*
1796          * I'd like to write `continue;' inside each of the
1797          * following loops, so that the solver returns here after
1798          * making some progress. However, I can't specify that I
1799          * want to continue an outer loop rather than the innermost
1800          * one, so I'm apologetically resorting to a goto.
1801          */
1802         cont:
1803
1804         /*
1805          * Blockwise positional elimination.
1806          */
1807         for (b = 0; b < cr; b++)
1808             for (n = 1; n <= cr; n++)
1809                 if (!usage->blk[b*cr+n-1]) {
1810                     for (i = 0; i < cr; i++)
1811                         scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1812                     ret = solver_elim(usage, scratch->indexlist
1813 #ifdef STANDALONE_SOLVER
1814                                       , "positional elimination,"
1815                                       " %d in block %s", n,
1816                                       usage->blocks->blocknames[b]
1817 #endif
1818                                       );
1819                     if (ret < 0) {
1820                         diff = DIFF_IMPOSSIBLE;
1821                         goto got_result;
1822                     } else if (ret > 0) {
1823                         diff = max(diff, DIFF_BLOCK);
1824                         goto cont;
1825                     }
1826                 }
1827
1828         if (usage->kclues != NULL) {
1829             int changed = FALSE;
1830
1831             /*
1832              * First, bring the kblocks into a more useful form: remove
1833              * all filled-in squares, and reduce the sum by their values.
1834              * Walk in reverse order, since otherwise remove_from_block
1835              * can move element past our loop counter.
1836              */
1837             for (b = 0; b < usage->kblocks->nr_blocks; b++)
1838                 for (i = usage->kblocks->nr_squares[b] -1; i >= 0; i--) {
1839                     int x = usage->kblocks->blocks[b][i];
1840                     int t = usage->grid[x];
1841
1842                     if (t == 0)
1843                         continue;
1844                     remove_from_block(usage->kblocks, b, x);
1845                     if (t > usage->kclues[b]) {
1846                         diff = DIFF_IMPOSSIBLE;
1847                         goto got_result;
1848                     }
1849                     usage->kclues[b] -= t;
1850                     /*
1851                      * Since cages are regions, this tells us something
1852                      * about the other squares in the cage.
1853                      */
1854                     for (n = 0; n < usage->kblocks->nr_squares[b]; n++) {
1855                         cube2(usage->kblocks->blocks[b][n], t) = FALSE;
1856                     }
1857                 }
1858
1859             /*
1860              * The most trivial kind of solver for killer puzzles: fill
1861              * single-square cages.
1862              */
1863             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1864                 int squares = usage->kblocks->nr_squares[b];
1865                 if (squares == 1) {
1866                     int v = usage->kclues[b];
1867                     if (v < 1 || v > cr) {
1868                         diff = DIFF_IMPOSSIBLE;
1869                         goto got_result;
1870                     }
1871                     x = usage->kblocks->blocks[b][0] % cr;
1872                     y = usage->kblocks->blocks[b][0] / cr;
1873                     if (!cube(x, y, v)) {
1874                         diff = DIFF_IMPOSSIBLE;
1875                         goto got_result;
1876                     }
1877                     solver_place(usage, x, y, v);
1878
1879 #ifdef STANDALONE_SOLVER
1880                     if (solver_show_working) {
1881                         printf("%*s  placing %d at (%d,%d)\n",
1882                                solver_recurse_depth*4, "killer single-square cage",
1883                                v, 1 + x%cr, 1 + x/cr);
1884                     }
1885 #endif
1886                     changed = TRUE;
1887                 }
1888             }
1889
1890             if (changed) {
1891                 kdiff = max(kdiff, DIFF_KSINGLE);
1892                 goto cont;
1893             }
1894         }
1895         if (dlev->maxkdiff >= DIFF_KINTERSECT && usage->kclues != NULL) {
1896             int changed = FALSE;
1897             /*
1898              * Now, create the extra_cages information.  Every full region
1899              * (row, column, or block) has the same sum total (45 for 3x3
1900              * puzzles.  After we try to cover these regions with cages that
1901              * lie entirely within them, any squares that remain must bring
1902              * the total to this known value, and so they form additional
1903              * cages which aren't immediately evident in the displayed form
1904              * of the puzzle.
1905              */
1906             usage->extra_cages->nr_blocks = 0;
1907             for (i = 0; i < 3; i++) {
1908                 for (n = 0; n < cr; n++) {
1909                     int *region = usage->regions + cr*n*3 + i*cr;
1910                     int sum = cr * (cr + 1) / 2;
1911                     int nsquares = cr;
1912                     int filtered;
1913                     int n_extra = usage->extra_cages->nr_blocks;
1914                     int *extra_list = usage->extra_cages->blocks[n_extra];
1915                     memcpy(extra_list, region, cr * sizeof *extra_list);
1916
1917                     nsquares = filter_whole_cages(usage, extra_list, nsquares, &filtered);
1918                     sum -= filtered;
1919                     if (nsquares == cr || nsquares == 0)
1920                         continue;
1921                     if (dlev->maxdiff >= DIFF_RECURSIVE) {
1922                         if (sum <= 0) {
1923                             dlev->diff = DIFF_IMPOSSIBLE;
1924                             goto got_result;
1925                         }
1926                     }
1927                     assert(sum > 0);
1928
1929                     if (nsquares == 1) {
1930                         if (sum > cr) {
1931                             diff = DIFF_IMPOSSIBLE;
1932                             goto got_result;
1933                         }
1934                         x = extra_list[0] % cr;
1935                         y = extra_list[0] / cr;
1936                         if (!cube(x, y, sum)) {
1937                             diff = DIFF_IMPOSSIBLE;
1938                             goto got_result;
1939                         }
1940                         solver_place(usage, x, y, sum);
1941                         changed = TRUE;
1942 #ifdef STANDALONE_SOLVER
1943                         if (solver_show_working) {
1944                             printf("%*s  placing %d at (%d,%d)\n",
1945                                    solver_recurse_depth*4, "killer single-square deduced cage",
1946                                    sum, 1 + x, 1 + y);
1947                         }
1948 #endif
1949                     }
1950
1951                     b = usage->kblocks->whichblock[extra_list[0]];
1952                     for (x = 1; x < nsquares; x++)
1953                         if (usage->kblocks->whichblock[extra_list[x]] != b)
1954                             break;
1955                     if (x == nsquares) {
1956                         assert(usage->kblocks->nr_squares[b] > nsquares);
1957                         split_block(usage->kblocks, extra_list, nsquares);
1958                         assert(usage->kblocks->nr_squares[usage->kblocks->nr_blocks - 1] == nsquares);
1959                         usage->kclues[usage->kblocks->nr_blocks - 1] = sum;
1960                         usage->kclues[b] -= sum;
1961                     } else {
1962                         usage->extra_cages->nr_squares[n_extra] = nsquares;
1963                         usage->extra_cages->nr_blocks++;
1964                         usage->extra_clues[n_extra] = sum;
1965                     }
1966                 }
1967             }
1968             if (changed) {
1969                 kdiff = max(kdiff, DIFF_KINTERSECT);
1970                 goto cont;
1971             }
1972         }
1973
1974         /*
1975          * Another simple killer-type elimination.  For every square in a
1976          * cage, find the minimum and maximum possible sums of all the
1977          * other squares in the same cage, and rule out possibilities
1978          * for the given square based on whether they are guaranteed to
1979          * cause the sum to be either too high or too low.
1980          * This is a special case of trying all possible sums across a
1981          * region, which is a recursive algorithm.  We should probably
1982          * implement it for a higher difficulty level.
1983          */
1984         if (dlev->maxkdiff >= DIFF_KMINMAX && usage->kclues != NULL) {
1985             int changed = FALSE;
1986             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1987                 int ret = solver_killer_minmax(usage, usage->kblocks,
1988                                                usage->kclues, b
1989 #ifdef STANDALONE_SOLVER
1990                                              , ""
1991 #endif
1992                                                );
1993                 if (ret < 0) {
1994                     diff = DIFF_IMPOSSIBLE;
1995                     goto got_result;
1996                 } else if (ret > 0)
1997                     changed = TRUE;
1998             }
1999             for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
2000                 int ret = solver_killer_minmax(usage, usage->extra_cages,
2001                                                usage->extra_clues, b
2002 #ifdef STANDALONE_SOLVER
2003                                                , "using deduced cages"
2004 #endif
2005                                                );
2006                 if (ret < 0) {
2007                     diff = DIFF_IMPOSSIBLE;
2008                     goto got_result;
2009                 } else if (ret > 0)
2010                     changed = TRUE;
2011             }
2012             if (changed) {
2013                 kdiff = max(kdiff, DIFF_KMINMAX);
2014                 goto cont;
2015             }
2016         }
2017
2018         /*
2019          * Try to use knowledge of which numbers can be used to generate
2020          * a given sum.
2021          * This can only be used if a cage lies entirely within a region.
2022          */
2023         if (dlev->maxkdiff >= DIFF_KSUMS && usage->kclues != NULL) {
2024             int changed = FALSE;
2025
2026             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
2027                 int ret = solver_killer_sums(usage, b, usage->kblocks,
2028                                              usage->kclues[b], TRUE
2029 #ifdef STANDALONE_SOLVER
2030                                              , "regular clues"
2031 #endif
2032                                              );
2033                 if (ret > 0) {
2034                     changed = TRUE;
2035                     kdiff = max(kdiff, DIFF_KSUMS);
2036                 } else if (ret < 0) {
2037                     diff = DIFF_IMPOSSIBLE;
2038                     goto got_result;
2039                 }
2040             }
2041
2042             for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
2043                 int ret = solver_killer_sums(usage, b, usage->extra_cages,
2044                                              usage->extra_clues[b], FALSE
2045 #ifdef STANDALONE_SOLVER
2046                                              , "deduced clues"
2047 #endif
2048                                              );
2049                 if (ret > 0) {
2050                     changed = TRUE;
2051                     kdiff = max(kdiff, DIFF_KSUMS);
2052                 } else if (ret < 0) {
2053                     diff = DIFF_IMPOSSIBLE;
2054                     goto got_result;
2055                 }
2056             }
2057
2058             if (changed)
2059                 goto cont;
2060         }
2061
2062         if (dlev->maxdiff <= DIFF_BLOCK)
2063             break;
2064
2065         /*
2066          * Row-wise positional elimination.
2067          */
2068         for (y = 0; y < cr; y++)
2069             for (n = 1; n <= cr; n++)
2070                 if (!usage->row[y*cr+n-1]) {
2071                     for (x = 0; x < cr; x++)
2072                         scratch->indexlist[x] = cubepos(x, y, n);
2073                     ret = solver_elim(usage, scratch->indexlist
2074 #ifdef STANDALONE_SOLVER
2075                                       , "positional elimination,"
2076                                       " %d in row %d", n, 1+y
2077 #endif
2078                                       );
2079                     if (ret < 0) {
2080                         diff = DIFF_IMPOSSIBLE;
2081                         goto got_result;
2082                     } else if (ret > 0) {
2083                         diff = max(diff, DIFF_SIMPLE);
2084                         goto cont;
2085                     }
2086                 }
2087         /*
2088          * Column-wise positional elimination.
2089          */
2090         for (x = 0; x < cr; x++)
2091             for (n = 1; n <= cr; n++)
2092                 if (!usage->col[x*cr+n-1]) {
2093                     for (y = 0; y < cr; y++)
2094                         scratch->indexlist[y] = cubepos(x, y, n);
2095                     ret = solver_elim(usage, scratch->indexlist
2096 #ifdef STANDALONE_SOLVER
2097                                       , "positional elimination,"
2098                                       " %d in column %d", n, 1+x
2099 #endif
2100                                       );
2101                     if (ret < 0) {
2102                         diff = DIFF_IMPOSSIBLE;
2103                         goto got_result;
2104                     } else if (ret > 0) {
2105                         diff = max(diff, DIFF_SIMPLE);
2106                         goto cont;
2107                     }
2108                 }
2109
2110         /*
2111          * X-diagonal positional elimination.
2112          */
2113         if (usage->diag) {
2114             for (n = 1; n <= cr; n++)
2115                 if (!usage->diag[n-1]) {
2116                     for (i = 0; i < cr; i++)
2117                         scratch->indexlist[i] = cubepos2(diag0(i), n);
2118                     ret = solver_elim(usage, scratch->indexlist
2119 #ifdef STANDALONE_SOLVER
2120                                       , "positional elimination,"
2121                                       " %d in \\-diagonal", n
2122 #endif
2123                                       );
2124                     if (ret < 0) {
2125                         diff = DIFF_IMPOSSIBLE;
2126                         goto got_result;
2127                     } else if (ret > 0) {
2128                         diff = max(diff, DIFF_SIMPLE);
2129                         goto cont;
2130                     }
2131                 }
2132             for (n = 1; n <= cr; n++)
2133                 if (!usage->diag[cr+n-1]) {
2134                     for (i = 0; i < cr; i++)
2135                         scratch->indexlist[i] = cubepos2(diag1(i), n);
2136                     ret = solver_elim(usage, scratch->indexlist
2137 #ifdef STANDALONE_SOLVER
2138                                       , "positional elimination,"
2139                                       " %d in /-diagonal", n
2140 #endif
2141                                       );
2142                     if (ret < 0) {
2143                         diff = DIFF_IMPOSSIBLE;
2144                         goto got_result;
2145                     } else if (ret > 0) {
2146                         diff = max(diff, DIFF_SIMPLE);
2147                         goto cont;
2148                     }
2149                 }
2150         }
2151
2152         /*
2153          * Numeric elimination.
2154          */
2155         for (x = 0; x < cr; x++)
2156             for (y = 0; y < cr; y++)
2157                 if (!usage->grid[y*cr+x]) {
2158                     for (n = 1; n <= cr; n++)
2159                         scratch->indexlist[n-1] = cubepos(x, y, n);
2160                     ret = solver_elim(usage, scratch->indexlist
2161 #ifdef STANDALONE_SOLVER
2162                                       , "numeric elimination at (%d,%d)",
2163                                       1+x, 1+y
2164 #endif
2165                                       );
2166                     if (ret < 0) {
2167                         diff = DIFF_IMPOSSIBLE;
2168                         goto got_result;
2169                     } else if (ret > 0) {
2170                         diff = max(diff, DIFF_SIMPLE);
2171                         goto cont;
2172                     }
2173                 }
2174
2175         if (dlev->maxdiff <= DIFF_SIMPLE)
2176             break;
2177
2178         /*
2179          * Intersectional analysis, rows vs blocks.
2180          */
2181         for (y = 0; y < cr; y++)
2182             for (b = 0; b < cr; b++)
2183                 for (n = 1; n <= cr; n++) {
2184                     if (usage->row[y*cr+n-1] ||
2185                         usage->blk[b*cr+n-1])
2186                         continue;
2187                     for (i = 0; i < cr; i++) {
2188                         scratch->indexlist[i] = cubepos(i, y, n);
2189                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2190                     }
2191                     /*
2192                      * solver_intersect() never returns -1.
2193                      */
2194                     if (solver_intersect(usage, scratch->indexlist,
2195                                          scratch->indexlist2
2196 #ifdef STANDALONE_SOLVER
2197                                           , "intersectional analysis,"
2198                                           " %d in row %d vs block %s",
2199                                           n, 1+y, usage->blocks->blocknames[b]
2200 #endif
2201                                           ) ||
2202                          solver_intersect(usage, scratch->indexlist2,
2203                                          scratch->indexlist
2204 #ifdef STANDALONE_SOLVER
2205                                           , "intersectional analysis,"
2206                                           " %d in block %s vs row %d",
2207                                           n, usage->blocks->blocknames[b], 1+y
2208 #endif
2209                                           )) {
2210                         diff = max(diff, DIFF_INTERSECT);
2211                         goto cont;
2212                     }
2213                 }
2214
2215         /*
2216          * Intersectional analysis, columns vs blocks.
2217          */
2218         for (x = 0; x < cr; x++)
2219             for (b = 0; b < cr; b++)
2220                 for (n = 1; n <= cr; n++) {
2221                     if (usage->col[x*cr+n-1] ||
2222                         usage->blk[b*cr+n-1])
2223                         continue;
2224                     for (i = 0; i < cr; i++) {
2225                         scratch->indexlist[i] = cubepos(x, i, n);
2226                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2227                     }
2228                     if (solver_intersect(usage, scratch->indexlist,
2229                                          scratch->indexlist2
2230 #ifdef STANDALONE_SOLVER
2231                                           , "intersectional analysis,"
2232                                           " %d in column %d vs block %s",
2233                                           n, 1+x, usage->blocks->blocknames[b]
2234 #endif
2235                                           ) ||
2236                          solver_intersect(usage, scratch->indexlist2,
2237                                          scratch->indexlist
2238 #ifdef STANDALONE_SOLVER
2239                                           , "intersectional analysis,"
2240                                           " %d in block %s vs column %d",
2241                                           n, usage->blocks->blocknames[b], 1+x
2242 #endif
2243                                           )) {
2244                         diff = max(diff, DIFF_INTERSECT);
2245                         goto cont;
2246                     }
2247                 }
2248
2249         if (usage->diag) {
2250             /*
2251              * Intersectional analysis, \-diagonal vs blocks.
2252              */
2253             for (b = 0; b < cr; b++)
2254                 for (n = 1; n <= cr; n++) {
2255                     if (usage->diag[n-1] ||
2256                         usage->blk[b*cr+n-1])
2257                         continue;
2258                     for (i = 0; i < cr; i++) {
2259                         scratch->indexlist[i] = cubepos2(diag0(i), n);
2260                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2261                     }
2262                     if (solver_intersect(usage, scratch->indexlist,
2263                                          scratch->indexlist2
2264 #ifdef STANDALONE_SOLVER
2265                                           , "intersectional analysis,"
2266                                           " %d in \\-diagonal vs block %s",
2267                                           n, usage->blocks->blocknames[b]
2268 #endif
2269                                           ) ||
2270                          solver_intersect(usage, scratch->indexlist2,
2271                                          scratch->indexlist
2272 #ifdef STANDALONE_SOLVER
2273                                           , "intersectional analysis,"
2274                                           " %d in block %s vs \\-diagonal",
2275                                           n, usage->blocks->blocknames[b]
2276 #endif
2277                                           )) {
2278                         diff = max(diff, DIFF_INTERSECT);
2279                         goto cont;
2280                     }
2281                 }
2282
2283             /*
2284              * Intersectional analysis, /-diagonal vs blocks.
2285              */
2286             for (b = 0; b < cr; b++)
2287                 for (n = 1; n <= cr; n++) {
2288                     if (usage->diag[cr+n-1] ||
2289                         usage->blk[b*cr+n-1])
2290                         continue;
2291                     for (i = 0; i < cr; i++) {
2292                         scratch->indexlist[i] = cubepos2(diag1(i), n);
2293                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2294                     }
2295                     if (solver_intersect(usage, scratch->indexlist,
2296                                          scratch->indexlist2
2297 #ifdef STANDALONE_SOLVER
2298                                           , "intersectional analysis,"
2299                                           " %d in /-diagonal vs block %s",
2300                                           n, usage->blocks->blocknames[b]
2301 #endif
2302                                           ) ||
2303                          solver_intersect(usage, scratch->indexlist2,
2304                                          scratch->indexlist
2305 #ifdef STANDALONE_SOLVER
2306                                           , "intersectional analysis,"
2307                                           " %d in block %s vs /-diagonal",
2308                                           n, usage->blocks->blocknames[b]
2309 #endif
2310                                           )) {
2311                         diff = max(diff, DIFF_INTERSECT);
2312                         goto cont;
2313                     }
2314                 }
2315         }
2316
2317         if (dlev->maxdiff <= DIFF_INTERSECT)
2318             break;
2319
2320         /*
2321          * Blockwise set elimination.
2322          */
2323         for (b = 0; b < cr; b++) {
2324             for (i = 0; i < cr; i++)
2325                 for (n = 1; n <= cr; n++)
2326                     scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
2327             ret = solver_set(usage, scratch, scratch->indexlist
2328 #ifdef STANDALONE_SOLVER
2329                              , "set elimination, block %s",
2330                              usage->blocks->blocknames[b]
2331 #endif
2332                                  );
2333             if (ret < 0) {
2334                 diff = DIFF_IMPOSSIBLE;
2335                 goto got_result;
2336             } else if (ret > 0) {
2337                 diff = max(diff, DIFF_SET);
2338                 goto cont;
2339             }
2340         }
2341
2342         /*
2343          * Row-wise set elimination.
2344          */
2345         for (y = 0; y < cr; y++) {
2346             for (x = 0; x < cr; x++)
2347                 for (n = 1; n <= cr; n++)
2348                     scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
2349             ret = solver_set(usage, scratch, scratch->indexlist
2350 #ifdef STANDALONE_SOLVER
2351                              , "set elimination, row %d", 1+y
2352 #endif
2353                              );
2354             if (ret < 0) {
2355                 diff = DIFF_IMPOSSIBLE;
2356                 goto got_result;
2357             } else if (ret > 0) {
2358                 diff = max(diff, DIFF_SET);
2359                 goto cont;
2360             }
2361         }
2362
2363         /*
2364          * Column-wise set elimination.
2365          */
2366         for (x = 0; x < cr; x++) {
2367             for (y = 0; y < cr; y++)
2368                 for (n = 1; n <= cr; n++)
2369                     scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
2370             ret = solver_set(usage, scratch, scratch->indexlist
2371 #ifdef STANDALONE_SOLVER
2372                              , "set elimination, column %d", 1+x
2373 #endif
2374                              );
2375             if (ret < 0) {
2376                 diff = DIFF_IMPOSSIBLE;
2377                 goto got_result;
2378             } else if (ret > 0) {
2379                 diff = max(diff, DIFF_SET);
2380                 goto cont;
2381             }
2382         }
2383
2384         if (usage->diag) {
2385             /*
2386              * \-diagonal set elimination.
2387              */
2388             for (i = 0; i < cr; i++)
2389                 for (n = 1; n <= cr; n++)
2390                     scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
2391             ret = solver_set(usage, scratch, scratch->indexlist
2392 #ifdef STANDALONE_SOLVER
2393                              , "set elimination, \\-diagonal"
2394 #endif
2395                              );
2396             if (ret < 0) {
2397                 diff = DIFF_IMPOSSIBLE;
2398                 goto got_result;
2399             } else if (ret > 0) {
2400                 diff = max(diff, DIFF_SET);
2401                 goto cont;
2402             }
2403
2404             /*
2405              * /-diagonal set elimination.
2406              */
2407             for (i = 0; i < cr; i++)
2408                 for (n = 1; n <= cr; n++)
2409                     scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
2410             ret = solver_set(usage, scratch, scratch->indexlist
2411 #ifdef STANDALONE_SOLVER
2412                              , "set elimination, /-diagonal"
2413 #endif
2414                              );
2415             if (ret < 0) {
2416                 diff = DIFF_IMPOSSIBLE;
2417                 goto got_result;
2418             } else if (ret > 0) {
2419                 diff = max(diff, DIFF_SET);
2420                 goto cont;
2421             }
2422         }
2423
2424         if (dlev->maxdiff <= DIFF_SET)
2425             break;
2426
2427         /*
2428          * Row-vs-column set elimination on a single number.
2429          */
2430         for (n = 1; n <= cr; n++) {
2431             for (y = 0; y < cr; y++)
2432                 for (x = 0; x < cr; x++)
2433                     scratch->indexlist[y*cr+x] = cubepos(x, y, n);
2434             ret = solver_set(usage, scratch, scratch->indexlist
2435 #ifdef STANDALONE_SOLVER
2436                              , "positional set elimination, number %d", n
2437 #endif
2438                              );
2439             if (ret < 0) {
2440                 diff = DIFF_IMPOSSIBLE;
2441                 goto got_result;
2442             } else if (ret > 0) {
2443                 diff = max(diff, DIFF_EXTREME);
2444                 goto cont;
2445             }
2446         }
2447
2448         /*
2449          * Forcing chains.
2450          */
2451         if (solver_forcing(usage, scratch)) {
2452             diff = max(diff, DIFF_EXTREME);
2453             goto cont;
2454         }
2455
2456         /*
2457          * If we reach here, we have made no deductions in this
2458          * iteration, so the algorithm terminates.
2459          */
2460         break;
2461     }
2462
2463     /*
2464      * Last chance: if we haven't fully solved the puzzle yet, try
2465      * recursing based on guesses for a particular square. We pick
2466      * one of the most constrained empty squares we can find, which
2467      * has the effect of pruning the search tree as much as
2468      * possible.
2469      */
2470     if (dlev->maxdiff >= DIFF_RECURSIVE) {
2471         int best, bestcount;
2472
2473         best = -1;
2474         bestcount = cr+1;
2475
2476         for (y = 0; y < cr; y++)
2477             for (x = 0; x < cr; x++)
2478                 if (!grid[y*cr+x]) {
2479                     int count;
2480
2481                     /*
2482                      * An unfilled square. Count the number of
2483                      * possible digits in it.
2484                      */
2485                     count = 0;
2486                     for (n = 1; n <= cr; n++)
2487                         if (cube(x,y,n))
2488                             count++;
2489
2490                     /*
2491                      * We should have found any impossibilities
2492                      * already, so this can safely be an assert.
2493                      */
2494                     assert(count > 1);
2495
2496                     if (count < bestcount) {
2497                         bestcount = count;
2498                         best = y*cr+x;
2499                     }
2500                 }
2501
2502         if (best != -1) {
2503             int i, j;
2504             digit *list, *ingrid, *outgrid;
2505
2506             diff = DIFF_IMPOSSIBLE;    /* no solution found yet */
2507
2508             /*
2509              * Attempt recursion.
2510              */
2511             y = best / cr;
2512             x = best % cr;
2513
2514             list = snewn(cr, digit);
2515             ingrid = snewn(cr * cr, digit);
2516             outgrid = snewn(cr * cr, digit);
2517             memcpy(ingrid, grid, cr * cr);
2518
2519             /* Make a list of the possible digits. */
2520             for (j = 0, n = 1; n <= cr; n++)
2521                 if (cube(x,y,n))
2522                     list[j++] = n;
2523
2524 #ifdef STANDALONE_SOLVER
2525             if (solver_show_working) {
2526                 char *sep = "";
2527                 printf("%*srecursing on (%d,%d) [",
2528                        solver_recurse_depth*4, "", x + 1, y + 1);
2529                 for (i = 0; i < j; i++) {
2530                     printf("%s%d", sep, list[i]);
2531                     sep = " or ";
2532                 }
2533                 printf("]\n");
2534             }
2535 #endif
2536
2537             /*
2538              * And step along the list, recursing back into the
2539              * main solver at every stage.
2540              */
2541             for (i = 0; i < j; i++) {
2542                 memcpy(outgrid, ingrid, cr * cr);
2543                 outgrid[y*cr+x] = list[i];
2544
2545 #ifdef STANDALONE_SOLVER
2546                 if (solver_show_working)
2547                     printf("%*sguessing %d at (%d,%d)\n",
2548                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2549                 solver_recurse_depth++;
2550 #endif
2551
2552                 solver(cr, blocks, kblocks, xtype, outgrid, kgrid, dlev);
2553
2554 #ifdef STANDALONE_SOLVER
2555                 solver_recurse_depth--;
2556                 if (solver_show_working) {
2557                     printf("%*sretracting %d at (%d,%d)\n",
2558                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2559                 }
2560 #endif
2561
2562                 /*
2563                  * If we have our first solution, copy it into the
2564                  * grid we will return.
2565                  */
2566                 if (diff == DIFF_IMPOSSIBLE && dlev->diff != DIFF_IMPOSSIBLE)
2567                     memcpy(grid, outgrid, cr*cr);
2568
2569                 if (dlev->diff == DIFF_AMBIGUOUS)
2570                     diff = DIFF_AMBIGUOUS;
2571                 else if (dlev->diff == DIFF_IMPOSSIBLE)
2572                     /* do not change our return value */;
2573                 else {
2574                     /* the recursion turned up exactly one solution */
2575                     if (diff == DIFF_IMPOSSIBLE)
2576                         diff = DIFF_RECURSIVE;
2577                     else
2578                         diff = DIFF_AMBIGUOUS;
2579                 }
2580
2581                 /*
2582                  * As soon as we've found more than one solution,
2583                  * give up immediately.
2584                  */
2585                 if (diff == DIFF_AMBIGUOUS)
2586                     break;
2587             }
2588
2589             sfree(outgrid);
2590             sfree(ingrid);
2591             sfree(list);
2592         }
2593
2594     } else {
2595         /*
2596          * We're forbidden to use recursion, so we just see whether
2597          * our grid is fully solved, and return DIFF_IMPOSSIBLE
2598          * otherwise.
2599          */
2600         for (y = 0; y < cr; y++)
2601             for (x = 0; x < cr; x++)
2602                 if (!grid[y*cr+x])
2603                     diff = DIFF_IMPOSSIBLE;
2604     }
2605
2606     got_result:
2607     dlev->diff = diff;
2608     dlev->kdiff = kdiff;
2609
2610 #ifdef STANDALONE_SOLVER
2611     if (solver_show_working)
2612         printf("%*s%s found\n",
2613                solver_recurse_depth*4, "",
2614                diff == DIFF_IMPOSSIBLE ? "no solution" :
2615                diff == DIFF_AMBIGUOUS ? "multiple solutions" :
2616                "one solution");
2617 #endif
2618
2619     sfree(usage->sq2region);
2620     sfree(usage->regions);
2621     sfree(usage->cube);
2622     sfree(usage->row);
2623     sfree(usage->col);
2624     sfree(usage->blk);
2625     if (usage->kblocks) {
2626         free_block_structure(usage->kblocks);
2627         free_block_structure(usage->extra_cages);
2628         sfree(usage->extra_clues);
2629     }
2630     if (usage->kclues) sfree(usage->kclues);
2631     sfree(usage);
2632
2633     solver_free_scratch(scratch);
2634 }
2635
2636 /* ----------------------------------------------------------------------
2637  * End of solver code.
2638  */
2639
2640 /* ----------------------------------------------------------------------
2641  * Killer set generator.
2642  */
2643
2644 /* ----------------------------------------------------------------------
2645  * Solo filled-grid generator.
2646  *
2647  * This grid generator works by essentially trying to solve a grid
2648  * starting from no clues, and not worrying that there's more than
2649  * one possible solution. Unfortunately, it isn't computationally
2650  * feasible to do this by calling the above solver with an empty
2651  * grid, because that one needs to allocate a lot of scratch space
2652  * at every recursion level. Instead, I have a much simpler
2653  * algorithm which I shamelessly copied from a Python solver
2654  * written by Andrew Wilkinson (which is GPLed, but I've reused
2655  * only ideas and no code). It mostly just does the obvious
2656  * recursive thing: pick an empty square, put one of the possible
2657  * digits in it, recurse until all squares are filled, backtrack
2658  * and change some choices if necessary.
2659  *
2660  * The clever bit is that every time it chooses which square to
2661  * fill in next, it does so by counting the number of _possible_
2662  * numbers that can go in each square, and it prioritises so that
2663  * it picks a square with the _lowest_ number of possibilities. The
2664  * idea is that filling in lots of the obvious bits (particularly
2665  * any squares with only one possibility) will cut down on the list
2666  * of possibilities for other squares and hence reduce the enormous
2667  * search space as much as possible as early as possible.
2668  *
2669  * The use of bit sets implies that we support puzzles up to a size of
2670  * 32x32 (less if anyone finds a 16-bit machine to compile this on).
2671  */
2672
2673 /*
2674  * Internal data structure used in gridgen to keep track of
2675  * progress.
2676  */
2677 struct gridgen_coord { int x, y, r; };
2678 struct gridgen_usage {
2679     int cr;
2680     struct block_structure *blocks, *kblocks;
2681     /* grid is a copy of the input grid, modified as we go along */
2682     digit *grid;
2683     /*
2684      * Bitsets.  In each of them, bit n is set if digit n has been placed
2685      * in the corresponding region.  row, col and blk are used for all
2686      * puzzles.  cge is used only for killer puzzles, and diag is used
2687      * only for x-type puzzles.
2688      * All of these have cr entries, except diag which only has 2,
2689      * and cge, which has as many entries as kblocks.
2690      */
2691     unsigned int *row, *col, *blk, *cge, *diag;
2692     /* This lists all the empty spaces remaining in the grid. */
2693     struct gridgen_coord *spaces;
2694     int nspaces;
2695     /* If we need randomisation in the solve, this is our random state. */
2696     random_state *rs;
2697 };
2698
2699 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n)
2700 {
2701     unsigned int bit = 1 << n;
2702     int cr = usage->cr;
2703     usage->row[y] |= bit;
2704     usage->col[x] |= bit;
2705     usage->blk[usage->blocks->whichblock[y*cr+x]] |= bit;
2706     if (usage->cge)
2707         usage->cge[usage->kblocks->whichblock[y*cr+x]] |= bit;
2708     if (usage->diag) {
2709         if (ondiag0(y*cr+x))
2710             usage->diag[0] |= bit;
2711         if (ondiag1(y*cr+x))
2712             usage->diag[1] |= bit;
2713     }
2714     usage->grid[y*cr+x] = n;
2715 }
2716
2717 static void gridgen_remove(struct gridgen_usage *usage, int x, int y, digit n)
2718 {
2719     unsigned int mask = ~(1 << n);
2720     int cr = usage->cr;
2721     usage->row[y] &= mask;
2722     usage->col[x] &= mask;
2723     usage->blk[usage->blocks->whichblock[y*cr+x]] &= mask;
2724     if (usage->cge)
2725         usage->cge[usage->kblocks->whichblock[y*cr+x]] &= mask;
2726     if (usage->diag) {
2727         if (ondiag0(y*cr+x))
2728             usage->diag[0] &= mask;
2729         if (ondiag1(y*cr+x))
2730             usage->diag[1] &= mask;
2731     }
2732     usage->grid[y*cr+x] = 0;
2733 }
2734
2735 #define N_SINGLE 32
2736
2737 /*
2738  * The real recursive step in the generating function.
2739  *
2740  * Return values: 1 means solution found, 0 means no solution
2741  * found on this branch.
2742  */
2743 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
2744 {
2745     int cr = usage->cr;
2746     int i, j, n, sx, sy, bestm, bestr, ret;
2747     int *digits;
2748     unsigned int used;
2749
2750     /*
2751      * Firstly, check for completion! If there are no spaces left
2752      * in the grid, we have a solution.
2753      */
2754     if (usage->nspaces == 0)
2755         return TRUE;
2756
2757     /*
2758      * Next, abandon generation if we went over our steps limit.
2759      */
2760     if (*steps <= 0)
2761         return FALSE;
2762     (*steps)--;
2763
2764     /*
2765      * Otherwise, there must be at least one space. Find the most
2766      * constrained space, using the `r' field as a tie-breaker.
2767      */
2768     bestm = cr+1;                      /* so that any space will beat it */
2769     bestr = 0;
2770     used = ~0;
2771     i = sx = sy = -1;
2772     for (j = 0; j < usage->nspaces; j++) {
2773         int x = usage->spaces[j].x, y = usage->spaces[j].y;
2774         unsigned int used_xy;
2775         int m;
2776
2777         m = usage->blocks->whichblock[y*cr+x];
2778         used_xy = usage->row[y] | usage->col[x] | usage->blk[m];
2779         if (usage->cge != NULL)
2780             used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2781         if (usage->cge != NULL)
2782             used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2783         if (usage->diag != NULL) {
2784             if (ondiag0(y*cr+x))
2785                 used_xy |= usage->diag[0];
2786             if (ondiag1(y*cr+x))
2787                 used_xy |= usage->diag[1];
2788         }
2789
2790         /*
2791          * Find the number of digits that could go in this space.
2792          */
2793         m = 0;
2794         for (n = 1; n <= cr; n++) {
2795             unsigned int bit = 1 << n;
2796             if ((used_xy & bit) == 0)
2797                 m++;
2798         }
2799         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
2800             bestm = m;
2801             bestr = usage->spaces[j].r;
2802             sx = x;
2803             sy = y;
2804             i = j;
2805             used = used_xy;
2806         }
2807     }
2808
2809     /*
2810      * Swap that square into the final place in the spaces array,
2811      * so that decrementing nspaces will remove it from the list.
2812      */
2813     if (i != usage->nspaces-1) {
2814         struct gridgen_coord t;
2815         t = usage->spaces[usage->nspaces-1];
2816         usage->spaces[usage->nspaces-1] = usage->spaces[i];
2817         usage->spaces[i] = t;
2818     }
2819
2820     /*
2821      * Now we've decided which square to start our recursion at,
2822      * simply go through all possible values, shuffling them
2823      * randomly first if necessary.
2824      */
2825     digits = snewn(bestm, int);
2826
2827     j = 0;
2828     for (n = 1; n <= cr; n++) {
2829         unsigned int bit = 1 << n;
2830
2831         if ((used & bit) == 0)
2832             digits[j++] = n;
2833     }
2834
2835     if (usage->rs)
2836         shuffle(digits, j, sizeof(*digits), usage->rs);
2837
2838     /* And finally, go through the digit list and actually recurse. */
2839     ret = FALSE;
2840     for (i = 0; i < j; i++) {
2841         n = digits[i];
2842
2843         /* Update the usage structure to reflect the placing of this digit. */
2844         gridgen_place(usage, sx, sy, n);
2845         usage->nspaces--;
2846
2847         /* Call the solver recursively. Stop when we find a solution. */
2848         if (gridgen_real(usage, grid, steps)) {
2849             ret = TRUE;
2850             break;
2851         }
2852
2853         /* Revert the usage structure. */
2854         gridgen_remove(usage, sx, sy, n);
2855         usage->nspaces++;
2856     }
2857
2858     sfree(digits);
2859     return ret;
2860 }
2861
2862 /*
2863  * Entry point to generator. You give it parameters and a starting
2864  * grid, which is simply an array of cr*cr digits.
2865  */
2866 static int gridgen(int cr, struct block_structure *blocks,
2867                    struct block_structure *kblocks, int xtype,
2868                    digit *grid, random_state *rs, int maxsteps)
2869 {
2870     struct gridgen_usage *usage;
2871     int x, y, ret;
2872
2873     /*
2874      * Clear the grid to start with.
2875      */
2876     memset(grid, 0, cr*cr);
2877
2878     /*
2879      * Create a gridgen_usage structure.
2880      */
2881     usage = snew(struct gridgen_usage);
2882
2883     usage->cr = cr;
2884     usage->blocks = blocks;
2885
2886     usage->grid = grid;
2887
2888     usage->row = snewn(cr, unsigned int);
2889     usage->col = snewn(cr, unsigned int);
2890     usage->blk = snewn(cr, unsigned int);
2891     if (kblocks != NULL) {
2892         usage->kblocks = kblocks;
2893         usage->cge = snewn(usage->kblocks->nr_blocks, unsigned int);
2894         memset(usage->cge, FALSE, kblocks->nr_blocks * sizeof *usage->cge);
2895     } else {
2896         usage->cge = NULL;
2897     }
2898
2899     memset(usage->row, 0, cr * sizeof *usage->row);
2900     memset(usage->col, 0, cr * sizeof *usage->col);
2901     memset(usage->blk, 0, cr * sizeof *usage->blk);
2902
2903     if (xtype) {
2904         usage->diag = snewn(2, unsigned int);
2905         memset(usage->diag, 0, 2 * sizeof *usage->diag);
2906     } else {
2907         usage->diag = NULL;
2908     }
2909
2910     /*
2911      * Begin by filling in the whole top row with randomly chosen
2912      * numbers. This cannot introduce any bias or restriction on
2913      * the available grids, since we already know those numbers
2914      * are all distinct so all we're doing is choosing their
2915      * labels.
2916      */
2917     for (x = 0; x < cr; x++)
2918         grid[x] = x+1;
2919     shuffle(grid, cr, sizeof(*grid), rs);
2920     for (x = 0; x < cr; x++)
2921         gridgen_place(usage, x, 0, grid[x]);
2922
2923     usage->spaces = snewn(cr * cr, struct gridgen_coord);
2924     usage->nspaces = 0;
2925
2926     usage->rs = rs;
2927
2928     /*
2929      * Initialise the list of grid spaces, taking care to leave
2930      * out the row I've already filled in above.
2931      */
2932     for (y = 1; y < cr; y++) {
2933         for (x = 0; x < cr; x++) {
2934             usage->spaces[usage->nspaces].x = x;
2935             usage->spaces[usage->nspaces].y = y;
2936             usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2937             usage->nspaces++;
2938         }
2939     }
2940
2941     /*
2942      * Run the real generator function.
2943      */
2944     ret = gridgen_real(usage, grid, &maxsteps);
2945
2946     /*
2947      * Clean up the usage structure now we have our answer.
2948      */
2949     sfree(usage->spaces);
2950     sfree(usage->cge);
2951     sfree(usage->blk);
2952     sfree(usage->col);
2953     sfree(usage->row);
2954     sfree(usage);
2955
2956     return ret;
2957 }
2958
2959 /* ----------------------------------------------------------------------
2960  * End of grid generator code.
2961  */
2962
2963 /*
2964  * Check whether a grid contains a valid complete puzzle.
2965  */
2966 static int check_valid(int cr, struct block_structure *blocks,
2967                        struct block_structure *kblocks, int xtype, digit *grid)
2968 {
2969     unsigned char *used;
2970     int x, y, i, j, n;
2971
2972     used = snewn(cr, unsigned char);
2973
2974     /*
2975      * Check that each row contains precisely one of everything.
2976      */
2977     for (y = 0; y < cr; y++) {
2978         memset(used, FALSE, cr);
2979         for (x = 0; x < cr; x++)
2980             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2981                 used[grid[y*cr+x]-1] = TRUE;
2982         for (n = 0; n < cr; n++)
2983             if (!used[n]) {
2984                 sfree(used);
2985                 return FALSE;
2986             }
2987     }
2988
2989     /*
2990      * Check that each column contains precisely one of everything.
2991      */
2992     for (x = 0; x < cr; x++) {
2993         memset(used, FALSE, cr);
2994         for (y = 0; y < cr; y++)
2995             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2996                 used[grid[y*cr+x]-1] = TRUE;
2997         for (n = 0; n < cr; n++)
2998             if (!used[n]) {
2999                 sfree(used);
3000                 return FALSE;
3001             }
3002     }
3003
3004     /*
3005      * Check that each block contains precisely one of everything.
3006      */
3007     for (i = 0; i < cr; i++) {
3008         memset(used, FALSE, cr);
3009         for (j = 0; j < cr; j++)
3010             if (grid[blocks->blocks[i][j]] > 0 &&
3011                 grid[blocks->blocks[i][j]] <= cr)
3012                 used[grid[blocks->blocks[i][j]]-1] = TRUE;
3013         for (n = 0; n < cr; n++)
3014             if (!used[n]) {
3015                 sfree(used);
3016                 return FALSE;
3017             }
3018     }
3019
3020     /*
3021      * Check that each Killer cage, if any, contains at most one of
3022      * everything.
3023      */
3024     if (kblocks) {
3025         for (i = 0; i < kblocks->nr_blocks; i++) {
3026             memset(used, FALSE, cr);
3027             for (j = 0; j < kblocks->nr_squares[i]; j++)
3028                 if (grid[kblocks->blocks[i][j]] > 0 &&
3029                     grid[kblocks->blocks[i][j]] <= cr) {
3030                     if (used[grid[kblocks->blocks[i][j]]-1]) {
3031                         sfree(used);
3032                         return FALSE;
3033                     }
3034                     used[grid[kblocks->blocks[i][j]]-1] = TRUE;
3035                 }
3036         }
3037     }
3038
3039     /*
3040      * Check that each diagonal contains precisely one of everything.
3041      */
3042     if (xtype) {
3043         memset(used, FALSE, cr);
3044         for (i = 0; i < cr; i++)
3045             if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
3046                 used[grid[diag0(i)]-1] = TRUE;
3047         for (n = 0; n < cr; n++)
3048             if (!used[n]) {
3049                 sfree(used);
3050                 return FALSE;
3051             }
3052         for (i = 0; i < cr; i++)
3053             if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
3054                 used[grid[diag1(i)]-1] = TRUE;
3055         for (n = 0; n < cr; n++)
3056             if (!used[n]) {
3057                 sfree(used);
3058                 return FALSE;
3059             }
3060     }
3061
3062     sfree(used);
3063     return TRUE;
3064 }
3065
3066 static int symmetries(const game_params *params, int x, int y,
3067                       int *output, int s)
3068 {
3069     int c = params->c, r = params->r, cr = c*r;
3070     int i = 0;
3071
3072 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
3073
3074     ADD(x, y);
3075
3076     switch (s) {
3077       case SYMM_NONE:
3078         break;                         /* just x,y is all we need */
3079       case SYMM_ROT2:
3080         ADD(cr - 1 - x, cr - 1 - y);
3081         break;
3082       case SYMM_ROT4:
3083         ADD(cr - 1 - y, x);
3084         ADD(y, cr - 1 - x);
3085         ADD(cr - 1 - x, cr - 1 - y);
3086         break;
3087       case SYMM_REF2:
3088         ADD(cr - 1 - x, y);
3089         break;
3090       case SYMM_REF2D:
3091         ADD(y, x);
3092         break;
3093       case SYMM_REF4:
3094         ADD(cr - 1 - x, y);
3095         ADD(x, cr - 1 - y);
3096         ADD(cr - 1 - x, cr - 1 - y);
3097         break;
3098       case SYMM_REF4D:
3099         ADD(y, x);
3100         ADD(cr - 1 - x, cr - 1 - y);
3101         ADD(cr - 1 - y, cr - 1 - x);
3102         break;
3103       case SYMM_REF8:
3104         ADD(cr - 1 - x, y);
3105         ADD(x, cr - 1 - y);
3106         ADD(cr - 1 - x, cr - 1 - y);
3107         ADD(y, x);
3108         ADD(y, cr - 1 - x);
3109         ADD(cr - 1 - y, x);
3110         ADD(cr - 1 - y, cr - 1 - x);
3111         break;
3112     }
3113
3114 #undef ADD
3115
3116     return i;
3117 }
3118
3119 static char *encode_solve_move(int cr, digit *grid)
3120 {
3121     int i, len;
3122     char *ret, *p, *sep;
3123
3124     /*
3125      * It's surprisingly easy to work out _exactly_ how long this
3126      * string needs to be. To decimal-encode all the numbers from 1
3127      * to n:
3128      * 
3129      *  - every number has a units digit; total is n.
3130      *  - all numbers above 9 have a tens digit; total is max(n-9,0).
3131      *  - all numbers above 99 have a hundreds digit; total is max(n-99,0).
3132      *  - and so on.
3133      */
3134     len = 0;
3135     for (i = 1; i <= cr; i *= 10)
3136         len += max(cr - i + 1, 0);
3137     len += cr;                 /* don't forget the commas */
3138     len *= cr;                 /* there are cr rows of these */
3139
3140     /*
3141      * Now len is one bigger than the total size of the
3142      * comma-separated numbers (because we counted an
3143      * additional leading comma). We need to have a leading S
3144      * and a trailing NUL, so we're off by one in total.
3145      */
3146     len++;
3147
3148     ret = snewn(len, char);
3149     p = ret;
3150     *p++ = 'S';
3151     sep = "";
3152     for (i = 0; i < cr*cr; i++) {
3153         p += sprintf(p, "%s%d", sep, grid[i]);
3154         sep = ",";
3155     }
3156     *p++ = '\0';
3157     assert(p - ret == len);
3158
3159     return ret;
3160 }
3161
3162 static void dsf_to_blocks(int *dsf, struct block_structure *blocks,
3163                           int min_expected, int max_expected)
3164 {
3165     int cr = blocks->c * blocks->r, area = cr * cr;
3166     int i, nb = 0;
3167
3168     for (i = 0; i < area; i++)
3169         blocks->whichblock[i] = -1;
3170     for (i = 0; i < area; i++) {
3171         int j = dsf_canonify(dsf, i);
3172         if (blocks->whichblock[j] < 0)
3173             blocks->whichblock[j] = nb++;
3174         blocks->whichblock[i] = blocks->whichblock[j];
3175     }
3176     assert(nb >= min_expected && nb <= max_expected);
3177     blocks->nr_blocks = nb;
3178 }
3179
3180 static void make_blocks_from_whichblock(struct block_structure *blocks)
3181 {
3182     int i;
3183
3184     for (i = 0; i < blocks->nr_blocks; i++) {
3185         blocks->blocks[i][blocks->max_nr_squares-1] = 0;
3186         blocks->nr_squares[i] = 0;
3187     }
3188     for (i = 0; i < blocks->area; i++) {
3189         int b = blocks->whichblock[i];
3190         int j = blocks->blocks[b][blocks->max_nr_squares-1]++;
3191         assert(j < blocks->max_nr_squares);
3192         blocks->blocks[b][j] = i;
3193         blocks->nr_squares[b]++;
3194     }
3195 }
3196
3197 static char *encode_block_structure_desc(char *p, struct block_structure *blocks)
3198 {
3199     int i, currrun = 0;
3200     int c = blocks->c, r = blocks->r, cr = c * r;
3201
3202     /*
3203      * Encode the block structure. We do this by encoding
3204      * the pattern of dividing lines: first we iterate
3205      * over the cr*(cr-1) internal vertical grid lines in
3206      * ordinary reading order, then over the cr*(cr-1)
3207      * internal horizontal ones in transposed reading
3208      * order.
3209      * 
3210      * We encode the number of non-lines between the
3211      * lines; _ means zero (two adjacent divisions), a
3212      * means 1, ..., y means 25, and z means 25 non-lines
3213      * _and no following line_ (so that za means 26, zb 27
3214      * etc).
3215      */
3216     for (i = 0; i <= 2*cr*(cr-1); i++) {
3217         int x, y, p0, p1, edge;
3218
3219         if (i == 2*cr*(cr-1)) {
3220             edge = TRUE;       /* terminating virtual edge */
3221         } else {
3222             if (i < cr*(cr-1)) {
3223                 y = i/(cr-1);
3224                 x = i%(cr-1);
3225                 p0 = y*cr+x;
3226                 p1 = y*cr+x+1;
3227             } else {
3228                 x = i/(cr-1) - cr;
3229                 y = i%(cr-1);
3230                 p0 = y*cr+x;
3231                 p1 = (y+1)*cr+x;
3232             }
3233             edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
3234         }
3235
3236         if (edge) {
3237             while (currrun > 25)
3238                 *p++ = 'z', currrun -= 25;
3239             if (currrun)
3240                 *p++ = 'a'-1 + currrun;
3241             else
3242                 *p++ = '_';
3243             currrun = 0;
3244         } else
3245             currrun++;
3246     }
3247     return p;
3248 }
3249
3250 static char *encode_grid(char *desc, digit *grid, int area)
3251 {
3252     int run, i;
3253     char *p = desc;
3254
3255     run = 0;
3256     for (i = 0; i <= area; i++) {
3257         int n = (i < area ? grid[i] : -1);
3258
3259         if (!n)
3260             run++;
3261         else {
3262             if (run) {
3263                 while (run > 0) {
3264                     int c = 'a' - 1 + run;
3265                     if (run > 26)
3266                         c = 'z';
3267                     *p++ = c;
3268                     run -= c - ('a' - 1);
3269                 }
3270             } else {
3271                 /*
3272                  * If there's a number in the very top left or
3273                  * bottom right, there's no point putting an
3274                  * unnecessary _ before or after it.
3275                  */
3276                 if (p > desc && n > 0)
3277                     *p++ = '_';
3278             }
3279             if (n > 0)
3280                 p += sprintf(p, "%d", n);
3281             run = 0;
3282         }
3283     }
3284     return p;
3285 }
3286
3287 /*
3288  * Conservatively stimate the number of characters required for
3289  * encoding a grid of a certain area.
3290  */
3291 static int grid_encode_space (int area)
3292 {
3293     int t, count;
3294     for (count = 1, t = area; t > 26; t -= 26)
3295         count++;
3296     return count * area;
3297 }
3298
3299 /*
3300  * Conservatively stimate the number of characters required for
3301  * encoding a given blocks structure.
3302  */
3303 static int blocks_encode_space(struct block_structure *blocks)
3304 {
3305     int cr = blocks->c * blocks->r, area = cr * cr;
3306     return grid_encode_space(area);
3307 }
3308
3309 static char *encode_puzzle_desc(const game_params *params, digit *grid,
3310                                 struct block_structure *blocks,
3311                                 digit *kgrid,
3312                                 struct block_structure *kblocks)
3313 {
3314     int c = params->c, r = params->r, cr = c*r;
3315     int area = cr*cr;
3316     char *p, *desc;
3317     int space;
3318
3319     space = grid_encode_space(area) + 1;
3320     if (r == 1)
3321         space += blocks_encode_space(blocks) + 1;
3322     if (params->killer) {
3323         space += blocks_encode_space(kblocks) + 1;
3324         space += grid_encode_space(area) + 1;
3325     }
3326     desc = snewn(space, char);
3327     p = encode_grid(desc, grid, area);
3328
3329     if (r == 1) {
3330         *p++ = ',';
3331         p = encode_block_structure_desc(p, blocks);
3332     }
3333     if (params->killer) {
3334         *p++ = ',';
3335         p = encode_block_structure_desc(p, kblocks);
3336         *p++ = ',';
3337         p = encode_grid(p, kgrid, area);
3338     }
3339     assert(p - desc < space);
3340     *p++ = '\0';
3341     desc = sresize(desc, p - desc, char);
3342
3343     return desc;
3344 }
3345
3346 static void merge_blocks(struct block_structure *b, int n1, int n2)
3347 {
3348     int i;
3349     /* Move data towards the lower block number.  */
3350     if (n2 < n1) {
3351         int t = n2;
3352         n2 = n1;
3353         n1 = t;
3354     }
3355
3356     /* Merge n2 into n1, and move the last block into n2's position.  */
3357     for (i = 0; i < b->nr_squares[n2]; i++)
3358         b->whichblock[b->blocks[n2][i]] = n1;
3359     memcpy(b->blocks[n1] + b->nr_squares[n1], b->blocks[n2],
3360            b->nr_squares[n2] * sizeof **b->blocks);
3361     b->nr_squares[n1] += b->nr_squares[n2];
3362
3363     n1 = b->nr_blocks - 1;
3364     if (n2 != n1) {
3365         memcpy(b->blocks[n2], b->blocks[n1],
3366                b->nr_squares[n1] * sizeof **b->blocks);
3367         for (i = 0; i < b->nr_squares[n1]; i++)
3368             b->whichblock[b->blocks[n1][i]] = n2;
3369         b->nr_squares[n2] = b->nr_squares[n1];
3370     }
3371     b->nr_blocks = n1;
3372 }
3373
3374 static int merge_some_cages(struct block_structure *b, int cr, int area,
3375                              digit *grid, random_state *rs)
3376 {
3377     /*
3378      * Make a list of all the pairs of adjacent blocks.
3379      */
3380     int i, j, k;
3381     struct pair {
3382         int b1, b2;
3383     } *pairs;
3384     int npairs;
3385
3386     pairs = snewn(b->nr_blocks * b->nr_blocks, struct pair);
3387     npairs = 0;
3388
3389     for (i = 0; i < b->nr_blocks; i++) {
3390         for (j = i+1; j < b->nr_blocks; j++) {
3391
3392             /*
3393              * Rule the merger out of consideration if it's
3394              * obviously not viable.
3395              */
3396             if (b->nr_squares[i] + b->nr_squares[j] > b->max_nr_squares)
3397                 continue;              /* we couldn't merge these anyway */
3398
3399             /*
3400              * See if these two blocks have a pair of squares
3401              * adjacent to each other.
3402              */
3403             for (k = 0; k < b->nr_squares[i]; k++) {
3404                 int xy = b->blocks[i][k];
3405                 int y = xy / cr, x = xy % cr;
3406                 if ((y   > 0  && b->whichblock[xy - cr] == j) ||
3407                     (y+1 < cr && b->whichblock[xy + cr] == j) ||
3408                     (x   > 0  && b->whichblock[xy -  1] == j) ||
3409                     (x+1 < cr && b->whichblock[xy +  1] == j)) {
3410                     /*
3411                      * Yes! Add this pair to our list.
3412                      */
3413                     pairs[npairs].b1 = i;
3414                     pairs[npairs].b2 = j;
3415                     break;
3416                 }
3417             }
3418         }
3419     }
3420
3421     /*
3422      * Now go through that list in random order until we find a pair
3423      * of blocks we can merge.
3424      */
3425     while (npairs > 0) {
3426         int n1, n2;
3427         unsigned int digits_found;
3428
3429         /*
3430          * Pick a random pair, and remove it from the list.
3431          */
3432         i = random_upto(rs, npairs);
3433         n1 = pairs[i].b1;
3434         n2 = pairs[i].b2;
3435         if (i != npairs-1)
3436             pairs[i] = pairs[npairs-1];
3437         npairs--;
3438
3439         /* Guarantee that the merged cage would still be a region.  */
3440         digits_found = 0;
3441         for (i = 0; i < b->nr_squares[n1]; i++)
3442             digits_found |= 1 << grid[b->blocks[n1][i]];
3443         for (i = 0; i < b->nr_squares[n2]; i++)
3444             if (digits_found & (1 << grid[b->blocks[n2][i]]))
3445                 break;
3446         if (i != b->nr_squares[n2])
3447             continue;
3448
3449         /*
3450          * Got one! Do the merge.
3451          */
3452         merge_blocks(b, n1, n2);
3453         sfree(pairs);
3454         return TRUE;
3455     }
3456
3457     sfree(pairs);
3458     return FALSE;
3459 }
3460
3461 static void compute_kclues(struct block_structure *cages, digit *kclues,
3462                            digit *grid, int area)
3463 {
3464     int i;
3465     memset(kclues, 0, area * sizeof *kclues);
3466     for (i = 0; i < cages->nr_blocks; i++) {
3467         int j, sum = 0;
3468         for (j = 0; j < area; j++)
3469             if (cages->whichblock[j] == i)
3470                 sum += grid[j];
3471         for (j = 0; j < area; j++)
3472             if (cages->whichblock[j] == i)
3473                 break;
3474         assert (j != area);
3475         kclues[j] = sum;
3476     }
3477 }
3478
3479 static struct block_structure *gen_killer_cages(int cr, random_state *rs,
3480                                                 int remove_singletons)
3481 {
3482     int nr;
3483     int x, y, area = cr * cr;
3484     int n_singletons = 0;
3485     struct block_structure *b = alloc_block_structure (1, cr, area, cr, area);
3486
3487     for (x = 0; x < area; x++)
3488         b->whichblock[x] = -1;
3489     nr = 0;
3490     for (y = 0; y < cr; y++)
3491         for (x = 0; x < cr; x++) {
3492             int rnd;
3493             int xy = y*cr+x;
3494             if (b->whichblock[xy] != -1)
3495                 continue;
3496             b->whichblock[xy] = nr;
3497
3498             rnd = random_bits(rs, 4);
3499             if (xy + 1 < area && (rnd >= 4 || (!remove_singletons && rnd >= 1))) {
3500                 int xy2 = xy + 1;
3501                 if (x + 1 == cr || b->whichblock[xy2] != -1 ||
3502                     (xy + cr < area && random_bits(rs, 1) == 0))
3503                     xy2 = xy + cr;
3504                 if (xy2 >= area)
3505                     n_singletons++;
3506                 else
3507                     b->whichblock[xy2] = nr;
3508             } else
3509                 n_singletons++;
3510             nr++;
3511         }
3512
3513     b->nr_blocks = nr;
3514     make_blocks_from_whichblock(b);
3515
3516     for (x = y = 0; x < b->nr_blocks; x++)
3517         if (b->nr_squares[x] == 1)
3518             y++;
3519     assert(y == n_singletons);
3520
3521     if (n_singletons > 0 && remove_singletons) {
3522         int n;
3523         for (n = 0; n < b->nr_blocks;) {
3524             int xy, x, y, xy2, other;
3525             if (b->nr_squares[n] > 1) {
3526                 n++;
3527                 continue;
3528             }
3529             xy = b->blocks[n][0];
3530             x = xy % cr;
3531             y = xy / cr;
3532             if (xy + 1 == area)
3533                 xy2 = xy - 1;
3534             else if (x + 1 < cr && (y + 1 == cr || random_bits(rs, 1) == 0))
3535                 xy2 = xy + 1;
3536             else
3537                 xy2 = xy + cr;
3538             other = b->whichblock[xy2];
3539
3540             if (b->nr_squares[other] == 1)
3541                 n_singletons--;
3542             n_singletons--;
3543             merge_blocks(b, n, other);
3544             if (n < other)
3545                 n++;
3546         }
3547         assert(n_singletons == 0);
3548     }
3549     return b;
3550 }
3551
3552 static char *new_game_desc(const game_params *params, random_state *rs,
3553                            char **aux, int interactive)
3554 {
3555     int c = params->c, r = params->r, cr = c*r;
3556     int area = cr*cr;
3557     struct block_structure *blocks, *kblocks;
3558     digit *grid, *grid2, *kgrid;
3559     struct xy { int x, y; } *locs;
3560     int nlocs;
3561     char *desc;
3562     int coords[16], ncoords;
3563     int x, y, i, j;
3564     struct difficulty dlev;
3565
3566     precompute_sum_bits();
3567
3568     /*
3569      * Adjust the maximum difficulty level to be consistent with
3570      * the puzzle size: all 2x2 puzzles appear to be Trivial
3571      * (DIFF_BLOCK) so we cannot hold out for even a Basic
3572      * (DIFF_SIMPLE) one.
3573      */
3574     dlev.maxdiff = params->diff;
3575     dlev.maxkdiff = params->kdiff;
3576     if (c == 2 && r == 2)
3577         dlev.maxdiff = DIFF_BLOCK;
3578
3579     grid = snewn(area, digit);
3580     locs = snewn(area, struct xy);
3581     grid2 = snewn(area, digit);
3582
3583     blocks = alloc_block_structure (c, r, area, cr, cr);
3584
3585     kblocks = NULL;
3586     kgrid = (params->killer) ? snewn(area, digit) : NULL;
3587
3588 #ifdef STANDALONE_SOLVER
3589     assert(!"This should never happen, so we don't need to create blocknames");
3590 #endif
3591
3592     /*
3593      * Loop until we get a grid of the required difficulty. This is
3594      * nasty, but it seems to be unpleasantly hard to generate
3595      * difficult grids otherwise.
3596      */
3597     while (1) {
3598         /*
3599          * Generate a random solved state, starting by
3600          * constructing the block structure.
3601          */
3602         if (r == 1) {                  /* jigsaw mode */
3603             int *dsf = divvy_rectangle(cr, cr, cr, rs);
3604
3605             dsf_to_blocks (dsf, blocks, cr, cr);
3606
3607             sfree(dsf);
3608         } else {                       /* basic Sudoku mode */
3609             for (y = 0; y < cr; y++)
3610                 for (x = 0; x < cr; x++)
3611                     blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
3612         }
3613         make_blocks_from_whichblock(blocks);
3614
3615         if (params->killer) {
3616             if (kblocks) free_block_structure(kblocks);
3617             kblocks = gen_killer_cages(cr, rs, params->kdiff > DIFF_KSINGLE);
3618         }
3619
3620         if (!gridgen(cr, blocks, kblocks, params->xtype, grid, rs, area*area))
3621             continue;
3622         assert(check_valid(cr, blocks, kblocks, params->xtype, grid));
3623
3624         /*
3625          * Save the solved grid in aux.
3626          */
3627         {
3628             /*
3629              * We might already have written *aux the last time we
3630              * went round this loop, in which case we should free
3631              * the old aux before overwriting it with the new one.
3632              */
3633             if (*aux) {
3634                 sfree(*aux);
3635             }
3636
3637             *aux = encode_solve_move(cr, grid);
3638         }
3639
3640         /*
3641          * Now we have a solved grid. For normal puzzles, we start removing
3642          * things from it while preserving solubility.  Killer puzzles are
3643          * different: we just pass the empty grid to the solver, and use
3644          * the puzzle if it comes back solved.
3645          */
3646
3647         if (params->killer) {
3648             struct block_structure *good_cages = NULL;
3649             struct block_structure *last_cages = NULL;
3650             int ntries = 0;
3651
3652             memcpy(grid2, grid, area);
3653
3654             for (;;) {
3655                 compute_kclues(kblocks, kgrid, grid2, area);
3656
3657                 memset(grid, 0, area * sizeof *grid);
3658                 solver(cr, blocks, kblocks, params->xtype, grid, kgrid, &dlev);
3659                 if (dlev.diff == dlev.maxdiff && dlev.kdiff == dlev.maxkdiff) {
3660                     /*
3661                      * We have one that matches our difficulty.  Store it for
3662                      * later, but keep going.
3663                      */
3664                     if (good_cages)
3665                         free_block_structure(good_cages);
3666                     ntries = 0;
3667                     good_cages = dup_block_structure(kblocks);
3668                     if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3669                         break;
3670                 } else if (dlev.diff > dlev.maxdiff || dlev.kdiff > dlev.maxkdiff) {
3671                     /*
3672                      * Give up after too many tries and either use the good one we
3673                      * found, or generate a new grid.
3674                      */
3675                     if (++ntries > 50)
3676                         break;
3677                     /*
3678                      * The difficulty level got too high.  If we have a good
3679                      * one, use it, otherwise go back to the last one that
3680                      * was at a lower difficulty and restart the process from
3681                      * there.
3682                      */
3683                     if (good_cages != NULL) {
3684                         free_block_structure(kblocks);
3685                         kblocks = dup_block_structure(good_cages);
3686                         if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3687                             break;
3688                     } else {
3689                         if (last_cages == NULL)
3690                             break;
3691                         free_block_structure(kblocks);
3692                         kblocks = last_cages;
3693                         last_cages = NULL;
3694                     }
3695                 } else {
3696                     if (last_cages)
3697                         free_block_structure(last_cages);
3698                     last_cages = dup_block_structure(kblocks);
3699                     if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3700                         break;
3701                 }
3702             }
3703             if (last_cages)
3704                 free_block_structure(last_cages);
3705             if (good_cages != NULL) {
3706                 free_block_structure(kblocks);
3707                 kblocks = good_cages;
3708                 compute_kclues(kblocks, kgrid, grid2, area);
3709                 memset(grid, 0, area * sizeof *grid);
3710                 break;
3711             }
3712             continue;
3713         }
3714
3715         /*
3716          * Find the set of equivalence classes of squares permitted
3717          * by the selected symmetry. We do this by enumerating all
3718          * the grid squares which have no symmetric companion
3719          * sorting lower than themselves.
3720          */
3721         nlocs = 0;
3722         for (y = 0; y < cr; y++)
3723             for (x = 0; x < cr; x++) {
3724                 int i = y*cr+x;
3725                 int j;
3726
3727                 ncoords = symmetries(params, x, y, coords, params->symm);
3728                 for (j = 0; j < ncoords; j++)
3729                     if (coords[2*j+1]*cr+coords[2*j] < i)
3730                         break;
3731                 if (j == ncoords) {
3732                     locs[nlocs].x = x;
3733                     locs[nlocs].y = y;
3734                     nlocs++;
3735                 }
3736             }
3737
3738         /*
3739          * Now shuffle that list.
3740          */
3741         shuffle(locs, nlocs, sizeof(*locs), rs);
3742
3743         /*
3744          * Now loop over the shuffled list and, for each element,
3745          * see whether removing that element (and its reflections)
3746          * from the grid will still leave the grid soluble.
3747          */
3748         for (i = 0; i < nlocs; i++) {
3749             x = locs[i].x;
3750             y = locs[i].y;
3751
3752             memcpy(grid2, grid, area);
3753             ncoords = symmetries(params, x, y, coords, params->symm);
3754             for (j = 0; j < ncoords; j++)
3755                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
3756
3757             solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3758             if (dlev.diff <= dlev.maxdiff &&
3759                 (!params->killer || dlev.kdiff <= dlev.maxkdiff)) {
3760                 for (j = 0; j < ncoords; j++)
3761                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
3762             }
3763         }
3764
3765         memcpy(grid2, grid, area);
3766
3767         solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3768         if (dlev.diff == dlev.maxdiff &&
3769             (!params->killer || dlev.kdiff == dlev.maxkdiff))
3770             break;                     /* found one! */
3771     }
3772
3773     sfree(grid2);
3774     sfree(locs);
3775
3776     /*
3777      * Now we have the grid as it will be presented to the user.
3778      * Encode it in a game desc.
3779      */
3780     desc = encode_puzzle_desc(params, grid, blocks, kgrid, kblocks);
3781
3782     sfree(grid);
3783     free_block_structure(blocks);
3784     if (params->killer) {
3785         free_block_structure(kblocks);
3786         sfree(kgrid);
3787     }
3788
3789     return desc;
3790 }
3791
3792 static const char *spec_to_grid(const char *desc, digit *grid, int area)
3793 {
3794     int i = 0;
3795     while (*desc && *desc != ',') {
3796         int n = *desc++;
3797         if (n >= 'a' && n <= 'z') {
3798             int run = n - 'a' + 1;
3799             assert(i + run <= area);
3800             while (run-- > 0)
3801                 grid[i++] = 0;
3802         } else if (n == '_') {
3803             /* do nothing */;
3804         } else if (n > '0' && n <= '9') {
3805             assert(i < area);
3806             grid[i++] = atoi(desc-1);
3807             while (*desc >= '0' && *desc <= '9')
3808                 desc++;
3809         } else {
3810             assert(!"We can't get here");
3811         }
3812     }
3813     assert(i == area);
3814     return desc;
3815 }
3816
3817 /*
3818  * Create a DSF from a spec found in *pdesc. Update this to point past the
3819  * end of the block spec, and return an error string or NULL if everything
3820  * is OK. The DSF is stored in *PDSF.
3821  */
3822 static char *spec_to_dsf(const char **pdesc, int **pdsf, int cr, int area)
3823 {
3824     const char *desc = *pdesc;
3825     int pos = 0;
3826     int *dsf;
3827
3828     *pdsf = dsf = snew_dsf(area);
3829
3830     while (*desc && *desc != ',') {
3831         int c, adv;
3832
3833         if (*desc == '_')
3834             c = 0;
3835         else if (*desc >= 'a' && *desc <= 'z')
3836             c = *desc - 'a' + 1;
3837         else {
3838             sfree(dsf);
3839             return "Invalid character in game description";
3840         }
3841         desc++;
3842
3843         adv = (c != 26);               /* 'z' is a special case */
3844
3845         while (c-- > 0) {
3846             int p0, p1;
3847
3848             /*
3849              * Non-edge; merge the two dsf classes on either
3850              * side of it.
3851              */
3852             if (pos >= 2*cr*(cr-1)) {
3853                 sfree(dsf);
3854                 return "Too much data in block structure specification";
3855             }
3856
3857             if (pos < cr*(cr-1)) {
3858                 int y = pos/(cr-1);
3859                 int x = pos%(cr-1);
3860                 p0 = y*cr+x;
3861                 p1 = y*cr+x+1;
3862             } else {
3863                 int x = pos/(cr-1) - cr;
3864                 int y = pos%(cr-1);
3865                 p0 = y*cr+x;
3866                 p1 = (y+1)*cr+x;
3867             }
3868             dsf_merge(dsf, p0, p1);
3869
3870             pos++;
3871         }
3872         if (adv)
3873             pos++;
3874     }
3875     *pdesc = desc;
3876
3877     /*
3878      * When desc is exhausted, we expect to have gone exactly
3879      * one space _past_ the end of the grid, due to the dummy
3880      * edge at the end.
3881      */
3882     if (pos != 2*cr*(cr-1)+1) {
3883         sfree(dsf);
3884         return "Not enough data in block structure specification";
3885     }
3886
3887     return NULL;
3888 }
3889
3890 static char *validate_grid_desc(const char **pdesc, int range, int area)
3891 {
3892     const char *desc = *pdesc;
3893     int squares = 0;
3894     while (*desc && *desc != ',') {
3895         int n = *desc++;
3896         if (n >= 'a' && n <= 'z') {
3897             squares += n - 'a' + 1;
3898         } else if (n == '_') {
3899             /* do nothing */;
3900         } else if (n > '0' && n <= '9') {
3901             int val = atoi(desc-1);
3902             if (val < 1 || val > range)
3903                 return "Out-of-range number in game description";
3904             squares++;
3905             while (*desc >= '0' && *desc <= '9')
3906                 desc++;
3907         } else
3908             return "Invalid character in game description";
3909     }
3910
3911     if (squares < area)
3912         return "Not enough data to fill grid";
3913
3914     if (squares > area)
3915         return "Too much data to fit in grid";
3916     *pdesc = desc;
3917     return NULL;
3918 }
3919
3920 static char *validate_block_desc(const char **pdesc, int cr, int area,
3921                                  int min_nr_blocks, int max_nr_blocks,
3922                                  int min_nr_squares, int max_nr_squares)
3923 {
3924     char *err;
3925     int *dsf;
3926
3927     err = spec_to_dsf(pdesc, &dsf, cr, area);
3928     if (err) {
3929         return err;
3930     }
3931
3932     if (min_nr_squares == max_nr_squares) {
3933         assert(min_nr_blocks == max_nr_blocks);
3934         assert(min_nr_blocks * min_nr_squares == area);
3935     }
3936     /*
3937      * Now we've got our dsf. Verify that it matches
3938      * expectations.
3939      */
3940     {
3941         int *canons, *counts;
3942         int i, j, c, ncanons = 0;
3943
3944         canons = snewn(max_nr_blocks, int);
3945         counts = snewn(max_nr_blocks, int);
3946
3947         for (i = 0; i < area; i++) {
3948             j = dsf_canonify(dsf, i);
3949
3950             for (c = 0; c < ncanons; c++)
3951                 if (canons[c] == j) {
3952                     counts[c]++;
3953                     if (counts[c] > max_nr_squares) {
3954                         sfree(dsf);
3955                         sfree(canons);
3956                         sfree(counts);
3957                         return "A jigsaw block is too big";
3958                     }
3959                     break;
3960                 }
3961
3962             if (c == ncanons) {
3963                 if (ncanons >= max_nr_blocks) {
3964                     sfree(dsf);
3965                     sfree(canons);
3966                     sfree(counts);
3967                     return "Too many distinct jigsaw blocks";
3968                 }
3969                 canons[ncanons] = j;
3970                 counts[ncanons] = 1;
3971                 ncanons++;
3972             }
3973         }
3974
3975         if (ncanons < min_nr_blocks) {
3976             sfree(dsf);
3977             sfree(canons);
3978             sfree(counts);
3979             return "Not enough distinct jigsaw blocks";
3980         }
3981         for (c = 0; c < ncanons; c++) {
3982             if (counts[c] < min_nr_squares) {
3983                 sfree(dsf);
3984                 sfree(canons);
3985                 sfree(counts);
3986                 return "A jigsaw block is too small";
3987             }
3988         }
3989         sfree(canons);
3990         sfree(counts);
3991     }
3992
3993     sfree(dsf);
3994     return NULL;
3995 }
3996
3997 static char *validate_desc(const game_params *params, const char *desc)
3998 {
3999     int cr = params->c * params->r, area = cr*cr;
4000     char *err;
4001
4002     err = validate_grid_desc(&desc, cr, area);
4003     if (err)
4004         return err;
4005
4006     if (params->r == 1) {
4007         /*
4008          * Now we expect a suffix giving the jigsaw block
4009          * structure. Parse it and validate that it divides the
4010          * grid into the right number of regions which are the
4011          * right size.
4012          */
4013         if (*desc != ',')
4014             return "Expected jigsaw block structure in game description";
4015         desc++;
4016         err = validate_block_desc(&desc, cr, area, cr, cr, cr, cr);
4017         if (err)
4018             return err;
4019
4020     }
4021     if (params->killer) {
4022         if (*desc != ',')
4023             return "Expected killer block structure in game description";
4024         desc++;
4025         err = validate_block_desc(&desc, cr, area, cr, area, 2, cr);
4026         if (err)
4027             return err;
4028         if (*desc != ',')
4029             return "Expected killer clue grid in game description";
4030         desc++;
4031         err = validate_grid_desc(&desc, cr * area, area);
4032         if (err)
4033             return err;
4034     }
4035     if (*desc)
4036         return "Unexpected data at end of game description";
4037
4038     return NULL;
4039 }
4040
4041 static game_state *new_game(midend *me, const game_params *params,
4042                             const char *desc)
4043 {
4044     game_state *state = snew(game_state);
4045     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
4046     int i;
4047
4048     precompute_sum_bits();
4049
4050     state->cr = cr;
4051     state->xtype = params->xtype;
4052     state->killer = params->killer;
4053
4054     state->grid = snewn(area, digit);
4055     state->pencil = snewn(area * cr, unsigned char);
4056     memset(state->pencil, 0, area * cr);
4057     state->immutable = snewn(area, unsigned char);
4058     memset(state->immutable, FALSE, area);
4059
4060     state->blocks = alloc_block_structure (c, r, area, cr, cr);
4061
4062     if (params->killer) {
4063         state->kblocks = alloc_block_structure (c, r, area, cr, area);
4064         state->kgrid = snewn(area, digit);
4065     } else {
4066         state->kblocks = NULL;
4067         state->kgrid = NULL;
4068     }
4069     state->completed = state->cheated = FALSE;
4070
4071     desc = spec_to_grid(desc, state->grid, area);
4072     for (i = 0; i < area; i++)
4073         if (state->grid[i] != 0)
4074             state->immutable[i] = TRUE;
4075
4076     if (r == 1) {
4077         char *err;
4078         int *dsf;
4079         assert(*desc == ',');
4080         desc++;
4081         err = spec_to_dsf(&desc, &dsf, cr, area);
4082         assert(err == NULL);
4083         dsf_to_blocks(dsf, state->blocks, cr, cr);
4084         sfree(dsf);
4085     } else {
4086         int x, y;
4087
4088         for (y = 0; y < cr; y++)
4089             for (x = 0; x < cr; x++)
4090                 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
4091     }
4092     make_blocks_from_whichblock(state->blocks);
4093
4094     if (params->killer) {
4095         char *err;
4096         int *dsf;
4097         assert(*desc == ',');
4098         desc++;
4099         err = spec_to_dsf(&desc, &dsf, cr, area);
4100         assert(err == NULL);
4101         dsf_to_blocks(dsf, state->kblocks, cr, area);
4102         sfree(dsf);
4103         make_blocks_from_whichblock(state->kblocks);
4104
4105         assert(*desc == ',');
4106         desc++;
4107         desc = spec_to_grid(desc, state->kgrid, area);
4108     }
4109     assert(!*desc);
4110
4111 #ifdef STANDALONE_SOLVER
4112     /*
4113      * Set up the block names for solver diagnostic output.
4114      */
4115     {
4116         char *p = (char *)(state->blocks->blocknames + cr);
4117
4118         if (r == 1) {
4119             for (i = 0; i < area; i++) {
4120                 int j = state->blocks->whichblock[i];
4121                 if (!state->blocks->blocknames[j]) {
4122                     state->blocks->blocknames[j] = p;
4123                     p += 1 + sprintf(p, "starting at (%d,%d)",
4124                                      1 + i%cr, 1 + i/cr);
4125                 }
4126             }
4127         } else {
4128             int bx, by;
4129             for (by = 0; by < r; by++)
4130                 for (bx = 0; bx < c; bx++) {
4131                     state->blocks->blocknames[by*c+bx] = p;
4132                     p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
4133                 }
4134         }
4135         assert(p - (char *)state->blocks->blocknames < (int)(cr*(sizeof(char *)+80)));
4136         for (i = 0; i < cr; i++)
4137             assert(state->blocks->blocknames[i]);
4138     }
4139 #endif
4140
4141     return state;
4142 }
4143
4144 static game_state *dup_game(const game_state *state)
4145 {
4146     game_state *ret = snew(game_state);
4147     int cr = state->cr, area = cr * cr;
4148
4149     ret->cr = state->cr;
4150     ret->xtype = state->xtype;
4151     ret->killer = state->killer;
4152
4153     ret->blocks = state->blocks;
4154     ret->blocks->refcount++;
4155
4156     ret->kblocks = state->kblocks;
4157     if (ret->kblocks)
4158         ret->kblocks->refcount++;
4159
4160     ret->grid = snewn(area, digit);
4161     memcpy(ret->grid, state->grid, area);
4162
4163     if (state->killer) {
4164         ret->kgrid = snewn(area, digit);
4165         memcpy(ret->kgrid, state->kgrid, area);
4166     } else
4167         ret->kgrid = NULL;
4168
4169     ret->pencil = snewn(area * cr, unsigned char);
4170     memcpy(ret->pencil, state->pencil, area * cr);
4171
4172     ret->immutable = snewn(area, unsigned char);
4173     memcpy(ret->immutable, state->immutable, area);
4174
4175     ret->completed = state->completed;
4176     ret->cheated = state->cheated;
4177
4178     return ret;
4179 }
4180
4181 static void free_game(game_state *state)
4182 {
4183     free_block_structure(state->blocks);
4184     if (state->kblocks)
4185         free_block_structure(state->kblocks);
4186
4187     sfree(state->immutable);
4188     sfree(state->pencil);
4189     sfree(state->grid);
4190     if (state->kgrid) sfree(state->kgrid);
4191     sfree(state);
4192 }
4193
4194 static char *solve_game(const game_state *state, const game_state *currstate,
4195                         const char *ai, char **error)
4196 {
4197     int cr = state->cr;
4198     char *ret;
4199     digit *grid;
4200     struct difficulty dlev;
4201
4202     /*
4203      * If we already have the solution in ai, save ourselves some
4204      * time.
4205      */
4206     if (ai)
4207         return dupstr(ai);
4208
4209     grid = snewn(cr*cr, digit);
4210     memcpy(grid, state->grid, cr*cr);
4211     dlev.maxdiff = DIFF_RECURSIVE;
4212     dlev.maxkdiff = DIFF_KINTERSECT;
4213     solver(cr, state->blocks, state->kblocks, state->xtype, grid,
4214            state->kgrid, &dlev);
4215
4216     *error = NULL;
4217
4218     if (dlev.diff == DIFF_IMPOSSIBLE)
4219         *error = "No solution exists for this puzzle";
4220     else if (dlev.diff == DIFF_AMBIGUOUS)
4221         *error = "Multiple solutions exist for this puzzle";
4222
4223     if (*error) {
4224         sfree(grid);
4225         return NULL;
4226     }
4227
4228     ret = encode_solve_move(cr, grid);
4229
4230     sfree(grid);
4231
4232     return ret;
4233 }
4234
4235 static char *grid_text_format(int cr, struct block_structure *blocks,
4236                               int xtype, digit *grid)
4237 {
4238     int vmod, hmod;
4239     int x, y;
4240     int totallen, linelen, nlines;
4241     char *ret, *p, ch;
4242
4243     /*
4244      * For non-jigsaw Sudoku, we format in the way we always have,
4245      * by having the digits unevenly spaced so that the dividing
4246      * lines can fit in:
4247      *
4248      * . . | . .
4249      * . . | . .
4250      * ----+----
4251      * . . | . .
4252      * . . | . .
4253      *
4254      * For jigsaw puzzles, however, we must leave space between
4255      * _all_ pairs of digits for an optional dividing line, so we
4256      * have to move to the rather ugly
4257      * 
4258      * .   .   .   .
4259      * ------+------
4260      * .   . | .   .
4261      *       +---+  
4262      * .   . | . | .
4263      * ------+   |  
4264      * .   .   . | .
4265      * 
4266      * We deal with both cases using the same formatting code; we
4267      * simply invent a vmod value such that there's a vertical
4268      * dividing line before column i iff i is divisible by vmod
4269      * (so it's r in the first case and 1 in the second), and hmod
4270      * likewise for horizontal dividing lines.
4271      */
4272
4273     if (blocks->r != 1) {
4274         vmod = blocks->r;
4275         hmod = blocks->c;
4276     } else {
4277         vmod = hmod = 1;
4278     }
4279
4280     /*
4281      * Line length: we have cr digits, each with a space after it,
4282      * and (cr-1)/vmod dividing lines, each with a space after it.
4283      * The final space is replaced by a newline, but that doesn't
4284      * affect the length.
4285      */
4286     linelen = 2*(cr + (cr-1)/vmod);
4287
4288     /*
4289      * Number of lines: we have cr rows of digits, and (cr-1)/hmod
4290      * dividing rows.
4291      */
4292     nlines = cr + (cr-1)/hmod;
4293
4294     /*
4295      * Allocate the space.
4296      */
4297     totallen = linelen * nlines;
4298     ret = snewn(totallen+1, char);     /* leave room for terminating NUL */
4299
4300     /*
4301      * Write the text.
4302      */
4303     p = ret;
4304     for (y = 0; y < cr; y++) {
4305         /*
4306          * Row of digits.
4307          */
4308         for (x = 0; x < cr; x++) {
4309             /*
4310              * Digit.
4311              */
4312             digit d = grid[y*cr+x];
4313
4314             if (d == 0) {
4315                 /*
4316                  * Empty space: we usually write a dot, but we'll
4317                  * highlight spaces on the X-diagonals (in X mode)
4318                  * by using underscores instead.
4319                  */
4320                 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
4321                     ch = '_';
4322                 else
4323                     ch = '.';
4324             } else if (d <= 9) {
4325                 ch = '0' + d;
4326             } else {
4327                 ch = 'a' + d-10;
4328             }
4329
4330             *p++ = ch;
4331             if (x == cr-1) {
4332                 *p++ = '\n';
4333                 continue;
4334             }
4335             *p++ = ' ';
4336
4337             if ((x+1) % vmod)
4338                 continue;
4339
4340             /*
4341              * Optional dividing line.
4342              */
4343             if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
4344                 ch = '|';
4345             else
4346                 ch = ' ';
4347             *p++ = ch;
4348             *p++ = ' ';
4349         }
4350         if (y == cr-1 || (y+1) % hmod)
4351             continue;
4352
4353         /*
4354          * Dividing row.
4355          */
4356         for (x = 0; x < cr; x++) {
4357             int dwid;
4358             int tl, tr, bl, br;
4359
4360             /*
4361              * Division between two squares. This varies
4362              * complicatedly in length.
4363              */
4364             dwid = 2;                  /* digit and its following space */
4365             if (x == cr-1)
4366                 dwid--;                /* no following space at end of line */
4367             if (x > 0 && x % vmod == 0)
4368                 dwid++;                /* preceding space after a divider */
4369
4370             if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
4371                 ch = '-';
4372             else
4373                 ch = ' ';
4374
4375             while (dwid-- > 0)
4376                 *p++ = ch;
4377
4378             if (x == cr-1) {
4379                 *p++ = '\n';
4380                 break;
4381             }
4382
4383             if ((x+1) % vmod)
4384                 continue;
4385
4386             /*
4387              * Corner square. This is:
4388              *  - a space if all four surrounding squares are in
4389              *    the same block
4390              *  - a vertical line if the two left ones are in one
4391              *    block and the two right in another
4392              *  - a horizontal line if the two top ones are in one
4393              *    block and the two bottom in another
4394              *  - a plus sign in all other cases. (If we had a
4395              *    richer character set available we could break
4396              *    this case up further by doing fun things with
4397              *    line-drawing T-pieces.)
4398              */
4399             tl = blocks->whichblock[y*cr+x];
4400             tr = blocks->whichblock[y*cr+x+1];
4401             bl = blocks->whichblock[(y+1)*cr+x];
4402             br = blocks->whichblock[(y+1)*cr+x+1];
4403
4404             if (tl == tr && tr == bl && bl == br)
4405                 ch = ' ';
4406             else if (tl == bl && tr == br)
4407                 ch = '|';
4408             else if (tl == tr && bl == br)
4409                 ch = '-';
4410             else
4411                 ch = '+';
4412
4413             *p++ = ch;
4414         }
4415     }
4416
4417     assert(p - ret == totallen);
4418     *p = '\0';
4419     return ret;
4420 }
4421
4422 static int game_can_format_as_text_now(const game_params *params)
4423 {
4424     /*
4425      * Formatting Killer puzzles as text is currently unsupported. I
4426      * can't think of any sensible way of doing it which doesn't
4427      * involve expanding the puzzle to such a large scale as to make
4428      * it unusable.
4429      */
4430     if (params->killer)
4431         return FALSE;
4432     return TRUE;
4433 }
4434
4435 static char *game_text_format(const game_state *state)
4436 {
4437     assert(!state->kblocks);
4438     return grid_text_format(state->cr, state->blocks, state->xtype,
4439                             state->grid);
4440 }
4441
4442 struct game_ui {
4443     /*
4444      * These are the coordinates of the currently highlighted
4445      * square on the grid, if hshow = 1.
4446      */
4447     int hx, hy;
4448     /*
4449      * This indicates whether the current highlight is a
4450      * pencil-mark one or a real one.
4451      */
4452     int hpencil;
4453     /*
4454      * This indicates whether or not we're showing the highlight
4455      * (used to be hx = hy = -1); important so that when we're
4456      * using the cursor keys it doesn't keep coming back at a
4457      * fixed position. When hshow = 1, pressing a valid number
4458      * or letter key or Space will enter that number or letter in the grid.
4459      */
4460     int hshow;
4461     /*
4462      * This indicates whether we're using the highlight as a cursor;
4463      * it means that it doesn't vanish on a keypress, and that it is
4464      * allowed on immutable squares.
4465      */
4466     int hcursor;
4467 };
4468
4469 static game_ui *new_ui(const game_state *state)
4470 {
4471     game_ui *ui = snew(game_ui);
4472
4473     ui->hx = ui->hy = 0;
4474     ui->hpencil = ui->hshow = ui->hcursor = 0;
4475
4476     return ui;
4477 }
4478
4479 static void free_ui(game_ui *ui)
4480 {
4481     sfree(ui);
4482 }
4483
4484 static char *encode_ui(const game_ui *ui)
4485 {
4486     return NULL;
4487 }
4488
4489 static void decode_ui(game_ui *ui, const char *encoding)
4490 {
4491 }
4492
4493 static void game_changed_state(game_ui *ui, const game_state *oldstate,
4494                                const game_state *newstate)
4495 {
4496     int cr = newstate->cr;
4497     /*
4498      * We prevent pencil-mode highlighting of a filled square, unless
4499      * we're using the cursor keys. So if the user has just filled in
4500      * a square which we had a pencil-mode highlight in (by Undo, or
4501      * by Redo, or by Solve), then we cancel the highlight.
4502      */
4503     if (ui->hshow && ui->hpencil && !ui->hcursor &&
4504         newstate->grid[ui->hy * cr + ui->hx] != 0) {
4505         ui->hshow = 0;
4506     }
4507 }
4508
4509 struct game_drawstate {
4510     int started;
4511     int cr, xtype;
4512     int tilesize;
4513     digit *grid;
4514     unsigned char *pencil;
4515     unsigned char *hl;
4516     /* This is scratch space used within a single call to game_redraw. */
4517     int nregions, *entered_items;
4518 };
4519
4520 static char *interpret_move(const game_state *state, game_ui *ui,
4521                             const game_drawstate *ds,
4522                             int x, int y, int button)
4523 {
4524     int cr = state->cr;
4525     int tx, ty;
4526     char buf[80];
4527
4528     button &= ~MOD_MASK;
4529
4530     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4531     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4532
4533     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
4534         if (button == LEFT_BUTTON) {
4535             if (state->immutable[ty*cr+tx]) {
4536                 ui->hshow = 0;
4537             } else if (tx == ui->hx && ty == ui->hy &&
4538                        ui->hshow && ui->hpencil == 0) {
4539                 ui->hshow = 0;
4540             } else {
4541                 ui->hx = tx;
4542                 ui->hy = ty;
4543                 ui->hshow = 1;
4544                 ui->hpencil = 0;
4545             }
4546             ui->hcursor = 0;
4547             return "";                 /* UI activity occurred */
4548         }
4549         if (button == RIGHT_BUTTON) {
4550             /*
4551              * Pencil-mode highlighting for non filled squares.
4552              */
4553             if (state->grid[ty*cr+tx] == 0) {
4554                 if (tx == ui->hx && ty == ui->hy &&
4555                     ui->hshow && ui->hpencil) {
4556                     ui->hshow = 0;
4557                 } else {
4558                     ui->hpencil = 1;
4559                     ui->hx = tx;
4560                     ui->hy = ty;
4561                     ui->hshow = 1;
4562                 }
4563             } else {
4564                 ui->hshow = 0;
4565             }
4566             ui->hcursor = 0;
4567             return "";                 /* UI activity occurred */
4568         }
4569     }
4570     if (IS_CURSOR_MOVE(button)) {
4571         move_cursor(button, &ui->hx, &ui->hy, cr, cr, 0);
4572         ui->hshow = ui->hcursor = 1;
4573         return "";
4574     }
4575     if (ui->hshow &&
4576         (button == CURSOR_SELECT)) {
4577         ui->hpencil = 1 - ui->hpencil;
4578         ui->hcursor = 1;
4579         return "";
4580     }
4581
4582     if (ui->hshow &&
4583         ((button >= '0' && button <= '9' && button - '0' <= cr) ||
4584          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
4585          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
4586          button == CURSOR_SELECT2 || button == '\b')) {
4587         int n = button - '0';
4588         if (button >= 'A' && button <= 'Z')
4589             n = button - 'A' + 10;
4590         if (button >= 'a' && button <= 'z')
4591             n = button - 'a' + 10;
4592         if (button == CURSOR_SELECT2 || button == '\b')
4593             n = 0;
4594
4595         /*
4596          * Can't overwrite this square. This can only happen here
4597          * if we're using the cursor keys.
4598          */
4599         if (state->immutable[ui->hy*cr+ui->hx])
4600             return NULL;
4601
4602         /*
4603          * Can't make pencil marks in a filled square. Again, this
4604          * can only become highlighted if we're using cursor keys.
4605          */
4606         if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
4607             return NULL;
4608
4609         sprintf(buf, "%c%d,%d,%d",
4610                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
4611
4612         if (!ui->hcursor) ui->hshow = 0;
4613
4614         return dupstr(buf);
4615     }
4616
4617     if (button == 'M' || button == 'm')
4618         return dupstr("M");
4619
4620     return NULL;
4621 }
4622
4623 static game_state *execute_move(const game_state *from, const char *move)
4624 {
4625     int cr = from->cr;
4626     game_state *ret;
4627     int x, y, n;
4628
4629     if (move[0] == 'S') {
4630         const char *p;
4631
4632         ret = dup_game(from);
4633         ret->completed = ret->cheated = TRUE;
4634
4635         p = move+1;
4636         for (n = 0; n < cr*cr; n++) {
4637             ret->grid[n] = atoi(p);
4638
4639             if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
4640                 free_game(ret);
4641                 return NULL;
4642             }
4643
4644             while (*p && isdigit((unsigned char)*p)) p++;
4645             if (*p == ',') p++;
4646         }
4647
4648         return ret;
4649     } else if ((move[0] == 'P' || move[0] == 'R') &&
4650         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
4651         x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
4652
4653         ret = dup_game(from);
4654         if (move[0] == 'P' && n > 0) {
4655             int index = (y*cr+x) * cr + (n-1);
4656             ret->pencil[index] = !ret->pencil[index];
4657         } else {
4658             ret->grid[y*cr+x] = n;
4659             memset(ret->pencil + (y*cr+x)*cr, 0, cr);
4660
4661             /*
4662              * We've made a real change to the grid. Check to see
4663              * if the game has been completed.
4664              */
4665             if (!ret->completed && check_valid(cr, ret->blocks, ret->kblocks,
4666                                                ret->xtype, ret->grid)) {
4667                 ret->completed = TRUE;
4668             }
4669         }
4670         return ret;
4671     } else if (move[0] == 'M') {
4672         /*
4673          * Fill in absolutely all pencil marks in unfilled squares,
4674          * for those who like to play by the rigorous approach of
4675          * starting off in that state and eliminating things.
4676          */
4677         ret = dup_game(from);
4678         for (y = 0; y < cr; y++) {
4679             for (x = 0; x < cr; x++) {
4680                 if (!ret->grid[y*cr+x]) {
4681                     memset(ret->pencil + (y*cr+x)*cr, 1, cr);
4682                 }
4683             }
4684         }
4685         return ret;
4686     } else
4687         return NULL;                   /* couldn't parse move string */
4688 }
4689
4690 /* ----------------------------------------------------------------------
4691  * Drawing routines.
4692  */
4693
4694 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
4695 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
4696
4697 static void game_compute_size(const game_params *params, int tilesize,
4698                               int *x, int *y)
4699 {
4700     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
4701     struct { int tilesize; } ads, *ds = &ads;
4702     ads.tilesize = tilesize;
4703
4704     *x = SIZE(params->c * params->r);
4705     *y = SIZE(params->c * params->r);
4706 }
4707
4708 static void game_set_size(drawing *dr, game_drawstate *ds,
4709                           const game_params *params, int tilesize)
4710 {
4711     ds->tilesize = tilesize;
4712 }
4713
4714 static float *game_colours(frontend *fe, int *ncolours)
4715 {
4716     float *ret = snewn(3 * NCOLOURS, float);
4717
4718     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
4719
4720     ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
4721     ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
4722     ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
4723
4724     ret[COL_GRID * 3 + 0] = 0.0F;
4725     ret[COL_GRID * 3 + 1] = 0.0F;
4726     ret[COL_GRID * 3 + 2] = 0.0F;
4727
4728     ret[COL_CLUE * 3 + 0] = 0.0F;
4729     ret[COL_CLUE * 3 + 1] = 0.0F;
4730     ret[COL_CLUE * 3 + 2] = 0.0F;
4731
4732     ret[COL_USER * 3 + 0] = 0.0F;
4733     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
4734     ret[COL_USER * 3 + 2] = 0.0F;
4735
4736     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
4737     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
4738     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
4739
4740     ret[COL_ERROR * 3 + 0] = 1.0F;
4741     ret[COL_ERROR * 3 + 1] = 0.0F;
4742     ret[COL_ERROR * 3 + 2] = 0.0F;
4743
4744     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4745     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4746     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
4747
4748     ret[COL_KILLER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4749     ret[COL_KILLER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4750     ret[COL_KILLER * 3 + 2] = 0.1F * ret[COL_BACKGROUND * 3 + 2];
4751
4752     *ncolours = NCOLOURS;
4753     return ret;
4754 }
4755
4756 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
4757 {
4758     struct game_drawstate *ds = snew(struct game_drawstate);
4759     int cr = state->cr;
4760
4761     ds->started = FALSE;
4762     ds->cr = cr;
4763     ds->xtype = state->xtype;
4764     ds->grid = snewn(cr*cr, digit);
4765     memset(ds->grid, cr+2, cr*cr);
4766     ds->pencil = snewn(cr*cr*cr, digit);
4767     memset(ds->pencil, 0, cr*cr*cr);
4768     ds->hl = snewn(cr*cr, unsigned char);
4769     memset(ds->hl, 0, cr*cr);
4770     /*
4771      * ds->entered_items needs one row of cr entries per entity in
4772      * which digits may not be duplicated. That's one for each row,
4773      * each column, each block, each diagonal, and each Killer cage.
4774      */
4775     ds->nregions = cr*3 + 2;
4776     if (state->kblocks)
4777         ds->nregions += state->kblocks->nr_blocks;
4778     ds->entered_items = snewn(cr * ds->nregions, int);
4779     ds->tilesize = 0;                  /* not decided yet */
4780     return ds;
4781 }
4782
4783 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
4784 {
4785     sfree(ds->hl);
4786     sfree(ds->pencil);
4787     sfree(ds->grid);
4788     sfree(ds->entered_items);
4789     sfree(ds);
4790 }
4791
4792 static void draw_number(drawing *dr, game_drawstate *ds,
4793                         const game_state *state, int x, int y, int hl)
4794 {
4795     int cr = state->cr;
4796     int tx, ty, tw, th;
4797     int cx, cy, cw, ch;
4798     int col_killer = (hl & 32 ? COL_ERROR : COL_KILLER);
4799     char str[20];
4800
4801     if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
4802         ds->hl[y*cr+x] == hl &&
4803         !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
4804         return;                        /* no change required */
4805
4806     tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
4807     ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
4808
4809     cx = tx;
4810     cy = ty;
4811     cw = tw = TILE_SIZE-1-2*GRIDEXTRA;
4812     ch = th = TILE_SIZE-1-2*GRIDEXTRA;
4813
4814     if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
4815         cx -= GRIDEXTRA, cw += GRIDEXTRA;
4816     if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
4817         cw += GRIDEXTRA;
4818     if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
4819         cy -= GRIDEXTRA, ch += GRIDEXTRA;
4820     if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
4821         ch += GRIDEXTRA;
4822
4823     clip(dr, cx, cy, cw, ch);
4824
4825     /* background needs erasing */
4826     draw_rect(dr, cx, cy, cw, ch,
4827               ((hl & 15) == 1 ? COL_HIGHLIGHT :
4828                (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
4829                COL_BACKGROUND));
4830
4831     /*
4832      * Draw the corners of thick lines in corner-adjacent squares,
4833      * which jut into this square by one pixel.
4834      */
4835     if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
4836         draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4837     if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
4838         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4839     if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
4840         draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4841     if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
4842         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4843
4844     /* pencil-mode highlight */
4845     if ((hl & 15) == 2) {
4846         int coords[6];
4847         coords[0] = cx;
4848         coords[1] = cy;
4849         coords[2] = cx+cw/2;
4850         coords[3] = cy;
4851         coords[4] = cx;
4852         coords[5] = cy+ch/2;
4853         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
4854     }
4855
4856     if (state->kblocks) {
4857         int t = GRIDEXTRA * 3;
4858         int kcx, kcy, kcw, kch;
4859         int kl, kt, kr, kb;
4860         int has_left = 0, has_right = 0, has_top = 0, has_bottom = 0;
4861
4862         /*
4863          * In non-jigsaw mode, the Killer cages are placed at a
4864          * fixed offset from the outer edge of the cell dividing
4865          * lines, so that they look right whether those lines are
4866          * thick or thin. In jigsaw mode, however, doing this will
4867          * sometimes cause the cage outlines in adjacent squares to
4868          * fail to match up with each other, so we must offset a
4869          * fixed amount from the _centre_ of the cell dividing
4870          * lines.
4871          */
4872         if (state->blocks->r == 1) {
4873             kcx = tx;
4874             kcy = ty;
4875             kcw = tw;
4876             kch = th;
4877         } else {
4878             kcx = cx;
4879             kcy = cy;
4880             kcw = cw;
4881             kch = ch;
4882         }
4883         kl = kcx - 1;
4884         kt = kcy - 1;
4885         kr = kcx + kcw;
4886         kb = kcy + kch;
4887
4888         /*
4889          * First, draw the lines dividing this area from neighbouring
4890          * different areas.
4891          */
4892         if (x == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x-1])
4893             has_left = 1, kl += t;
4894         if (x+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x+1])
4895             has_right = 1, kr -= t;
4896         if (y == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x])
4897             has_top = 1, kt += t;
4898         if (y+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x])
4899             has_bottom = 1, kb -= t;
4900         if (has_top)
4901             draw_line(dr, kl, kt, kr, kt, col_killer);
4902         if (has_bottom)
4903             draw_line(dr, kl, kb, kr, kb, col_killer);
4904         if (has_left)
4905             draw_line(dr, kl, kt, kl, kb, col_killer);
4906         if (has_right)
4907             draw_line(dr, kr, kt, kr, kb, col_killer);
4908         /*
4909          * Now, take care of the corners (just as for the normal borders).
4910          * We only need a corner if there wasn't a full edge.
4911          */
4912         if (x > 0 && y > 0 && !has_left && !has_top
4913             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x-1])
4914         {
4915             draw_line(dr, kl, kt + t, kl + t, kt + t, col_killer);
4916             draw_line(dr, kl + t, kt, kl + t, kt + t, col_killer);
4917         }
4918         if (x+1 < cr && y > 0 && !has_right && !has_top
4919             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x+1])
4920         {
4921             draw_line(dr, kcx + kcw - t, kt + t, kcx + kcw, kt + t, col_killer);
4922             draw_line(dr, kcx + kcw - t, kt, kcx + kcw - t, kt + t, col_killer);
4923         }
4924         if (x > 0 && y+1 < cr && !has_left && !has_bottom
4925             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x-1])
4926         {
4927             draw_line(dr, kl, kcy + kch - t, kl + t, kcy + kch - t, col_killer);
4928             draw_line(dr, kl + t, kcy + kch - t, kl + t, kcy + kch, col_killer);
4929         }
4930         if (x+1 < cr && y+1 < cr && !has_right && !has_bottom
4931             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x+1])
4932         {
4933             draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw - t, kcy + kch, col_killer);
4934             draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw, kcy + kch - t, col_killer);
4935         }
4936
4937     }
4938
4939     if (state->killer && state->kgrid[y*cr+x]) {
4940         sprintf (str, "%d", state->kgrid[y*cr+x]);
4941         draw_text(dr, tx + GRIDEXTRA * 4, ty + GRIDEXTRA * 4 + TILE_SIZE/4,
4942                   FONT_VARIABLE, TILE_SIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
4943                   col_killer, str);
4944     }
4945
4946     /* new number needs drawing? */
4947     if (state->grid[y*cr+x]) {
4948         str[1] = '\0';
4949         str[0] = state->grid[y*cr+x] + '0';
4950         if (str[0] > '9')
4951             str[0] += 'a' - ('9'+1);
4952         draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
4953                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
4954                   state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
4955     } else {
4956         int i, j, npencil;
4957         int pl, pr, pt, pb;
4958         float bestsize;
4959         int pw, ph, minph, pbest, fontsize;
4960
4961         /* Count the pencil marks required. */
4962         for (i = npencil = 0; i < cr; i++)
4963             if (state->pencil[(y*cr+x)*cr+i])
4964                 npencil++;
4965         if (npencil) {
4966
4967             minph = 2;
4968
4969             /*
4970              * Determine the bounding rectangle within which we're going
4971              * to put the pencil marks.
4972              */
4973             /* Start with the whole square */
4974             pl = tx + GRIDEXTRA;
4975             pr = pl + TILE_SIZE - GRIDEXTRA;
4976             pt = ty + GRIDEXTRA;
4977             pb = pt + TILE_SIZE - GRIDEXTRA;
4978             if (state->killer) {
4979                 /*
4980                  * Make space for the Killer cages. We do this
4981                  * unconditionally, for uniformity between squares,
4982                  * rather than making it depend on whether a Killer
4983                  * cage edge is actually present on any given side.
4984                  */
4985                 pl += GRIDEXTRA * 3;
4986                 pr -= GRIDEXTRA * 3;
4987                 pt += GRIDEXTRA * 3;
4988                 pb -= GRIDEXTRA * 3;
4989                 if (state->kgrid[y*cr+x] != 0) {
4990                     /* Make further space for the Killer number. */
4991                     pt += TILE_SIZE/4;
4992                     /* minph--; */
4993                 }
4994             }
4995
4996             /*
4997              * We arrange our pencil marks in a grid layout, with
4998              * the number of rows and columns adjusted to allow the
4999              * maximum font size.
5000              *
5001              * So now we work out what the grid size ought to be.
5002              */
5003             bestsize = 0.0;
5004             pbest = 0;
5005             /* Minimum */
5006             for (pw = 3; pw < max(npencil,4); pw++) {
5007                 float fw, fh, fs;
5008
5009                 ph = (npencil + pw - 1) / pw;
5010                 ph = max(ph, minph);
5011                 fw = (pr - pl) / (float)pw;
5012                 fh = (pb - pt) / (float)ph;
5013                 fs = min(fw, fh);
5014                 if (fs > bestsize) {
5015                     bestsize = fs;
5016                     pbest = pw;
5017                 }
5018             }
5019             assert(pbest > 0);
5020             pw = pbest;
5021             ph = (npencil + pw - 1) / pw;
5022             ph = max(ph, minph);
5023
5024             /*
5025              * Now we've got our grid dimensions, work out the pixel
5026              * size of a grid element, and round it to the nearest
5027              * pixel. (We don't want rounding errors to make the
5028              * grid look uneven at low pixel sizes.)
5029              */
5030             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
5031
5032             /*
5033              * Centre the resulting figure in the square.
5034              */
5035             pl = tx + (TILE_SIZE - fontsize * pw) / 2;
5036             pt = ty + (TILE_SIZE - fontsize * ph) / 2;
5037
5038             /*
5039              * And move it down a bit if it's collided with the
5040              * Killer cage number.
5041              */
5042             if (state->killer && state->kgrid[y*cr+x] != 0) {
5043                 pt = max(pt, ty + GRIDEXTRA * 3 + TILE_SIZE/4);
5044             }
5045
5046             /*
5047              * Now actually draw the pencil marks.
5048              */
5049             for (i = j = 0; i < cr; i++)
5050                 if (state->pencil[(y*cr+x)*cr+i]) {
5051                     int dx = j % pw, dy = j / pw;
5052
5053                     str[1] = '\0';
5054                     str[0] = i + '1';
5055                     if (str[0] > '9')
5056                         str[0] += 'a' - ('9'+1);
5057                     draw_text(dr, pl + fontsize * (2*dx+1) / 2,
5058                               pt + fontsize * (2*dy+1) / 2,
5059                               FONT_VARIABLE, fontsize,
5060                               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
5061                     j++;
5062                 }
5063         }
5064     }
5065
5066     unclip(dr);
5067
5068     draw_update(dr, cx, cy, cw, ch);
5069
5070     ds->grid[y*cr+x] = state->grid[y*cr+x];
5071     memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
5072     ds->hl[y*cr+x] = hl;
5073 }
5074
5075 static void game_redraw(drawing *dr, game_drawstate *ds,
5076                         const game_state *oldstate, const game_state *state,
5077                         int dir, const game_ui *ui,
5078                         float animtime, float flashtime)
5079 {
5080     int cr = state->cr;
5081     int x, y;
5082
5083     if (!ds->started) {
5084         /*
5085          * The initial contents of the window are not guaranteed
5086          * and can vary with front ends. To be on the safe side,
5087          * all games should start by drawing a big
5088          * background-colour rectangle covering the whole window.
5089          */
5090         draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
5091
5092         /*
5093          * Draw the grid. We draw it as a big thick rectangle of
5094          * COL_GRID initially; individual calls to draw_number()
5095          * will poke the right-shaped holes in it.
5096          */
5097         draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
5098                   cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
5099                   COL_GRID);
5100     }
5101
5102     /*
5103      * This array is used to keep track of rows, columns and boxes
5104      * which contain a number more than once.
5105      */
5106     for (x = 0; x < cr * ds->nregions; x++)
5107         ds->entered_items[x] = 0;
5108     for (x = 0; x < cr; x++)
5109         for (y = 0; y < cr; y++) {
5110             digit d = state->grid[y*cr+x];
5111             if (d) {
5112                 int box, kbox;
5113
5114                 /* Rows */
5115                 ds->entered_items[x*cr+d-1]++;
5116
5117                 /* Columns */
5118                 ds->entered_items[(y+cr)*cr+d-1]++;
5119
5120                 /* Blocks */
5121                 box = state->blocks->whichblock[y*cr+x];
5122                 ds->entered_items[(box+2*cr)*cr+d-1]++;
5123
5124                 /* Diagonals */
5125                 if (ds->xtype) {
5126                     if (ondiag0(y*cr+x))
5127                         ds->entered_items[(3*cr)*cr+d-1]++;
5128                     if (ondiag1(y*cr+x))
5129                         ds->entered_items[(3*cr+1)*cr+d-1]++;
5130                 }
5131
5132                 /* Killer cages */
5133                 if (state->kblocks) {
5134                     kbox = state->kblocks->whichblock[y*cr+x];
5135                     ds->entered_items[(kbox+3*cr+2)*cr+d-1]++;
5136                 }
5137             }
5138         }
5139
5140     /*
5141      * Draw any numbers which need redrawing.
5142      */
5143     for (x = 0; x < cr; x++) {
5144         for (y = 0; y < cr; y++) {
5145             int highlight = 0;
5146             digit d = state->grid[y*cr+x];
5147
5148             if (flashtime > 0 &&
5149                 (flashtime <= FLASH_TIME/3 ||
5150                  flashtime >= FLASH_TIME*2/3))
5151                 highlight = 1;
5152
5153             /* Highlight active input areas. */
5154             if (x == ui->hx && y == ui->hy && ui->hshow)
5155                 highlight = ui->hpencil ? 2 : 1;
5156
5157             /* Mark obvious errors (ie, numbers which occur more than once
5158              * in a single row, column, or box). */
5159             if (d && (ds->entered_items[x*cr+d-1] > 1 ||
5160                       ds->entered_items[(y+cr)*cr+d-1] > 1 ||
5161                       ds->entered_items[(state->blocks->whichblock[y*cr+x]
5162                                          +2*cr)*cr+d-1] > 1 ||
5163                       (ds->xtype && ((ondiag0(y*cr+x) &&
5164                                       ds->entered_items[(3*cr)*cr+d-1] > 1) ||
5165                                      (ondiag1(y*cr+x) &&
5166                                       ds->entered_items[(3*cr+1)*cr+d-1]>1)))||
5167                       (state->kblocks &&
5168                        ds->entered_items[(state->kblocks->whichblock[y*cr+x]
5169                                           +3*cr+2)*cr+d-1] > 1)))
5170                 highlight |= 16;
5171
5172             if (d && state->kblocks) {
5173                 int i, b = state->kblocks->whichblock[y*cr+x];
5174                 int n_squares = state->kblocks->nr_squares[b];
5175                 int sum = 0, clue = 0;
5176                 for (i = 0; i < n_squares; i++) {
5177                     int xy = state->kblocks->blocks[b][i];
5178                     if (state->grid[xy] == 0)
5179                         break;
5180
5181                     sum += state->grid[xy];
5182                     if (state->kgrid[xy]) {
5183                         assert(clue == 0);
5184                         clue = state->kgrid[xy];
5185                     }
5186                 }
5187
5188                 if (i == n_squares) {
5189                     assert(clue != 0);
5190                     if (sum != clue)
5191                         highlight |= 32;
5192                 }
5193             }
5194
5195             draw_number(dr, ds, state, x, y, highlight);
5196         }
5197     }
5198
5199     /*
5200      * Update the _entire_ grid if necessary.
5201      */
5202     if (!ds->started) {
5203         draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
5204         ds->started = TRUE;
5205     }
5206 }
5207
5208 static float game_anim_length(const game_state *oldstate,
5209                               const game_state *newstate, int dir, game_ui *ui)
5210 {
5211     return 0.0F;
5212 }
5213
5214 static float game_flash_length(const game_state *oldstate,
5215                                const game_state *newstate, int dir, game_ui *ui)
5216 {
5217     if (!oldstate->completed && newstate->completed &&
5218         !oldstate->cheated && !newstate->cheated)
5219         return FLASH_TIME;
5220     return 0.0F;
5221 }
5222
5223 static int game_status(const game_state *state)
5224 {
5225     return state->completed ? +1 : 0;
5226 }
5227
5228 static int game_timing_state(const game_state *state, game_ui *ui)
5229 {
5230     if (state->completed)
5231         return FALSE;
5232     return TRUE;
5233 }
5234
5235 static void game_print_size(const game_params *params, float *x, float *y)
5236 {
5237     int pw, ph;
5238
5239     /*
5240      * I'll use 9mm squares by default. They should be quite big
5241      * for this game, because players will want to jot down no end
5242      * of pencil marks in the squares.
5243      */
5244     game_compute_size(params, 900, &pw, &ph);
5245     *x = pw / 100.0F;
5246     *y = ph / 100.0F;
5247 }
5248
5249 /*
5250  * Subfunction to draw the thick lines between cells. In order to do
5251  * this using the line-drawing rather than rectangle-drawing API (so
5252  * as to get line thicknesses to scale correctly) and yet have
5253  * correctly mitred joins between lines, we must do this by tracing
5254  * the boundary of each sub-block and drawing it in one go as a
5255  * single polygon.
5256  *
5257  * This subfunction is also reused with thinner dotted lines to
5258  * outline the Killer cages, this time offsetting the outline toward
5259  * the interior of the affected squares.
5260  */
5261 static void outline_block_structure(drawing *dr, game_drawstate *ds,
5262                                     const game_state *state,
5263                                     struct block_structure *blocks,
5264                                     int ink, int inset)
5265 {
5266     int cr = state->cr;
5267     int *coords;
5268     int bi, i, n;
5269     int x, y, dx, dy, sx, sy, sdx, sdy;
5270
5271     /*
5272      * Maximum perimeter of a k-omino is 2k+2. (Proof: start
5273      * with k unconnected squares, with total perimeter 4k.
5274      * Now repeatedly join two disconnected components
5275      * together into a larger one; every time you do so you
5276      * remove at least two unit edges, and you require k-1 of
5277      * these operations to create a single connected piece, so
5278      * you must have at most 4k-2(k-1) = 2k+2 unit edges left
5279      * afterwards.)
5280      */
5281     coords = snewn(4*cr+4, int);   /* 2k+2 points, 2 coords per point */
5282
5283     /*
5284      * Iterate over all the blocks.
5285      */
5286     for (bi = 0; bi < blocks->nr_blocks; bi++) {
5287         if (blocks->nr_squares[bi] == 0)
5288             continue;
5289
5290         /*
5291          * For each block, find a starting square within it
5292          * which has a boundary at the left.
5293          */
5294         for (i = 0; i < cr; i++) {
5295             int j = blocks->blocks[bi][i];
5296             if (j % cr == 0 || blocks->whichblock[j-1] != bi)
5297                 break;
5298         }
5299         assert(i < cr); /* every block must have _some_ leftmost square */
5300         x = blocks->blocks[bi][i] % cr;
5301         y = blocks->blocks[bi][i] / cr;
5302         dx = -1;
5303         dy = 0;
5304
5305         /*
5306          * Now begin tracing round the perimeter. At all
5307          * times, (x,y) describes some square within the
5308          * block, and (x+dx,y+dy) is some adjacent square
5309          * outside it; so the edge between those two squares
5310          * is always an edge of the block.
5311          */
5312         sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
5313         n = 0;
5314         do {
5315             int cx, cy, tx, ty, nin;
5316
5317             /*
5318              * Advance to the next edge, by looking at the two
5319              * squares beyond it. If they're both outside the block,
5320              * we turn right (by leaving x,y the same and rotating
5321              * dx,dy clockwise); if they're both inside, we turn
5322              * left (by rotating dx,dy anticlockwise and contriving
5323              * to leave x+dx,y+dy unchanged); if one of each, we go
5324              * straight on (and may enforce by assertion that
5325              * they're one of each the _right_ way round).
5326              */
5327             nin = 0;
5328             tx = x - dy + dx;
5329             ty = y + dx + dy;
5330             nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5331                     blocks->whichblock[ty*cr+tx] == bi);
5332             tx = x - dy;
5333             ty = y + dx;
5334             nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5335                     blocks->whichblock[ty*cr+tx] == bi);
5336             if (nin == 0) {
5337                 /*
5338                  * Turn right.
5339                  */
5340                 int tmp;
5341                 tmp = dx;
5342                 dx = -dy;
5343                 dy = tmp;
5344             } else if (nin == 2) {
5345                 /*
5346                  * Turn left.
5347                  */
5348                 int tmp;
5349
5350                 x += dx;
5351                 y += dy;
5352
5353                 tmp = dx;
5354                 dx = dy;
5355                 dy = -tmp;
5356
5357                 x -= dx;
5358                 y -= dy;
5359             } else {
5360                 /*
5361                  * Go straight on.
5362                  */
5363                 x -= dy;
5364                 y += dx;
5365             }
5366
5367             /*
5368              * Now enforce by assertion that we ended up
5369              * somewhere sensible.
5370              */
5371             assert(x >= 0 && x < cr && y >= 0 && y < cr &&
5372                    blocks->whichblock[y*cr+x] == bi);
5373             assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
5374                    blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
5375
5376             /*
5377              * Record the point we just went past at one end of the
5378              * edge. To do this, we translate (x,y) down and right
5379              * by half a unit (so they're describing a point in the
5380              * _centre_ of the square) and then translate back again
5381              * in a manner rotated by dy and dx.
5382              */
5383             assert(n < 2*cr+2);
5384             cx = ((2*x+1) + dy + dx) / 2;
5385             cy = ((2*y+1) - dx + dy) / 2;
5386             coords[2*n+0] = BORDER + cx * TILE_SIZE;
5387             coords[2*n+1] = BORDER + cy * TILE_SIZE;
5388             coords[2*n+0] -= dx * inset;
5389             coords[2*n+1] -= dy * inset;
5390             if (nin == 0) {
5391                 /*
5392                  * We turned right, so inset this corner back along
5393                  * the edge towards the centre of the square.
5394                  */
5395                 coords[2*n+0] -= dy * inset;
5396                 coords[2*n+1] += dx * inset;
5397             } else if (nin == 2) {
5398                 /*
5399                  * We turned left, so inset this corner further
5400                  * _out_ along the edge into the next square.
5401                  */
5402                 coords[2*n+0] += dy * inset;
5403                 coords[2*n+1] -= dx * inset;
5404             }
5405             n++;
5406
5407         } while (x != sx || y != sy || dx != sdx || dy != sdy);
5408
5409         /*
5410          * That's our polygon; now draw it.
5411          */
5412         draw_polygon(dr, coords, n, -1, ink);
5413     }
5414
5415     sfree(coords);
5416 }
5417
5418 static void game_print(drawing *dr, const game_state *state, int tilesize)
5419 {
5420     int cr = state->cr;
5421     int ink = print_mono_colour(dr, 0);
5422     int x, y;
5423
5424     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
5425     game_drawstate ads, *ds = &ads;
5426     game_set_size(dr, ds, NULL, tilesize);
5427
5428     /*
5429      * Border.
5430      */
5431     print_line_width(dr, 3 * TILE_SIZE / 40);
5432     draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
5433
5434     /*
5435      * Highlight X-diagonal squares.
5436      */
5437     if (state->xtype) {
5438         int i;
5439         int xhighlight = print_grey_colour(dr, 0.90F);
5440
5441         for (i = 0; i < cr; i++)
5442             draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
5443                       TILE_SIZE, TILE_SIZE, xhighlight);
5444         for (i = 0; i < cr; i++)
5445             if (i*2 != cr-1)  /* avoid redoing centre square, just for fun */
5446                 draw_rect(dr, BORDER + i*TILE_SIZE,
5447                           BORDER + (cr-1-i)*TILE_SIZE,
5448                           TILE_SIZE, TILE_SIZE, xhighlight);
5449     }
5450
5451     /*
5452      * Main grid.
5453      */
5454     for (x = 1; x < cr; x++) {
5455         print_line_width(dr, TILE_SIZE / 40);
5456         draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
5457                   BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
5458     }
5459     for (y = 1; y < cr; y++) {
5460         print_line_width(dr, TILE_SIZE / 40);
5461         draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
5462                   BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
5463     }
5464
5465     /*
5466      * Thick lines between cells.
5467      */
5468     print_line_width(dr, 3 * TILE_SIZE / 40);
5469     outline_block_structure(dr, ds, state, state->blocks, ink, 0);
5470
5471     /*
5472      * Killer cages and their totals.
5473      */
5474     if (state->kblocks) {
5475         print_line_width(dr, TILE_SIZE / 40);
5476         print_line_dotted(dr, TRUE);
5477         outline_block_structure(dr, ds, state, state->kblocks, ink,
5478                                 5 * TILE_SIZE / 40);
5479         print_line_dotted(dr, FALSE);
5480         for (y = 0; y < cr; y++)
5481             for (x = 0; x < cr; x++)
5482                 if (state->kgrid[y*cr+x]) {
5483                     char str[20];
5484                     sprintf(str, "%d", state->kgrid[y*cr+x]);
5485                     draw_text(dr,
5486                               BORDER+x*TILE_SIZE + 7*TILE_SIZE/40,
5487                               BORDER+y*TILE_SIZE + 16*TILE_SIZE/40,
5488                               FONT_VARIABLE, TILE_SIZE/4,
5489                               ALIGN_VNORMAL | ALIGN_HLEFT,
5490                               ink, str);
5491                 }
5492     }
5493
5494     /*
5495      * Standard (non-Killer) clue numbers.
5496      */
5497     for (y = 0; y < cr; y++)
5498         for (x = 0; x < cr; x++)
5499             if (state->grid[y*cr+x]) {
5500                 char str[2];
5501                 str[1] = '\0';
5502                 str[0] = state->grid[y*cr+x] + '0';
5503                 if (str[0] > '9')
5504                     str[0] += 'a' - ('9'+1);
5505                 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
5506                           BORDER + y*TILE_SIZE + TILE_SIZE/2,
5507                           FONT_VARIABLE, TILE_SIZE/2,
5508                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
5509             }
5510 }
5511
5512 #ifdef COMBINED
5513 #define thegame solo
5514 #endif
5515
5516 const struct game thegame = {
5517     "Solo", "games.solo", "solo",
5518     default_params,
5519     game_fetch_preset,
5520     decode_params,
5521     encode_params,
5522     free_params,
5523     dup_params,
5524     TRUE, game_configure, custom_params,
5525     validate_params,
5526     new_game_desc,
5527     validate_desc,
5528     new_game,
5529     dup_game,
5530     free_game,
5531     TRUE, solve_game,
5532     TRUE, game_can_format_as_text_now, game_text_format,
5533     new_ui,
5534     free_ui,
5535     encode_ui,
5536     decode_ui,
5537     game_changed_state,
5538     interpret_move,
5539     execute_move,
5540     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
5541     game_colours,
5542     game_new_drawstate,
5543     game_free_drawstate,
5544     game_redraw,
5545     game_anim_length,
5546     game_flash_length,
5547     game_status,
5548     TRUE, FALSE, game_print_size, game_print,
5549     FALSE,                             /* wants_statusbar */
5550     FALSE, game_timing_state,
5551     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
5552 };
5553
5554 #ifdef STANDALONE_SOLVER
5555
5556 int main(int argc, char **argv)
5557 {
5558     game_params *p;
5559     game_state *s;
5560     char *id = NULL, *desc, *err;
5561     int grade = FALSE;
5562     struct difficulty dlev;
5563
5564     while (--argc > 0) {
5565         char *p = *++argv;
5566         if (!strcmp(p, "-v")) {
5567             solver_show_working = TRUE;
5568         } else if (!strcmp(p, "-g")) {
5569             grade = TRUE;
5570         } else if (*p == '-') {
5571             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
5572             return 1;
5573         } else {
5574             id = p;
5575         }
5576     }
5577
5578     if (!id) {
5579         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
5580         return 1;
5581     }
5582
5583     desc = strchr(id, ':');
5584     if (!desc) {
5585         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
5586         return 1;
5587     }
5588     *desc++ = '\0';
5589
5590     p = default_params();
5591     decode_params(p, id);
5592     err = validate_desc(p, desc);
5593     if (err) {
5594         fprintf(stderr, "%s: %s\n", argv[0], err);
5595         return 1;
5596     }
5597     s = new_game(NULL, p, desc);
5598
5599     dlev.maxdiff = DIFF_RECURSIVE;
5600     dlev.maxkdiff = DIFF_KINTERSECT;
5601     solver(s->cr, s->blocks, s->kblocks, s->xtype, s->grid, s->kgrid, &dlev);
5602     if (grade) {
5603         printf("Difficulty rating: %s\n",
5604                dlev.diff==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
5605                dlev.diff==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
5606                dlev.diff==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
5607                dlev.diff==DIFF_SET ? "Advanced (set elimination required)":
5608                dlev.diff==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
5609                dlev.diff==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
5610                dlev.diff==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
5611                dlev.diff==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
5612                "INTERNAL ERROR: unrecognised difficulty code");
5613         if (p->killer)
5614             printf("Killer difficulty: %s\n",
5615                    dlev.kdiff==DIFF_KSINGLE ? "Trivial (single square cages only)":
5616                    dlev.kdiff==DIFF_KMINMAX ? "Simple (maximum sum analysis required)":
5617                    dlev.kdiff==DIFF_KSUMS ? "Intermediate (sum possibilities)":
5618                    dlev.kdiff==DIFF_KINTERSECT ? "Advanced (sum region intersections)":
5619                    "INTERNAL ERROR: unrecognised difficulty code");
5620     } else {
5621         printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
5622     }
5623
5624     return 0;
5625 }
5626
5627 #endif
5628
5629 /* vim: set shiftwidth=4 tabstop=8: */