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