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