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