New infrastructure feature. Games are now permitted to be
[sgt/puzzles] / solo.c
1 /*
2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3 *
4 * TODO:
5 *
6 * - reports from users are that `Trivial'-mode puzzles are still
7 * rather hard compared to newspapers' easy ones, so some better
8 * low-end difficulty grading would be nice
9 * + it's possible that really easy puzzles always have
10 * _several_ things you can do, so don't make you hunt too
11 * hard for the one deduction you can currently make
12 * + it's also possible that easy puzzles require fewer
13 * cross-eliminations: perhaps there's a higher incidence of
14 * things you can deduce by looking only at (say) rows,
15 * rather than things you have to check both rows and columns
16 * for
17 * + but really, what I need to do is find some really easy
18 * puzzles and _play_ them, to see what's actually easy about
19 * them
20 * + while I'm revamping this area, filling in the _last_
21 * number in a nearly-full row or column should certainly be
22 * permitted even at the lowest difficulty level.
23 * + also Owen noticed that `Basic' grids requiring numeric
24 * elimination are actually very hard, so I wonder if a
25 * difficulty gradation between that and positional-
26 * elimination-only might be in order
27 * + but it's not good to have _too_ many difficulty levels, or
28 * it'll take too long to randomly generate a given level.
29 *
30 * - it might still be nice to do some prioritisation on the
31 * removal of numbers from the grid
32 * + one possibility is to try to minimise the maximum number
33 * of filled squares in any block, which in particular ought
34 * to enforce never leaving a completely filled block in the
35 * puzzle as presented.
36 *
37 * - alternative interface modes
38 * + sudoku.com's Windows program has a palette of possible
39 * entries; you select a palette entry first and then click
40 * on the square you want it to go in, thus enabling
41 * mouse-only play. Useful for PDAs! I don't think it's
42 * actually incompatible with the current highlight-then-type
43 * approach: you _either_ highlight a palette entry and then
44 * click, _or_ you highlight a square and then type. At most
45 * one thing is ever highlighted at a time, so there's no way
46 * to confuse the two.
47 * + then again, I don't actually like sudoku.com's interface;
48 * it's too much like a paint package whereas I prefer to
49 * think of Solo as a text editor.
50 * + another PDA-friendly possibility is a drag interface:
51 * _drag_ numbers from the palette into the grid squares.
52 * Thought experiments suggest I'd prefer that to the
53 * sudoku.com approach, but I haven't actually tried it.
54 */
55
56 /*
57 * Solo puzzles need to be square overall (since each row and each
58 * column must contain one of every digit), but they need not be
59 * subdivided the same way internally. I am going to adopt a
60 * convention whereby I _always_ refer to `r' as the number of rows
61 * of _big_ divisions, and `c' as the number of columns of _big_
62 * divisions. Thus, a 2c by 3r puzzle looks something like this:
63 *
64 * 4 5 1 | 2 6 3
65 * 6 3 2 | 5 4 1
66 * ------+------ (Of course, you can't subdivide it the other way
67 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
68 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
69 * ------+------ box down on the left-hand side.)
70 * 5 1 4 | 3 2 6
71 * 2 6 3 | 1 5 4
72 *
73 * The need for a strong naming convention should now be clear:
74 * each small box is two rows of digits by three columns, while the
75 * overall puzzle has three rows of small boxes by two columns. So
76 * I will (hopefully) consistently use `r' to denote the number of
77 * rows _of small boxes_ (here 3), which is also the number of
78 * columns of digits in each small box; and `c' vice versa (here
79 * 2).
80 *
81 * I'm also going to choose arbitrarily to list c first wherever
82 * possible: the above is a 2x3 puzzle, not a 3x2 one.
83 */
84
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <assert.h>
89 #include <ctype.h>
90 #include <math.h>
91
92 #ifdef STANDALONE_SOLVER
93 #include <stdarg.h>
94 int solver_show_working, solver_recurse_depth;
95 #endif
96
97 #include "puzzles.h"
98
99 /*
100 * To save space, I store digits internally as unsigned char. This
101 * imposes a hard limit of 255 on the order of the puzzle. Since
102 * even a 5x5 takes unacceptably long to generate, I don't see this
103 * as a serious limitation unless something _really_ impressive
104 * happens in computing technology; but here's a typedef anyway for
105 * general good practice.
106 */
107 typedef unsigned char digit;
108 #define ORDER_MAX 255
109
110 #define PREFERRED_TILE_SIZE 32
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113 #define GRIDEXTRA (TILE_SIZE / 32)
114
115 #define FLASH_TIME 0.4F
116
117 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
118 SYMM_REF4D, SYMM_REF8 };
119
120 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME,
121 DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
122
123 enum {
124 COL_BACKGROUND,
125 COL_XDIAGONALS,
126 COL_GRID,
127 COL_CLUE,
128 COL_USER,
129 COL_HIGHLIGHT,
130 COL_ERROR,
131 COL_PENCIL,
132 NCOLOURS
133 };
134
135 struct game_params {
136 /*
137 * For a square puzzle, `c' and `r' indicate the puzzle
138 * parameters as described above.
139 *
140 * A jigsaw-style puzzle is indicated by r==1, in which case c
141 * can be whatever it likes (there is no constraint on
142 * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
143 */
144 int c, r, symm, diff;
145 int xtype; /* require all digits in X-diagonals */
146 };
147
148 struct block_structure {
149 int refcount;
150
151 /*
152 * For text formatting, we do need c and r here.
153 */
154 int c, r;
155
156 /*
157 * For any square index, whichblock[i] gives its block index.
158 *
159 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
160 * square in block b.
161 *
162 * whichblock and blocks are each dynamically allocated in
163 * their own right, but the subarrays in blocks are appended
164 * to the whichblock array, so shouldn't be freed
165 * individually.
166 */
167 int *whichblock, **blocks;
168
169 #ifdef STANDALONE_SOLVER
170 /*
171 * Textual descriptions of each block. For normal Sudoku these
172 * are of the form "(1,3)"; for jigsaw they are "starting at
173 * (5,7)". So the sensible usage in both cases is to say
174 * "elimination within block %s" with one of these strings.
175 *
176 * Only blocknames itself needs individually freeing; it's all
177 * one block.
178 */
179 char **blocknames;
180 #endif
181 };
182
183 struct game_state {
184 /*
185 * For historical reasons, I use `cr' to denote the overall
186 * width/height of the puzzle. It was a natural notation when
187 * all puzzles were divided into blocks in a grid, but doesn't
188 * really make much sense given jigsaw puzzles. However, the
189 * obvious `n' is heavily used in the solver to describe the
190 * index of a number being placed, so `cr' will have to stay.
191 */
192 int cr;
193 struct block_structure *blocks;
194 int xtype;
195 digit *grid;
196 unsigned char *pencil; /* c*r*c*r elements */
197 unsigned char *immutable; /* marks which digits are clues */
198 int completed, cheated;
199 };
200
201 static game_params *default_params(void)
202 {
203 game_params *ret = snew(game_params);
204
205 ret->c = ret->r = 3;
206 ret->xtype = FALSE;
207 ret->symm = SYMM_ROT2; /* a plausible default */
208 ret->diff = DIFF_BLOCK; /* so is this */
209
210 return ret;
211 }
212
213 static void free_params(game_params *params)
214 {
215 sfree(params);
216 }
217
218 static game_params *dup_params(game_params *params)
219 {
220 game_params *ret = snew(game_params);
221 *ret = *params; /* structure copy */
222 return ret;
223 }
224
225 static int game_fetch_preset(int i, char **name, game_params **params)
226 {
227 static struct {
228 char *title;
229 game_params params;
230 } presets[] = {
231 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, FALSE } },
232 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
233 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, FALSE } },
234 { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
235 { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, TRUE } },
236 { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, FALSE } },
237 { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, FALSE } },
238 { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, TRUE } },
239 { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, FALSE } },
240 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, FALSE } },
241 { "9 Jigsaw Basic", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
242 { "9 Jigsaw Basic X", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, TRUE } },
243 { "9 Jigsaw Advanced", { 9, 1, SYMM_ROT2, DIFF_SET, FALSE } },
244 #ifndef SLOW_SYSTEM
245 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
246 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
247 #endif
248 };
249
250 if (i < 0 || i >= lenof(presets))
251 return FALSE;
252
253 *name = dupstr(presets[i].title);
254 *params = dup_params(&presets[i].params);
255
256 return TRUE;
257 }
258
259 static void decode_params(game_params *ret, char const *string)
260 {
261 int seen_r = FALSE;
262
263 ret->c = ret->r = atoi(string);
264 ret->xtype = FALSE;
265 while (*string && isdigit((unsigned char)*string)) string++;
266 if (*string == 'x') {
267 string++;
268 ret->r = atoi(string);
269 seen_r = TRUE;
270 while (*string && isdigit((unsigned char)*string)) string++;
271 }
272 while (*string) {
273 if (*string == 'j') {
274 string++;
275 if (seen_r)
276 ret->c *= ret->r;
277 ret->r = 1;
278 } else if (*string == 'x') {
279 string++;
280 ret->xtype = TRUE;
281 } else if (*string == 'r' || *string == 'm' || *string == 'a') {
282 int sn, sc, sd;
283 sc = *string++;
284 if (sc == 'm' && *string == 'd') {
285 sd = TRUE;
286 string++;
287 } else {
288 sd = FALSE;
289 }
290 sn = atoi(string);
291 while (*string && isdigit((unsigned char)*string)) string++;
292 if (sc == 'm' && sn == 8)
293 ret->symm = SYMM_REF8;
294 if (sc == 'm' && sn == 4)
295 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
296 if (sc == 'm' && sn == 2)
297 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
298 if (sc == 'r' && sn == 4)
299 ret->symm = SYMM_ROT4;
300 if (sc == 'r' && sn == 2)
301 ret->symm = SYMM_ROT2;
302 if (sc == 'a')
303 ret->symm = SYMM_NONE;
304 } else if (*string == 'd') {
305 string++;
306 if (*string == 't') /* trivial */
307 string++, ret->diff = DIFF_BLOCK;
308 else if (*string == 'b') /* basic */
309 string++, ret->diff = DIFF_SIMPLE;
310 else if (*string == 'i') /* intermediate */
311 string++, ret->diff = DIFF_INTERSECT;
312 else if (*string == 'a') /* advanced */
313 string++, ret->diff = DIFF_SET;
314 else if (*string == 'e') /* extreme */
315 string++, ret->diff = DIFF_EXTREME;
316 else if (*string == 'u') /* unreasonable */
317 string++, ret->diff = DIFF_RECURSIVE;
318 } else
319 string++; /* eat unknown character */
320 }
321 }
322
323 static char *encode_params(game_params *params, int full)
324 {
325 char str[80];
326
327 if (params->r > 1)
328 sprintf(str, "%dx%d", params->c, params->r);
329 else
330 sprintf(str, "%dj", params->c);
331 if (params->xtype)
332 strcat(str, "x");
333
334 if (full) {
335 switch (params->symm) {
336 case SYMM_REF8: strcat(str, "m8"); break;
337 case SYMM_REF4: strcat(str, "m4"); break;
338 case SYMM_REF4D: strcat(str, "md4"); break;
339 case SYMM_REF2: strcat(str, "m2"); break;
340 case SYMM_REF2D: strcat(str, "md2"); break;
341 case SYMM_ROT4: strcat(str, "r4"); break;
342 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
343 case SYMM_NONE: strcat(str, "a"); break;
344 }
345 switch (params->diff) {
346 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
347 case DIFF_SIMPLE: strcat(str, "db"); break;
348 case DIFF_INTERSECT: strcat(str, "di"); break;
349 case DIFF_SET: strcat(str, "da"); break;
350 case DIFF_EXTREME: strcat(str, "de"); break;
351 case DIFF_RECURSIVE: strcat(str, "du"); break;
352 }
353 }
354 return dupstr(str);
355 }
356
357 static config_item *game_configure(game_params *params)
358 {
359 config_item *ret;
360 char buf[80];
361
362 ret = snewn(7, config_item);
363
364 ret[0].name = "Columns of sub-blocks";
365 ret[0].type = C_STRING;
366 sprintf(buf, "%d", params->c);
367 ret[0].sval = dupstr(buf);
368 ret[0].ival = 0;
369
370 ret[1].name = "Rows of sub-blocks";
371 ret[1].type = C_STRING;
372 sprintf(buf, "%d", params->r);
373 ret[1].sval = dupstr(buf);
374 ret[1].ival = 0;
375
376 ret[2].name = "\"X\" (require every number in each main diagonal)";
377 ret[2].type = C_BOOLEAN;
378 ret[2].sval = NULL;
379 ret[2].ival = params->xtype;
380
381 ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
382 ret[3].type = C_BOOLEAN;
383 ret[3].sval = NULL;
384 ret[3].ival = (params->r == 1);
385
386 ret[4].name = "Symmetry";
387 ret[4].type = C_CHOICES;
388 ret[4].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
389 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
390 "8-way mirror";
391 ret[4].ival = params->symm;
392
393 ret[5].name = "Difficulty";
394 ret[5].type = C_CHOICES;
395 ret[5].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
396 ret[5].ival = params->diff;
397
398 ret[6].name = NULL;
399 ret[6].type = C_END;
400 ret[6].sval = NULL;
401 ret[6].ival = 0;
402
403 return ret;
404 }
405
406 static game_params *custom_params(config_item *cfg)
407 {
408 game_params *ret = snew(game_params);
409
410 ret->c = atoi(cfg[0].sval);
411 ret->r = atoi(cfg[1].sval);
412 ret->xtype = cfg[2].ival;
413 if (cfg[3].ival) {
414 ret->c *= ret->r;
415 ret->r = 1;
416 }
417 ret->symm = cfg[4].ival;
418 ret->diff = cfg[5].ival;
419
420 return ret;
421 }
422
423 static char *validate_params(game_params *params, int full)
424 {
425 if (params->c < 2)
426 return "Both dimensions must be at least 2";
427 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
428 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
429 if ((params->c * params->r) > 35)
430 return "Unable to support more than 35 distinct symbols in a puzzle";
431 return NULL;
432 }
433
434 /* ----------------------------------------------------------------------
435 * Solver.
436 *
437 * This solver is used for two purposes:
438 * + to check solubility of a grid as we gradually remove numbers
439 * from it
440 * + to solve an externally generated puzzle when the user selects
441 * `Solve'.
442 *
443 * It supports a variety of specific modes of reasoning. By
444 * enabling or disabling subsets of these modes we can arrange a
445 * range of difficulty levels.
446 */
447
448 /*
449 * Modes of reasoning currently supported:
450 *
451 * - Positional elimination: a number must go in a particular
452 * square because all the other empty squares in a given
453 * row/col/blk are ruled out.
454 *
455 * - Numeric elimination: a square must have a particular number
456 * in because all the other numbers that could go in it are
457 * ruled out.
458 *
459 * - Intersectional analysis: given two domains which overlap
460 * (hence one must be a block, and the other can be a row or
461 * col), if the possible locations for a particular number in
462 * one of the domains can be narrowed down to the overlap, then
463 * that number can be ruled out everywhere but the overlap in
464 * the other domain too.
465 *
466 * - Set elimination: if there is a subset of the empty squares
467 * within a domain such that the union of the possible numbers
468 * in that subset has the same size as the subset itself, then
469 * those numbers can be ruled out everywhere else in the domain.
470 * (For example, if there are five empty squares and the
471 * possible numbers in each are 12, 23, 13, 134 and 1345, then
472 * the first three empty squares form such a subset: the numbers
473 * 1, 2 and 3 _must_ be in those three squares in some
474 * permutation, and hence we can deduce none of them can be in
475 * the fourth or fifth squares.)
476 * + You can also see this the other way round, concentrating
477 * on numbers rather than squares: if there is a subset of
478 * the unplaced numbers within a domain such that the union
479 * of all their possible positions has the same size as the
480 * subset itself, then all other numbers can be ruled out for
481 * those positions. However, it turns out that this is
482 * exactly equivalent to the first formulation at all times:
483 * there is a 1-1 correspondence between suitable subsets of
484 * the unplaced numbers and suitable subsets of the unfilled
485 * places, found by taking the _complement_ of the union of
486 * the numbers' possible positions (or the spaces' possible
487 * contents).
488 *
489 * - Forcing chains (see comment for solver_forcing().)
490 *
491 * - Recursion. If all else fails, we pick one of the currently
492 * most constrained empty squares and take a random guess at its
493 * contents, then continue solving on that basis and see if we
494 * get any further.
495 */
496
497 struct solver_usage {
498 int cr;
499 struct block_structure *blocks;
500 /*
501 * We set up a cubic array, indexed by x, y and digit; each
502 * element of this array is TRUE or FALSE according to whether
503 * or not that digit _could_ in principle go in that position.
504 *
505 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
506 * are macros below to help with this.
507 */
508 unsigned char *cube;
509 /*
510 * This is the grid in which we write down our final
511 * deductions. y-coordinates in here are _not_ transformed.
512 */
513 digit *grid;
514 /*
515 * Now we keep track, at a slightly higher level, of what we
516 * have yet to work out, to prevent doing the same deduction
517 * many times.
518 */
519 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
520 unsigned char *row;
521 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
522 unsigned char *col;
523 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
524 unsigned char *blk;
525 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
526 unsigned char *diag; /* diag 0 is \, 1 is / */
527 };
528 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
529 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
530 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
531 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
532
533 #define ondiag0(xy) ((xy) % (cr+1) == 0)
534 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
535 #define diag0(i) ((i) * (cr+1))
536 #define diag1(i) ((i+1) * (cr-1))
537
538 /*
539 * Function called when we are certain that a particular square has
540 * a particular number in it. The y-coordinate passed in here is
541 * transformed.
542 */
543 static void solver_place(struct solver_usage *usage, int x, int y, int n)
544 {
545 int cr = usage->cr;
546 int sqindex = y*cr+x;
547 int i, bi;
548
549 assert(cube(x,y,n));
550
551 /*
552 * Rule out all other numbers in this square.
553 */
554 for (i = 1; i <= cr; i++)
555 if (i != n)
556 cube(x,y,i) = FALSE;
557
558 /*
559 * Rule out this number in all other positions in the row.
560 */
561 for (i = 0; i < cr; i++)
562 if (i != y)
563 cube(x,i,n) = FALSE;
564
565 /*
566 * Rule out this number in all other positions in the column.
567 */
568 for (i = 0; i < cr; i++)
569 if (i != x)
570 cube(i,y,n) = FALSE;
571
572 /*
573 * Rule out this number in all other positions in the block.
574 */
575 bi = usage->blocks->whichblock[sqindex];
576 for (i = 0; i < cr; i++) {
577 int bp = usage->blocks->blocks[bi][i];
578 if (bp != sqindex)
579 cube2(bp,n) = FALSE;
580 }
581
582 /*
583 * Enter the number in the result grid.
584 */
585 usage->grid[sqindex] = n;
586
587 /*
588 * Cross out this number from the list of numbers left to place
589 * in its row, its column and its block.
590 */
591 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
592 usage->blk[bi*cr+n-1] = TRUE;
593
594 if (usage->diag) {
595 if (ondiag0(sqindex)) {
596 for (i = 0; i < cr; i++)
597 if (diag0(i) != sqindex)
598 cube2(diag0(i),n) = FALSE;
599 usage->diag[n-1] = TRUE;
600 }
601 if (ondiag1(sqindex)) {
602 for (i = 0; i < cr; i++)
603 if (diag1(i) != sqindex)
604 cube2(diag1(i),n) = FALSE;
605 usage->diag[cr+n-1] = TRUE;
606 }
607 }
608 }
609
610 static int solver_elim(struct solver_usage *usage, int *indices
611 #ifdef STANDALONE_SOLVER
612 , char *fmt, ...
613 #endif
614 )
615 {
616 int cr = usage->cr;
617 int fpos, m, i;
618
619 /*
620 * Count the number of set bits within this section of the
621 * cube.
622 */
623 m = 0;
624 fpos = -1;
625 for (i = 0; i < cr; i++)
626 if (usage->cube[indices[i]]) {
627 fpos = indices[i];
628 m++;
629 }
630
631 if (m == 1) {
632 int x, y, n;
633 assert(fpos >= 0);
634
635 n = 1 + fpos % cr;
636 x = fpos / cr;
637 y = x / cr;
638 x %= cr;
639
640 if (!usage->grid[y*cr+x]) {
641 #ifdef STANDALONE_SOLVER
642 if (solver_show_working) {
643 va_list ap;
644 printf("%*s", solver_recurse_depth*4, "");
645 va_start(ap, fmt);
646 vprintf(fmt, ap);
647 va_end(ap);
648 printf(":\n%*s placing %d at (%d,%d)\n",
649 solver_recurse_depth*4, "", n, 1+x, 1+y);
650 }
651 #endif
652 solver_place(usage, x, y, n);
653 return +1;
654 }
655 } else if (m == 0) {
656 #ifdef STANDALONE_SOLVER
657 if (solver_show_working) {
658 va_list ap;
659 printf("%*s", solver_recurse_depth*4, "");
660 va_start(ap, fmt);
661 vprintf(fmt, ap);
662 va_end(ap);
663 printf(":\n%*s no possibilities available\n",
664 solver_recurse_depth*4, "");
665 }
666 #endif
667 return -1;
668 }
669
670 return 0;
671 }
672
673 static int solver_intersect(struct solver_usage *usage,
674 int *indices1, int *indices2
675 #ifdef STANDALONE_SOLVER
676 , char *fmt, ...
677 #endif
678 )
679 {
680 int cr = usage->cr;
681 int ret, i, j;
682
683 /*
684 * Loop over the first domain and see if there's any set bit
685 * not also in the second.
686 */
687 for (i = j = 0; i < cr; i++) {
688 int p = indices1[i];
689 while (j < cr && indices2[j] < p)
690 j++;
691 if (usage->cube[p]) {
692 if (j < cr && indices2[j] == p)
693 continue; /* both domains contain this index */
694 else
695 return 0; /* there is, so we can't deduce */
696 }
697 }
698
699 /*
700 * We have determined that all set bits in the first domain are
701 * within its overlap with the second. So loop over the second
702 * domain and remove all set bits that aren't also in that
703 * overlap; return +1 iff we actually _did_ anything.
704 */
705 ret = 0;
706 for (i = j = 0; i < cr; i++) {
707 int p = indices2[i];
708 while (j < cr && indices1[j] < p)
709 j++;
710 if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
711 #ifdef STANDALONE_SOLVER
712 if (solver_show_working) {
713 int px, py, pn;
714
715 if (!ret) {
716 va_list ap;
717 printf("%*s", solver_recurse_depth*4, "");
718 va_start(ap, fmt);
719 vprintf(fmt, ap);
720 va_end(ap);
721 printf(":\n");
722 }
723
724 pn = 1 + p % cr;
725 px = p / cr;
726 py = px / cr;
727 px %= cr;
728
729 printf("%*s ruling out %d at (%d,%d)\n",
730 solver_recurse_depth*4, "", pn, 1+px, 1+py);
731 }
732 #endif
733 ret = +1; /* we did something */
734 usage->cube[p] = 0;
735 }
736 }
737
738 return ret;
739 }
740
741 struct solver_scratch {
742 unsigned char *grid, *rowidx, *colidx, *set;
743 int *neighbours, *bfsqueue;
744 int *indexlist, *indexlist2;
745 #ifdef STANDALONE_SOLVER
746 int *bfsprev;
747 #endif
748 };
749
750 static int solver_set(struct solver_usage *usage,
751 struct solver_scratch *scratch,
752 int *indices
753 #ifdef STANDALONE_SOLVER
754 , char *fmt, ...
755 #endif
756 )
757 {
758 int cr = usage->cr;
759 int i, j, n, count;
760 unsigned char *grid = scratch->grid;
761 unsigned char *rowidx = scratch->rowidx;
762 unsigned char *colidx = scratch->colidx;
763 unsigned char *set = scratch->set;
764
765 /*
766 * We are passed a cr-by-cr matrix of booleans. Our first job
767 * is to winnow it by finding any definite placements - i.e.
768 * any row with a solitary 1 - and discarding that row and the
769 * column containing the 1.
770 */
771 memset(rowidx, TRUE, cr);
772 memset(colidx, TRUE, cr);
773 for (i = 0; i < cr; i++) {
774 int count = 0, first = -1;
775 for (j = 0; j < cr; j++)
776 if (usage->cube[indices[i*cr+j]])
777 first = j, count++;
778
779 /*
780 * If count == 0, then there's a row with no 1s at all and
781 * the puzzle is internally inconsistent. However, we ought
782 * to have caught this already during the simpler reasoning
783 * methods, so we can safely fail an assertion if we reach
784 * this point here.
785 */
786 assert(count > 0);
787 if (count == 1)
788 rowidx[i] = colidx[first] = FALSE;
789 }
790
791 /*
792 * Convert each of rowidx/colidx from a list of 0s and 1s to a
793 * list of the indices of the 1s.
794 */
795 for (i = j = 0; i < cr; i++)
796 if (rowidx[i])
797 rowidx[j++] = i;
798 n = j;
799 for (i = j = 0; i < cr; i++)
800 if (colidx[i])
801 colidx[j++] = i;
802 assert(n == j);
803
804 /*
805 * And create the smaller matrix.
806 */
807 for (i = 0; i < n; i++)
808 for (j = 0; j < n; j++)
809 grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
810
811 /*
812 * Having done that, we now have a matrix in which every row
813 * has at least two 1s in. Now we search to see if we can find
814 * a rectangle of zeroes (in the set-theoretic sense of
815 * `rectangle', i.e. a subset of rows crossed with a subset of
816 * columns) whose width and height add up to n.
817 */
818
819 memset(set, 0, n);
820 count = 0;
821 while (1) {
822 /*
823 * We have a candidate set. If its size is <=1 or >=n-1
824 * then we move on immediately.
825 */
826 if (count > 1 && count < n-1) {
827 /*
828 * The number of rows we need is n-count. See if we can
829 * find that many rows which each have a zero in all
830 * the positions listed in `set'.
831 */
832 int rows = 0;
833 for (i = 0; i < n; i++) {
834 int ok = TRUE;
835 for (j = 0; j < n; j++)
836 if (set[j] && grid[i*cr+j]) {
837 ok = FALSE;
838 break;
839 }
840 if (ok)
841 rows++;
842 }
843
844 /*
845 * We expect never to be able to get _more_ than
846 * n-count suitable rows: this would imply that (for
847 * example) there are four numbers which between them
848 * have at most three possible positions, and hence it
849 * indicates a faulty deduction before this point or
850 * even a bogus clue.
851 */
852 if (rows > n - count) {
853 #ifdef STANDALONE_SOLVER
854 if (solver_show_working) {
855 va_list ap;
856 printf("%*s", solver_recurse_depth*4,
857 "");
858 va_start(ap, fmt);
859 vprintf(fmt, ap);
860 va_end(ap);
861 printf(":\n%*s contradiction reached\n",
862 solver_recurse_depth*4, "");
863 }
864 #endif
865 return -1;
866 }
867
868 if (rows >= n - count) {
869 int progress = FALSE;
870
871 /*
872 * We've got one! Now, for each row which _doesn't_
873 * satisfy the criterion, eliminate all its set
874 * bits in the positions _not_ listed in `set'.
875 * Return +1 (meaning progress has been made) if we
876 * successfully eliminated anything at all.
877 *
878 * This involves referring back through
879 * rowidx/colidx in order to work out which actual
880 * positions in the cube to meddle with.
881 */
882 for (i = 0; i < n; i++) {
883 int ok = TRUE;
884 for (j = 0; j < n; j++)
885 if (set[j] && grid[i*cr+j]) {
886 ok = FALSE;
887 break;
888 }
889 if (!ok) {
890 for (j = 0; j < n; j++)
891 if (!set[j] && grid[i*cr+j]) {
892 int fpos = indices[rowidx[i]*cr+colidx[j]];
893 #ifdef STANDALONE_SOLVER
894 if (solver_show_working) {
895 int px, py, pn;
896
897 if (!progress) {
898 va_list ap;
899 printf("%*s", solver_recurse_depth*4,
900 "");
901 va_start(ap, fmt);
902 vprintf(fmt, ap);
903 va_end(ap);
904 printf(":\n");
905 }
906
907 pn = 1 + fpos % cr;
908 px = fpos / cr;
909 py = px / cr;
910 px %= cr;
911
912 printf("%*s ruling out %d at (%d,%d)\n",
913 solver_recurse_depth*4, "",
914 pn, 1+px, 1+py);
915 }
916 #endif
917 progress = TRUE;
918 usage->cube[fpos] = FALSE;
919 }
920 }
921 }
922
923 if (progress) {
924 return +1;
925 }
926 }
927 }
928
929 /*
930 * Binary increment: change the rightmost 0 to a 1, and
931 * change all 1s to the right of it to 0s.
932 */
933 i = n;
934 while (i > 0 && set[i-1])
935 set[--i] = 0, count--;
936 if (i > 0)
937 set[--i] = 1, count++;
938 else
939 break; /* done */
940 }
941
942 return 0;
943 }
944
945 /*
946 * Look for forcing chains. A forcing chain is a path of
947 * pairwise-exclusive squares (i.e. each pair of adjacent squares
948 * in the path are in the same row, column or block) with the
949 * following properties:
950 *
951 * (a) Each square on the path has precisely two possible numbers.
952 *
953 * (b) Each pair of squares which are adjacent on the path share
954 * at least one possible number in common.
955 *
956 * (c) Each square in the middle of the path shares _both_ of its
957 * numbers with at least one of its neighbours (not the same
958 * one with both neighbours).
959 *
960 * These together imply that at least one of the possible number
961 * choices at one end of the path forces _all_ the rest of the
962 * numbers along the path. In order to make real use of this, we
963 * need further properties:
964 *
965 * (c) Ruling out some number N from the square at one end of the
966 * path forces the square at the other end to take the same
967 * number N.
968 *
969 * (d) The two end squares are both in line with some third
970 * square.
971 *
972 * (e) That third square currently has N as a possibility.
973 *
974 * If we can find all of that lot, we can deduce that at least one
975 * of the two ends of the forcing chain has number N, and that
976 * therefore the mutually adjacent third square does not.
977 *
978 * To find forcing chains, we're going to start a bfs at each
979 * suitable square, once for each of its two possible numbers.
980 */
981 static int solver_forcing(struct solver_usage *usage,
982 struct solver_scratch *scratch)
983 {
984 int cr = usage->cr;
985 int *bfsqueue = scratch->bfsqueue;
986 #ifdef STANDALONE_SOLVER
987 int *bfsprev = scratch->bfsprev;
988 #endif
989 unsigned char *number = scratch->grid;
990 int *neighbours = scratch->neighbours;
991 int x, y;
992
993 for (y = 0; y < cr; y++)
994 for (x = 0; x < cr; x++) {
995 int count, t, n;
996
997 /*
998 * If this square doesn't have exactly two candidate
999 * numbers, don't try it.
1000 *
1001 * In this loop we also sum the candidate numbers,
1002 * which is a nasty hack to allow us to quickly find
1003 * `the other one' (since we will shortly know there
1004 * are exactly two).
1005 */
1006 for (count = t = 0, n = 1; n <= cr; n++)
1007 if (cube(x, y, n))
1008 count++, t += n;
1009 if (count != 2)
1010 continue;
1011
1012 /*
1013 * Now attempt a bfs for each candidate.
1014 */
1015 for (n = 1; n <= cr; n++)
1016 if (cube(x, y, n)) {
1017 int orign, currn, head, tail;
1018
1019 /*
1020 * Begin a bfs.
1021 */
1022 orign = n;
1023
1024 memset(number, cr+1, cr*cr);
1025 head = tail = 0;
1026 bfsqueue[tail++] = y*cr+x;
1027 #ifdef STANDALONE_SOLVER
1028 bfsprev[y*cr+x] = -1;
1029 #endif
1030 number[y*cr+x] = t - n;
1031
1032 while (head < tail) {
1033 int xx, yy, nneighbours, xt, yt, i;
1034
1035 xx = bfsqueue[head++];
1036 yy = xx / cr;
1037 xx %= cr;
1038
1039 currn = number[yy*cr+xx];
1040
1041 /*
1042 * Find neighbours of yy,xx.
1043 */
1044 nneighbours = 0;
1045 for (yt = 0; yt < cr; yt++)
1046 neighbours[nneighbours++] = yt*cr+xx;
1047 for (xt = 0; xt < cr; xt++)
1048 neighbours[nneighbours++] = yy*cr+xt;
1049 xt = usage->blocks->whichblock[yy*cr+xx];
1050 for (yt = 0; yt < cr; yt++)
1051 neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1052 if (usage->diag) {
1053 int sqindex = yy*cr+xx;
1054 if (ondiag0(sqindex)) {
1055 for (i = 0; i < cr; i++)
1056 neighbours[nneighbours++] = diag0(i);
1057 }
1058 if (ondiag1(sqindex)) {
1059 for (i = 0; i < cr; i++)
1060 neighbours[nneighbours++] = diag1(i);
1061 }
1062 }
1063
1064 /*
1065 * Try visiting each of those neighbours.
1066 */
1067 for (i = 0; i < nneighbours; i++) {
1068 int cc, tt, nn;
1069
1070 xt = neighbours[i] % cr;
1071 yt = neighbours[i] / cr;
1072
1073 /*
1074 * We need this square to not be
1075 * already visited, and to include
1076 * currn as a possible number.
1077 */
1078 if (number[yt*cr+xt] <= cr)
1079 continue;
1080 if (!cube(xt, yt, currn))
1081 continue;
1082
1083 /*
1084 * Don't visit _this_ square a second
1085 * time!
1086 */
1087 if (xt == xx && yt == yy)
1088 continue;
1089
1090 /*
1091 * To continue with the bfs, we need
1092 * this square to have exactly two
1093 * possible numbers.
1094 */
1095 for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1096 if (cube(xt, yt, nn))
1097 cc++, tt += nn;
1098 if (cc == 2) {
1099 bfsqueue[tail++] = yt*cr+xt;
1100 #ifdef STANDALONE_SOLVER
1101 bfsprev[yt*cr+xt] = yy*cr+xx;
1102 #endif
1103 number[yt*cr+xt] = tt - currn;
1104 }
1105
1106 /*
1107 * One other possibility is that this
1108 * might be the square in which we can
1109 * make a real deduction: if it's
1110 * adjacent to x,y, and currn is equal
1111 * to the original number we ruled out.
1112 */
1113 if (currn == orign &&
1114 (xt == x || yt == y ||
1115 (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1116 (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1117 (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1118 #ifdef STANDALONE_SOLVER
1119 if (solver_show_working) {
1120 char *sep = "";
1121 int xl, yl;
1122 printf("%*sforcing chain, %d at ends of ",
1123 solver_recurse_depth*4, "", orign);
1124 xl = xx;
1125 yl = yy;
1126 while (1) {
1127 printf("%s(%d,%d)", sep, 1+xl,
1128 1+yl);
1129 xl = bfsprev[yl*cr+xl];
1130 if (xl < 0)
1131 break;
1132 yl = xl / cr;
1133 xl %= cr;
1134 sep = "-";
1135 }
1136 printf("\n%*s ruling out %d at (%d,%d)\n",
1137 solver_recurse_depth*4, "",
1138 orign, 1+xt, 1+yt);
1139 }
1140 #endif
1141 cube(xt, yt, orign) = FALSE;
1142 return 1;
1143 }
1144 }
1145 }
1146 }
1147 }
1148
1149 return 0;
1150 }
1151
1152 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1153 {
1154 struct solver_scratch *scratch = snew(struct solver_scratch);
1155 int cr = usage->cr;
1156 scratch->grid = snewn(cr*cr, unsigned char);
1157 scratch->rowidx = snewn(cr, unsigned char);
1158 scratch->colidx = snewn(cr, unsigned char);
1159 scratch->set = snewn(cr, unsigned char);
1160 scratch->neighbours = snewn(5*cr, int);
1161 scratch->bfsqueue = snewn(cr*cr, int);
1162 #ifdef STANDALONE_SOLVER
1163 scratch->bfsprev = snewn(cr*cr, int);
1164 #endif
1165 scratch->indexlist = snewn(cr*cr, int); /* used for set elimination */
1166 scratch->indexlist2 = snewn(cr, int); /* only used for intersect() */
1167 return scratch;
1168 }
1169
1170 static void solver_free_scratch(struct solver_scratch *scratch)
1171 {
1172 #ifdef STANDALONE_SOLVER
1173 sfree(scratch->bfsprev);
1174 #endif
1175 sfree(scratch->bfsqueue);
1176 sfree(scratch->neighbours);
1177 sfree(scratch->set);
1178 sfree(scratch->colidx);
1179 sfree(scratch->rowidx);
1180 sfree(scratch->grid);
1181 sfree(scratch->indexlist);
1182 sfree(scratch->indexlist2);
1183 sfree(scratch);
1184 }
1185
1186 static int solver(int cr, struct block_structure *blocks, int xtype,
1187 digit *grid, int maxdiff)
1188 {
1189 struct solver_usage *usage;
1190 struct solver_scratch *scratch;
1191 int x, y, b, i, n, ret;
1192 int diff = DIFF_BLOCK;
1193
1194 /*
1195 * Set up a usage structure as a clean slate (everything
1196 * possible).
1197 */
1198 usage = snew(struct solver_usage);
1199 usage->cr = cr;
1200 usage->blocks = blocks;
1201 usage->cube = snewn(cr*cr*cr, unsigned char);
1202 usage->grid = grid; /* write straight back to the input */
1203 memset(usage->cube, TRUE, cr*cr*cr);
1204
1205 usage->row = snewn(cr * cr, unsigned char);
1206 usage->col = snewn(cr * cr, unsigned char);
1207 usage->blk = snewn(cr * cr, unsigned char);
1208 memset(usage->row, FALSE, cr * cr);
1209 memset(usage->col, FALSE, cr * cr);
1210 memset(usage->blk, FALSE, cr * cr);
1211
1212 if (xtype) {
1213 usage->diag = snewn(cr * 2, unsigned char);
1214 memset(usage->diag, FALSE, cr * 2);
1215 } else
1216 usage->diag = NULL;
1217
1218 scratch = solver_new_scratch(usage);
1219
1220 /*
1221 * Place all the clue numbers we are given.
1222 */
1223 for (x = 0; x < cr; x++)
1224 for (y = 0; y < cr; y++)
1225 if (grid[y*cr+x])
1226 solver_place(usage, x, y, grid[y*cr+x]);
1227
1228 /*
1229 * Now loop over the grid repeatedly trying all permitted modes
1230 * of reasoning. The loop terminates if we complete an
1231 * iteration without making any progress; we then return
1232 * failure or success depending on whether the grid is full or
1233 * not.
1234 */
1235 while (1) {
1236 /*
1237 * I'd like to write `continue;' inside each of the
1238 * following loops, so that the solver returns here after
1239 * making some progress. However, I can't specify that I
1240 * want to continue an outer loop rather than the innermost
1241 * one, so I'm apologetically resorting to a goto.
1242 */
1243 cont:
1244
1245 /*
1246 * Blockwise positional elimination.
1247 */
1248 for (b = 0; b < cr; b++)
1249 for (n = 1; n <= cr; n++)
1250 if (!usage->blk[b*cr+n-1]) {
1251 for (i = 0; i < cr; i++)
1252 scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1253 ret = solver_elim(usage, scratch->indexlist
1254 #ifdef STANDALONE_SOLVER
1255 , "positional elimination,"
1256 " %d in block %s", n,
1257 usage->blocks->blocknames[b]
1258 #endif
1259 );
1260 if (ret < 0) {
1261 diff = DIFF_IMPOSSIBLE;
1262 goto got_result;
1263 } else if (ret > 0) {
1264 diff = max(diff, DIFF_BLOCK);
1265 goto cont;
1266 }
1267 }
1268
1269 if (maxdiff <= DIFF_BLOCK)
1270 break;
1271
1272 /*
1273 * Row-wise positional elimination.
1274 */
1275 for (y = 0; y < cr; y++)
1276 for (n = 1; n <= cr; n++)
1277 if (!usage->row[y*cr+n-1]) {
1278 for (x = 0; x < cr; x++)
1279 scratch->indexlist[x] = cubepos(x, y, n);
1280 ret = solver_elim(usage, scratch->indexlist
1281 #ifdef STANDALONE_SOLVER
1282 , "positional elimination,"
1283 " %d in row %d", n, 1+y
1284 #endif
1285 );
1286 if (ret < 0) {
1287 diff = DIFF_IMPOSSIBLE;
1288 goto got_result;
1289 } else if (ret > 0) {
1290 diff = max(diff, DIFF_SIMPLE);
1291 goto cont;
1292 }
1293 }
1294 /*
1295 * Column-wise positional elimination.
1296 */
1297 for (x = 0; x < cr; x++)
1298 for (n = 1; n <= cr; n++)
1299 if (!usage->col[x*cr+n-1]) {
1300 for (y = 0; y < cr; y++)
1301 scratch->indexlist[y] = cubepos(x, y, n);
1302 ret = solver_elim(usage, scratch->indexlist
1303 #ifdef STANDALONE_SOLVER
1304 , "positional elimination,"
1305 " %d in column %d", n, 1+x
1306 #endif
1307 );
1308 if (ret < 0) {
1309 diff = DIFF_IMPOSSIBLE;
1310 goto got_result;
1311 } else if (ret > 0) {
1312 diff = max(diff, DIFF_SIMPLE);
1313 goto cont;
1314 }
1315 }
1316
1317 /*
1318 * X-diagonal positional elimination.
1319 */
1320 if (usage->diag) {
1321 for (n = 1; n <= cr; n++)
1322 if (!usage->diag[n-1]) {
1323 for (i = 0; i < cr; i++)
1324 scratch->indexlist[i] = cubepos2(diag0(i), n);
1325 ret = solver_elim(usage, scratch->indexlist
1326 #ifdef STANDALONE_SOLVER
1327 , "positional elimination,"
1328 " %d in \\-diagonal", n
1329 #endif
1330 );
1331 if (ret < 0) {
1332 diff = DIFF_IMPOSSIBLE;
1333 goto got_result;
1334 } else if (ret > 0) {
1335 diff = max(diff, DIFF_SIMPLE);
1336 goto cont;
1337 }
1338 }
1339 for (n = 1; n <= cr; n++)
1340 if (!usage->diag[cr+n-1]) {
1341 for (i = 0; i < cr; i++)
1342 scratch->indexlist[i] = cubepos2(diag1(i), n);
1343 ret = solver_elim(usage, scratch->indexlist
1344 #ifdef STANDALONE_SOLVER
1345 , "positional elimination,"
1346 " %d in /-diagonal", n
1347 #endif
1348 );
1349 if (ret < 0) {
1350 diff = DIFF_IMPOSSIBLE;
1351 goto got_result;
1352 } else if (ret > 0) {
1353 diff = max(diff, DIFF_SIMPLE);
1354 goto cont;
1355 }
1356 }
1357 }
1358
1359 /*
1360 * Numeric elimination.
1361 */
1362 for (x = 0; x < cr; x++)
1363 for (y = 0; y < cr; y++)
1364 if (!usage->grid[y*cr+x]) {
1365 for (n = 1; n <= cr; n++)
1366 scratch->indexlist[n-1] = cubepos(x, y, n);
1367 ret = solver_elim(usage, scratch->indexlist
1368 #ifdef STANDALONE_SOLVER
1369 , "numeric elimination at (%d,%d)",
1370 1+x, 1+y
1371 #endif
1372 );
1373 if (ret < 0) {
1374 diff = DIFF_IMPOSSIBLE;
1375 goto got_result;
1376 } else if (ret > 0) {
1377 diff = max(diff, DIFF_SIMPLE);
1378 goto cont;
1379 }
1380 }
1381
1382 if (maxdiff <= DIFF_SIMPLE)
1383 break;
1384
1385 /*
1386 * Intersectional analysis, rows vs blocks.
1387 */
1388 for (y = 0; y < cr; y++)
1389 for (b = 0; b < cr; b++)
1390 for (n = 1; n <= cr; n++) {
1391 if (usage->row[y*cr+n-1] ||
1392 usage->blk[b*cr+n-1])
1393 continue;
1394 for (i = 0; i < cr; i++) {
1395 scratch->indexlist[i] = cubepos(i, y, n);
1396 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1397 }
1398 /*
1399 * solver_intersect() never returns -1.
1400 */
1401 if (solver_intersect(usage, scratch->indexlist,
1402 scratch->indexlist2
1403 #ifdef STANDALONE_SOLVER
1404 , "intersectional analysis,"
1405 " %d in row %d vs block %s",
1406 n, 1+y, usage->blocks->blocknames[b]
1407 #endif
1408 ) ||
1409 solver_intersect(usage, scratch->indexlist2,
1410 scratch->indexlist
1411 #ifdef STANDALONE_SOLVER
1412 , "intersectional analysis,"
1413 " %d in block %s vs row %d",
1414 n, usage->blocks->blocknames[b], 1+y
1415 #endif
1416 )) {
1417 diff = max(diff, DIFF_INTERSECT);
1418 goto cont;
1419 }
1420 }
1421
1422 /*
1423 * Intersectional analysis, columns vs blocks.
1424 */
1425 for (x = 0; x < cr; x++)
1426 for (b = 0; b < cr; b++)
1427 for (n = 1; n <= cr; n++) {
1428 if (usage->col[x*cr+n-1] ||
1429 usage->blk[b*cr+n-1])
1430 continue;
1431 for (i = 0; i < cr; i++) {
1432 scratch->indexlist[i] = cubepos(x, i, n);
1433 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1434 }
1435 if (solver_intersect(usage, scratch->indexlist,
1436 scratch->indexlist2
1437 #ifdef STANDALONE_SOLVER
1438 , "intersectional analysis,"
1439 " %d in column %d vs block %s",
1440 n, 1+x, usage->blocks->blocknames[b]
1441 #endif
1442 ) ||
1443 solver_intersect(usage, scratch->indexlist2,
1444 scratch->indexlist
1445 #ifdef STANDALONE_SOLVER
1446 , "intersectional analysis,"
1447 " %d in block %s vs column %d",
1448 n, usage->blocks->blocknames[b], 1+x
1449 #endif
1450 )) {
1451 diff = max(diff, DIFF_INTERSECT);
1452 goto cont;
1453 }
1454 }
1455
1456 if (usage->diag) {
1457 /*
1458 * Intersectional analysis, \-diagonal vs blocks.
1459 */
1460 for (b = 0; b < cr; b++)
1461 for (n = 1; n <= cr; n++) {
1462 if (usage->diag[n-1] ||
1463 usage->blk[b*cr+n-1])
1464 continue;
1465 for (i = 0; i < cr; i++) {
1466 scratch->indexlist[i] = cubepos2(diag0(i), n);
1467 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1468 }
1469 if (solver_intersect(usage, scratch->indexlist,
1470 scratch->indexlist2
1471 #ifdef STANDALONE_SOLVER
1472 , "intersectional analysis,"
1473 " %d in \\-diagonal vs block %s",
1474 n, 1+x, usage->blocks->blocknames[b]
1475 #endif
1476 ) ||
1477 solver_intersect(usage, scratch->indexlist2,
1478 scratch->indexlist
1479 #ifdef STANDALONE_SOLVER
1480 , "intersectional analysis,"
1481 " %d in block %s vs \\-diagonal",
1482 n, usage->blocks->blocknames[b], 1+x
1483 #endif
1484 )) {
1485 diff = max(diff, DIFF_INTERSECT);
1486 goto cont;
1487 }
1488 }
1489
1490 /*
1491 * Intersectional analysis, /-diagonal vs blocks.
1492 */
1493 for (b = 0; b < cr; b++)
1494 for (n = 1; n <= cr; n++) {
1495 if (usage->diag[cr+n-1] ||
1496 usage->blk[b*cr+n-1])
1497 continue;
1498 for (i = 0; i < cr; i++) {
1499 scratch->indexlist[i] = cubepos2(diag1(i), n);
1500 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1501 }
1502 if (solver_intersect(usage, scratch->indexlist,
1503 scratch->indexlist2
1504 #ifdef STANDALONE_SOLVER
1505 , "intersectional analysis,"
1506 " %d in /-diagonal vs block %s",
1507 n, 1+x, usage->blocks->blocknames[b]
1508 #endif
1509 ) ||
1510 solver_intersect(usage, scratch->indexlist2,
1511 scratch->indexlist
1512 #ifdef STANDALONE_SOLVER
1513 , "intersectional analysis,"
1514 " %d in block %s vs /-diagonal",
1515 n, usage->blocks->blocknames[b], 1+x
1516 #endif
1517 )) {
1518 diff = max(diff, DIFF_INTERSECT);
1519 goto cont;
1520 }
1521 }
1522 }
1523
1524 if (maxdiff <= DIFF_INTERSECT)
1525 break;
1526
1527 /*
1528 * Blockwise set elimination.
1529 */
1530 for (b = 0; b < cr; b++) {
1531 for (i = 0; i < cr; i++)
1532 for (n = 1; n <= cr; n++)
1533 scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
1534 ret = solver_set(usage, scratch, scratch->indexlist
1535 #ifdef STANDALONE_SOLVER
1536 , "set elimination, block %s",
1537 usage->blocks->blocknames[b]
1538 #endif
1539 );
1540 if (ret < 0) {
1541 diff = DIFF_IMPOSSIBLE;
1542 goto got_result;
1543 } else if (ret > 0) {
1544 diff = max(diff, DIFF_SET);
1545 goto cont;
1546 }
1547 }
1548
1549 /*
1550 * Row-wise set elimination.
1551 */
1552 for (y = 0; y < cr; y++) {
1553 for (x = 0; x < cr; x++)
1554 for (n = 1; n <= cr; n++)
1555 scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
1556 ret = solver_set(usage, scratch, scratch->indexlist
1557 #ifdef STANDALONE_SOLVER
1558 , "set elimination, row %d", 1+y
1559 #endif
1560 );
1561 if (ret < 0) {
1562 diff = DIFF_IMPOSSIBLE;
1563 goto got_result;
1564 } else if (ret > 0) {
1565 diff = max(diff, DIFF_SET);
1566 goto cont;
1567 }
1568 }
1569
1570 /*
1571 * Column-wise set elimination.
1572 */
1573 for (x = 0; x < cr; x++) {
1574 for (y = 0; y < cr; y++)
1575 for (n = 1; n <= cr; n++)
1576 scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
1577 ret = solver_set(usage, scratch, scratch->indexlist
1578 #ifdef STANDALONE_SOLVER
1579 , "set elimination, column %d", 1+x
1580 #endif
1581 );
1582 if (ret < 0) {
1583 diff = DIFF_IMPOSSIBLE;
1584 goto got_result;
1585 } else if (ret > 0) {
1586 diff = max(diff, DIFF_SET);
1587 goto cont;
1588 }
1589 }
1590
1591 if (usage->diag) {
1592 /*
1593 * \-diagonal set elimination.
1594 */
1595 for (i = 0; i < cr; i++)
1596 for (n = 1; n <= cr; n++)
1597 scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
1598 ret = solver_set(usage, scratch, scratch->indexlist
1599 #ifdef STANDALONE_SOLVER
1600 , "set elimination, \\-diagonal"
1601 #endif
1602 );
1603 if (ret < 0) {
1604 diff = DIFF_IMPOSSIBLE;
1605 goto got_result;
1606 } else if (ret > 0) {
1607 diff = max(diff, DIFF_SET);
1608 goto cont;
1609 }
1610
1611 /*
1612 * /-diagonal set elimination.
1613 */
1614 for (i = 0; i < cr; i++)
1615 for (n = 1; n <= cr; n++)
1616 scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
1617 ret = solver_set(usage, scratch, scratch->indexlist
1618 #ifdef STANDALONE_SOLVER
1619 , "set elimination, \\-diagonal"
1620 #endif
1621 );
1622 if (ret < 0) {
1623 diff = DIFF_IMPOSSIBLE;
1624 goto got_result;
1625 } else if (ret > 0) {
1626 diff = max(diff, DIFF_SET);
1627 goto cont;
1628 }
1629 }
1630
1631 if (maxdiff <= DIFF_SET)
1632 break;
1633
1634 /*
1635 * Row-vs-column set elimination on a single number.
1636 */
1637 for (n = 1; n <= cr; n++) {
1638 for (y = 0; y < cr; y++)
1639 for (x = 0; x < cr; x++)
1640 scratch->indexlist[y*cr+x] = cubepos(x, y, n);
1641 ret = solver_set(usage, scratch, scratch->indexlist
1642 #ifdef STANDALONE_SOLVER
1643 , "positional set elimination, number %d", n
1644 #endif
1645 );
1646 if (ret < 0) {
1647 diff = DIFF_IMPOSSIBLE;
1648 goto got_result;
1649 } else if (ret > 0) {
1650 diff = max(diff, DIFF_EXTREME);
1651 goto cont;
1652 }
1653 }
1654
1655 /*
1656 * Forcing chains.
1657 */
1658 if (solver_forcing(usage, scratch)) {
1659 diff = max(diff, DIFF_EXTREME);
1660 goto cont;
1661 }
1662
1663 /*
1664 * If we reach here, we have made no deductions in this
1665 * iteration, so the algorithm terminates.
1666 */
1667 break;
1668 }
1669
1670 /*
1671 * Last chance: if we haven't fully solved the puzzle yet, try
1672 * recursing based on guesses for a particular square. We pick
1673 * one of the most constrained empty squares we can find, which
1674 * has the effect of pruning the search tree as much as
1675 * possible.
1676 */
1677 if (maxdiff >= DIFF_RECURSIVE) {
1678 int best, bestcount;
1679
1680 best = -1;
1681 bestcount = cr+1;
1682
1683 for (y = 0; y < cr; y++)
1684 for (x = 0; x < cr; x++)
1685 if (!grid[y*cr+x]) {
1686 int count;
1687
1688 /*
1689 * An unfilled square. Count the number of
1690 * possible digits in it.
1691 */
1692 count = 0;
1693 for (n = 1; n <= cr; n++)
1694 if (cube(x,y,n))
1695 count++;
1696
1697 /*
1698 * We should have found any impossibilities
1699 * already, so this can safely be an assert.
1700 */
1701 assert(count > 1);
1702
1703 if (count < bestcount) {
1704 bestcount = count;
1705 best = y*cr+x;
1706 }
1707 }
1708
1709 if (best != -1) {
1710 int i, j;
1711 digit *list, *ingrid, *outgrid;
1712
1713 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
1714
1715 /*
1716 * Attempt recursion.
1717 */
1718 y = best / cr;
1719 x = best % cr;
1720
1721 list = snewn(cr, digit);
1722 ingrid = snewn(cr * cr, digit);
1723 outgrid = snewn(cr * cr, digit);
1724 memcpy(ingrid, grid, cr * cr);
1725
1726 /* Make a list of the possible digits. */
1727 for (j = 0, n = 1; n <= cr; n++)
1728 if (cube(x,y,n))
1729 list[j++] = n;
1730
1731 #ifdef STANDALONE_SOLVER
1732 if (solver_show_working) {
1733 char *sep = "";
1734 printf("%*srecursing on (%d,%d) [",
1735 solver_recurse_depth*4, "", x + 1, y + 1);
1736 for (i = 0; i < j; i++) {
1737 printf("%s%d", sep, list[i]);
1738 sep = " or ";
1739 }
1740 printf("]\n");
1741 }
1742 #endif
1743
1744 /*
1745 * And step along the list, recursing back into the
1746 * main solver at every stage.
1747 */
1748 for (i = 0; i < j; i++) {
1749 int ret;
1750
1751 memcpy(outgrid, ingrid, cr * cr);
1752 outgrid[y*cr+x] = list[i];
1753
1754 #ifdef STANDALONE_SOLVER
1755 if (solver_show_working)
1756 printf("%*sguessing %d at (%d,%d)\n",
1757 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1758 solver_recurse_depth++;
1759 #endif
1760
1761 ret = solver(cr, blocks, xtype, outgrid, maxdiff);
1762
1763 #ifdef STANDALONE_SOLVER
1764 solver_recurse_depth--;
1765 if (solver_show_working) {
1766 printf("%*sretracting %d at (%d,%d)\n",
1767 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1768 }
1769 #endif
1770
1771 /*
1772 * If we have our first solution, copy it into the
1773 * grid we will return.
1774 */
1775 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1776 memcpy(grid, outgrid, cr*cr);
1777
1778 if (ret == DIFF_AMBIGUOUS)
1779 diff = DIFF_AMBIGUOUS;
1780 else if (ret == DIFF_IMPOSSIBLE)
1781 /* do not change our return value */;
1782 else {
1783 /* the recursion turned up exactly one solution */
1784 if (diff == DIFF_IMPOSSIBLE)
1785 diff = DIFF_RECURSIVE;
1786 else
1787 diff = DIFF_AMBIGUOUS;
1788 }
1789
1790 /*
1791 * As soon as we've found more than one solution,
1792 * give up immediately.
1793 */
1794 if (diff == DIFF_AMBIGUOUS)
1795 break;
1796 }
1797
1798 sfree(outgrid);
1799 sfree(ingrid);
1800 sfree(list);
1801 }
1802
1803 } else {
1804 /*
1805 * We're forbidden to use recursion, so we just see whether
1806 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1807 * otherwise.
1808 */
1809 for (y = 0; y < cr; y++)
1810 for (x = 0; x < cr; x++)
1811 if (!grid[y*cr+x])
1812 diff = DIFF_IMPOSSIBLE;
1813 }
1814
1815 got_result:;
1816
1817 #ifdef STANDALONE_SOLVER
1818 if (solver_show_working)
1819 printf("%*s%s found\n",
1820 solver_recurse_depth*4, "",
1821 diff == DIFF_IMPOSSIBLE ? "no solution" :
1822 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1823 "one solution");
1824 #endif
1825
1826 sfree(usage->cube);
1827 sfree(usage->row);
1828 sfree(usage->col);
1829 sfree(usage->blk);
1830 sfree(usage);
1831
1832 solver_free_scratch(scratch);
1833
1834 return diff;
1835 }
1836
1837 /* ----------------------------------------------------------------------
1838 * End of solver code.
1839 */
1840
1841 /* ----------------------------------------------------------------------
1842 * Solo filled-grid generator.
1843 *
1844 * This grid generator works by essentially trying to solve a grid
1845 * starting from no clues, and not worrying that there's more than
1846 * one possible solution. Unfortunately, it isn't computationally
1847 * feasible to do this by calling the above solver with an empty
1848 * grid, because that one needs to allocate a lot of scratch space
1849 * at every recursion level. Instead, I have a much simpler
1850 * algorithm which I shamelessly copied from a Python solver
1851 * written by Andrew Wilkinson (which is GPLed, but I've reused
1852 * only ideas and no code). It mostly just does the obvious
1853 * recursive thing: pick an empty square, put one of the possible
1854 * digits in it, recurse until all squares are filled, backtrack
1855 * and change some choices if necessary.
1856 *
1857 * The clever bit is that every time it chooses which square to
1858 * fill in next, it does so by counting the number of _possible_
1859 * numbers that can go in each square, and it prioritises so that
1860 * it picks a square with the _lowest_ number of possibilities. The
1861 * idea is that filling in lots of the obvious bits (particularly
1862 * any squares with only one possibility) will cut down on the list
1863 * of possibilities for other squares and hence reduce the enormous
1864 * search space as much as possible as early as possible.
1865 */
1866
1867 /*
1868 * Internal data structure used in gridgen to keep track of
1869 * progress.
1870 */
1871 struct gridgen_coord { int x, y, r; };
1872 struct gridgen_usage {
1873 int cr;
1874 struct block_structure *blocks;
1875 /* grid is a copy of the input grid, modified as we go along */
1876 digit *grid;
1877 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1878 unsigned char *row;
1879 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1880 unsigned char *col;
1881 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1882 unsigned char *blk;
1883 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
1884 unsigned char *diag;
1885 /* This lists all the empty spaces remaining in the grid. */
1886 struct gridgen_coord *spaces;
1887 int nspaces;
1888 /* If we need randomisation in the solve, this is our random state. */
1889 random_state *rs;
1890 };
1891
1892 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n,
1893 int placing)
1894 {
1895 int cr = usage->cr;
1896 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
1897 usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n-1] = placing;
1898 if (usage->diag) {
1899 if (ondiag0(y*cr+x))
1900 usage->diag[n-1] = placing;
1901 if (ondiag1(y*cr+x))
1902 usage->diag[cr+n-1] = placing;
1903 }
1904 usage->grid[y*cr+x] = placing ? n : 0;
1905 }
1906
1907 /*
1908 * The real recursive step in the generating function.
1909 *
1910 * Return values: 1 means solution found, 0 means no solution
1911 * found on this branch.
1912 */
1913 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
1914 {
1915 int cr = usage->cr;
1916 int i, j, n, sx, sy, bestm, bestr, ret;
1917 int *digits;
1918
1919 /*
1920 * Firstly, check for completion! If there are no spaces left
1921 * in the grid, we have a solution.
1922 */
1923 if (usage->nspaces == 0)
1924 return TRUE;
1925
1926 /*
1927 * Next, abandon generation if we went over our steps limit.
1928 */
1929 if (*steps <= 0)
1930 return FALSE;
1931 (*steps)--;
1932
1933 /*
1934 * Otherwise, there must be at least one space. Find the most
1935 * constrained space, using the `r' field as a tie-breaker.
1936 */
1937 bestm = cr+1; /* so that any space will beat it */
1938 bestr = 0;
1939 i = sx = sy = -1;
1940 for (j = 0; j < usage->nspaces; j++) {
1941 int x = usage->spaces[j].x, y = usage->spaces[j].y;
1942 int m;
1943
1944 /*
1945 * Find the number of digits that could go in this space.
1946 */
1947 m = 0;
1948 for (n = 0; n < cr; n++)
1949 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1950 !usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n] &&
1951 (!usage->diag || ((!ondiag0(y*cr+x) || !usage->diag[n]) &&
1952 (!ondiag1(y*cr+x) || !usage->diag[cr+n]))))
1953 m++;
1954
1955 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1956 bestm = m;
1957 bestr = usage->spaces[j].r;
1958 sx = x;
1959 sy = y;
1960 i = j;
1961 }
1962 }
1963
1964 /*
1965 * Swap that square into the final place in the spaces array,
1966 * so that decrementing nspaces will remove it from the list.
1967 */
1968 if (i != usage->nspaces-1) {
1969 struct gridgen_coord t;
1970 t = usage->spaces[usage->nspaces-1];
1971 usage->spaces[usage->nspaces-1] = usage->spaces[i];
1972 usage->spaces[i] = t;
1973 }
1974
1975 /*
1976 * Now we've decided which square to start our recursion at,
1977 * simply go through all possible values, shuffling them
1978 * randomly first if necessary.
1979 */
1980 digits = snewn(bestm, int);
1981 j = 0;
1982 for (n = 0; n < cr; n++)
1983 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1984 !usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n] &&
1985 (!usage->diag || ((!ondiag0(sy*cr+sx) || !usage->diag[n]) &&
1986 (!ondiag1(sy*cr+sx) || !usage->diag[cr+n])))) {
1987 digits[j++] = n+1;
1988 }
1989
1990 if (usage->rs)
1991 shuffle(digits, j, sizeof(*digits), usage->rs);
1992
1993 /* And finally, go through the digit list and actually recurse. */
1994 ret = FALSE;
1995 for (i = 0; i < j; i++) {
1996 n = digits[i];
1997
1998 /* Update the usage structure to reflect the placing of this digit. */
1999 gridgen_place(usage, sx, sy, n, TRUE);
2000 usage->nspaces--;
2001
2002 /* Call the solver recursively. Stop when we find a solution. */
2003 if (gridgen_real(usage, grid, steps)) {
2004 ret = TRUE;
2005 break;
2006 }
2007
2008 /* Revert the usage structure. */
2009 gridgen_place(usage, sx, sy, n, FALSE);
2010 usage->nspaces++;
2011 }
2012
2013 sfree(digits);
2014 return ret;
2015 }
2016
2017 /*
2018 * Entry point to generator. You give it parameters and a starting
2019 * grid, which is simply an array of cr*cr digits.
2020 */
2021 static int gridgen(int cr, struct block_structure *blocks, int xtype,
2022 digit *grid, random_state *rs, int maxsteps)
2023 {
2024 struct gridgen_usage *usage;
2025 int x, y, ret;
2026
2027 /*
2028 * Clear the grid to start with.
2029 */
2030 memset(grid, 0, cr*cr);
2031
2032 /*
2033 * Create a gridgen_usage structure.
2034 */
2035 usage = snew(struct gridgen_usage);
2036
2037 usage->cr = cr;
2038 usage->blocks = blocks;
2039
2040 usage->grid = grid;
2041
2042 usage->row = snewn(cr * cr, unsigned char);
2043 usage->col = snewn(cr * cr, unsigned char);
2044 usage->blk = snewn(cr * cr, unsigned char);
2045 memset(usage->row, FALSE, cr * cr);
2046 memset(usage->col, FALSE, cr * cr);
2047 memset(usage->blk, FALSE, cr * cr);
2048
2049 if (xtype) {
2050 usage->diag = snewn(2 * cr, unsigned char);
2051 memset(usage->diag, FALSE, 2 * cr);
2052 } else {
2053 usage->diag = NULL;
2054 }
2055
2056 /*
2057 * Begin by filling in the whole top row with randomly chosen
2058 * numbers. This cannot introduce any bias or restriction on
2059 * the available grids, since we already know those numbers
2060 * are all distinct so all we're doing is choosing their
2061 * labels.
2062 */
2063 for (x = 0; x < cr; x++)
2064 grid[x] = x+1;
2065 shuffle(grid, cr, sizeof(*grid), rs);
2066 for (x = 0; x < cr; x++)
2067 gridgen_place(usage, x, 0, grid[x], TRUE);
2068
2069 usage->spaces = snewn(cr * cr, struct gridgen_coord);
2070 usage->nspaces = 0;
2071
2072 usage->rs = rs;
2073
2074 /*
2075 * Initialise the list of grid spaces, taking care to leave
2076 * out the row I've already filled in above.
2077 */
2078 for (y = 1; y < cr; y++) {
2079 for (x = 0; x < cr; x++) {
2080 usage->spaces[usage->nspaces].x = x;
2081 usage->spaces[usage->nspaces].y = y;
2082 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2083 usage->nspaces++;
2084 }
2085 }
2086
2087 /*
2088 * Run the real generator function.
2089 */
2090 ret = gridgen_real(usage, grid, &maxsteps);
2091
2092 /*
2093 * Clean up the usage structure now we have our answer.
2094 */
2095 sfree(usage->spaces);
2096 sfree(usage->blk);
2097 sfree(usage->col);
2098 sfree(usage->row);
2099 sfree(usage);
2100
2101 return ret;
2102 }
2103
2104 /* ----------------------------------------------------------------------
2105 * End of grid generator code.
2106 */
2107
2108 /*
2109 * Check whether a grid contains a valid complete puzzle.
2110 */
2111 static int check_valid(int cr, struct block_structure *blocks, int xtype,
2112 digit *grid)
2113 {
2114 unsigned char *used;
2115 int x, y, i, j, n;
2116
2117 used = snewn(cr, unsigned char);
2118
2119 /*
2120 * Check that each row contains precisely one of everything.
2121 */
2122 for (y = 0; y < cr; y++) {
2123 memset(used, FALSE, cr);
2124 for (x = 0; x < cr; x++)
2125 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2126 used[grid[y*cr+x]-1] = TRUE;
2127 for (n = 0; n < cr; n++)
2128 if (!used[n]) {
2129 sfree(used);
2130 return FALSE;
2131 }
2132 }
2133
2134 /*
2135 * Check that each column contains precisely one of everything.
2136 */
2137 for (x = 0; x < cr; x++) {
2138 memset(used, FALSE, cr);
2139 for (y = 0; y < cr; y++)
2140 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2141 used[grid[y*cr+x]-1] = TRUE;
2142 for (n = 0; n < cr; n++)
2143 if (!used[n]) {
2144 sfree(used);
2145 return FALSE;
2146 }
2147 }
2148
2149 /*
2150 * Check that each block contains precisely one of everything.
2151 */
2152 for (i = 0; i < cr; i++) {
2153 memset(used, FALSE, cr);
2154 for (j = 0; j < cr; j++)
2155 if (grid[blocks->blocks[i][j]] > 0 &&
2156 grid[blocks->blocks[i][j]] <= cr)
2157 used[grid[blocks->blocks[i][j]]-1] = TRUE;
2158 for (n = 0; n < cr; n++)
2159 if (!used[n]) {
2160 sfree(used);
2161 return FALSE;
2162 }
2163 }
2164
2165 /*
2166 * Check that each diagonal contains precisely one of everything.
2167 */
2168 if (xtype) {
2169 memset(used, FALSE, cr);
2170 for (i = 0; i < cr; i++)
2171 if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
2172 used[grid[diag0(i)]-1] = TRUE;
2173 for (n = 0; n < cr; n++)
2174 if (!used[n]) {
2175 sfree(used);
2176 return FALSE;
2177 }
2178 for (i = 0; i < cr; i++)
2179 if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
2180 used[grid[diag1(i)]-1] = TRUE;
2181 for (n = 0; n < cr; n++)
2182 if (!used[n]) {
2183 sfree(used);
2184 return FALSE;
2185 }
2186 }
2187
2188 sfree(used);
2189 return TRUE;
2190 }
2191
2192 static int symmetries(game_params *params, int x, int y, int *output, int s)
2193 {
2194 int c = params->c, r = params->r, cr = c*r;
2195 int i = 0;
2196
2197 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2198
2199 ADD(x, y);
2200
2201 switch (s) {
2202 case SYMM_NONE:
2203 break; /* just x,y is all we need */
2204 case SYMM_ROT2:
2205 ADD(cr - 1 - x, cr - 1 - y);
2206 break;
2207 case SYMM_ROT4:
2208 ADD(cr - 1 - y, x);
2209 ADD(y, cr - 1 - x);
2210 ADD(cr - 1 - x, cr - 1 - y);
2211 break;
2212 case SYMM_REF2:
2213 ADD(cr - 1 - x, y);
2214 break;
2215 case SYMM_REF2D:
2216 ADD(y, x);
2217 break;
2218 case SYMM_REF4:
2219 ADD(cr - 1 - x, y);
2220 ADD(x, cr - 1 - y);
2221 ADD(cr - 1 - x, cr - 1 - y);
2222 break;
2223 case SYMM_REF4D:
2224 ADD(y, x);
2225 ADD(cr - 1 - x, cr - 1 - y);
2226 ADD(cr - 1 - y, cr - 1 - x);
2227 break;
2228 case SYMM_REF8:
2229 ADD(cr - 1 - x, y);
2230 ADD(x, cr - 1 - y);
2231 ADD(cr - 1 - x, cr - 1 - y);
2232 ADD(y, x);
2233 ADD(y, cr - 1 - x);
2234 ADD(cr - 1 - y, x);
2235 ADD(cr - 1 - y, cr - 1 - x);
2236 break;
2237 }
2238
2239 #undef ADD
2240
2241 return i;
2242 }
2243
2244 static char *encode_solve_move(int cr, digit *grid)
2245 {
2246 int i, len;
2247 char *ret, *p, *sep;
2248
2249 /*
2250 * It's surprisingly easy to work out _exactly_ how long this
2251 * string needs to be. To decimal-encode all the numbers from 1
2252 * to n:
2253 *
2254 * - every number has a units digit; total is n.
2255 * - all numbers above 9 have a tens digit; total is max(n-9,0).
2256 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2257 * - and so on.
2258 */
2259 len = 0;
2260 for (i = 1; i <= cr; i *= 10)
2261 len += max(cr - i + 1, 0);
2262 len += cr; /* don't forget the commas */
2263 len *= cr; /* there are cr rows of these */
2264
2265 /*
2266 * Now len is one bigger than the total size of the
2267 * comma-separated numbers (because we counted an
2268 * additional leading comma). We need to have a leading S
2269 * and a trailing NUL, so we're off by one in total.
2270 */
2271 len++;
2272
2273 ret = snewn(len, char);
2274 p = ret;
2275 *p++ = 'S';
2276 sep = "";
2277 for (i = 0; i < cr*cr; i++) {
2278 p += sprintf(p, "%s%d", sep, grid[i]);
2279 sep = ",";
2280 }
2281 *p++ = '\0';
2282 assert(p - ret == len);
2283
2284 return ret;
2285 }
2286
2287 static char *new_game_desc(game_params *params, random_state *rs,
2288 char **aux, int interactive)
2289 {
2290 int c = params->c, r = params->r, cr = c*r;
2291 int area = cr*cr;
2292 struct block_structure *blocks;
2293 digit *grid, *grid2;
2294 struct xy { int x, y; } *locs;
2295 int nlocs;
2296 char *desc;
2297 int coords[16], ncoords;
2298 int maxdiff;
2299 int x, y, i, j;
2300
2301 /*
2302 * Adjust the maximum difficulty level to be consistent with
2303 * the puzzle size: all 2x2 puzzles appear to be Trivial
2304 * (DIFF_BLOCK) so we cannot hold out for even a Basic
2305 * (DIFF_SIMPLE) one.
2306 */
2307 maxdiff = params->diff;
2308 if (c == 2 && r == 2)
2309 maxdiff = DIFF_BLOCK;
2310
2311 grid = snewn(area, digit);
2312 locs = snewn(area, struct xy);
2313 grid2 = snewn(area, digit);
2314
2315 blocks = snew(struct block_structure);
2316 blocks->c = params->c; blocks->r = params->r;
2317 blocks->whichblock = snewn(area*2, int);
2318 blocks->blocks = snewn(cr, int *);
2319 for (i = 0; i < cr; i++)
2320 blocks->blocks[i] = blocks->whichblock + area + i*cr;
2321 #ifdef STANDALONE_SOLVER
2322 assert(!"This should never happen, so we don't need to create blocknames");
2323 #endif
2324
2325 /*
2326 * Loop until we get a grid of the required difficulty. This is
2327 * nasty, but it seems to be unpleasantly hard to generate
2328 * difficult grids otherwise.
2329 */
2330 while (1) {
2331 /*
2332 * Generate a random solved state, starting by
2333 * constructing the block structure.
2334 */
2335 if (r == 1) { /* jigsaw mode */
2336 int *dsf = divvy_rectangle(cr, cr, cr, rs);
2337 int nb = 0;
2338
2339 for (i = 0; i < area; i++)
2340 blocks->whichblock[i] = -1;
2341 for (i = 0; i < area; i++) {
2342 int j = dsf_canonify(dsf, i);
2343 if (blocks->whichblock[j] < 0)
2344 blocks->whichblock[j] = nb++;
2345 blocks->whichblock[i] = blocks->whichblock[j];
2346 }
2347 assert(nb == cr);
2348
2349 sfree(dsf);
2350 } else { /* basic Sudoku mode */
2351 for (y = 0; y < cr; y++)
2352 for (x = 0; x < cr; x++)
2353 blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2354 }
2355 for (i = 0; i < cr; i++)
2356 blocks->blocks[i][cr-1] = 0;
2357 for (i = 0; i < area; i++) {
2358 int b = blocks->whichblock[i];
2359 j = blocks->blocks[b][cr-1]++;
2360 assert(j < cr);
2361 blocks->blocks[b][j] = i;
2362 }
2363
2364 if (!gridgen(cr, blocks, params->xtype, grid, rs, area*area))
2365 continue;
2366 assert(check_valid(cr, blocks, params->xtype, grid));
2367
2368 /*
2369 * Save the solved grid in aux.
2370 */
2371 {
2372 /*
2373 * We might already have written *aux the last time we
2374 * went round this loop, in which case we should free
2375 * the old aux before overwriting it with the new one.
2376 */
2377 if (*aux) {
2378 sfree(*aux);
2379 }
2380
2381 *aux = encode_solve_move(cr, grid);
2382 }
2383
2384 /*
2385 * Now we have a solved grid, start removing things from it
2386 * while preserving solubility.
2387 */
2388
2389 /*
2390 * Find the set of equivalence classes of squares permitted
2391 * by the selected symmetry. We do this by enumerating all
2392 * the grid squares which have no symmetric companion
2393 * sorting lower than themselves.
2394 */
2395 nlocs = 0;
2396 for (y = 0; y < cr; y++)
2397 for (x = 0; x < cr; x++) {
2398 int i = y*cr+x;
2399 int j;
2400
2401 ncoords = symmetries(params, x, y, coords, params->symm);
2402 for (j = 0; j < ncoords; j++)
2403 if (coords[2*j+1]*cr+coords[2*j] < i)
2404 break;
2405 if (j == ncoords) {
2406 locs[nlocs].x = x;
2407 locs[nlocs].y = y;
2408 nlocs++;
2409 }
2410 }
2411
2412 /*
2413 * Now shuffle that list.
2414 */
2415 shuffle(locs, nlocs, sizeof(*locs), rs);
2416
2417 /*
2418 * Now loop over the shuffled list and, for each element,
2419 * see whether removing that element (and its reflections)
2420 * from the grid will still leave the grid soluble.
2421 */
2422 for (i = 0; i < nlocs; i++) {
2423 int ret;
2424
2425 x = locs[i].x;
2426 y = locs[i].y;
2427
2428 memcpy(grid2, grid, area);
2429 ncoords = symmetries(params, x, y, coords, params->symm);
2430 for (j = 0; j < ncoords; j++)
2431 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
2432
2433 ret = solver(cr, blocks, params->xtype, grid2, maxdiff);
2434 if (ret <= maxdiff) {
2435 for (j = 0; j < ncoords; j++)
2436 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
2437 }
2438 }
2439
2440 memcpy(grid2, grid, area);
2441
2442 if (solver(cr, blocks, params->xtype, grid2, maxdiff) == maxdiff)
2443 break; /* found one! */
2444 }
2445
2446 sfree(grid2);
2447 sfree(locs);
2448
2449 /*
2450 * Now we have the grid as it will be presented to the user.
2451 * Encode it in a game desc.
2452 */
2453 {
2454 char *p;
2455 int run, i;
2456
2457 desc = snewn(7 * area, char);
2458 p = desc;
2459 run = 0;
2460 for (i = 0; i <= area; i++) {
2461 int n = (i < area ? grid[i] : -1);
2462
2463 if (!n)
2464 run++;
2465 else {
2466 if (run) {
2467 while (run > 0) {
2468 int c = 'a' - 1 + run;
2469 if (run > 26)
2470 c = 'z';
2471 *p++ = c;
2472 run -= c - ('a' - 1);
2473 }
2474 } else {
2475 /*
2476 * If there's a number in the very top left or
2477 * bottom right, there's no point putting an
2478 * unnecessary _ before or after it.
2479 */
2480 if (p > desc && n > 0)
2481 *p++ = '_';
2482 }
2483 if (n > 0)
2484 p += sprintf(p, "%d", n);
2485 run = 0;
2486 }
2487 }
2488
2489 if (r == 1) {
2490 int currrun = 0;
2491
2492 *p++ = ',';
2493
2494 /*
2495 * Encode the block structure. We do this by encoding
2496 * the pattern of dividing lines: first we iterate
2497 * over the cr*(cr-1) internal vertical grid lines in
2498 * ordinary reading order, then over the cr*(cr-1)
2499 * internal horizontal ones in transposed reading
2500 * order.
2501 *
2502 * We encode the number of non-lines between the
2503 * lines; _ means zero (two adjacent divisions), a
2504 * means 1, ..., y means 25, and z means 25 non-lines
2505 * _and no following line_ (so that za means 26, zb 27
2506 * etc).
2507 */
2508 for (i = 0; i <= 2*cr*(cr-1); i++) {
2509 int p0, p1, edge;
2510
2511 if (i == 2*cr*(cr-1)) {
2512 edge = TRUE; /* terminating virtual edge */
2513 } else {
2514 if (i < cr*(cr-1)) {
2515 y = i/(cr-1);
2516 x = i%(cr-1);
2517 p0 = y*cr+x;
2518 p1 = y*cr+x+1;
2519 } else {
2520 x = i/(cr-1) - cr;
2521 y = i%(cr-1);
2522 p0 = y*cr+x;
2523 p1 = (y+1)*cr+x;
2524 }
2525 edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
2526 }
2527
2528 if (edge) {
2529 while (currrun > 25)
2530 *p++ = 'z', currrun -= 25;
2531 if (currrun)
2532 *p++ = 'a'-1 + currrun;
2533 else
2534 *p++ = '_';
2535 currrun = 0;
2536 } else
2537 currrun++;
2538 }
2539 }
2540
2541 assert(p - desc < 7 * area);
2542 *p++ = '\0';
2543 desc = sresize(desc, p - desc, char);
2544 }
2545
2546 sfree(grid);
2547
2548 return desc;
2549 }
2550
2551 static char *validate_desc(game_params *params, char *desc)
2552 {
2553 int cr = params->c * params->r, area = cr*cr;
2554 int squares = 0;
2555 int *dsf;
2556
2557 while (*desc && *desc != ',') {
2558 int n = *desc++;
2559 if (n >= 'a' && n <= 'z') {
2560 squares += n - 'a' + 1;
2561 } else if (n == '_') {
2562 /* do nothing */;
2563 } else if (n > '0' && n <= '9') {
2564 int val = atoi(desc-1);
2565 if (val < 1 || val > params->c * params->r)
2566 return "Out-of-range number in game description";
2567 squares++;
2568 while (*desc >= '0' && *desc <= '9')
2569 desc++;
2570 } else
2571 return "Invalid character in game description";
2572 }
2573
2574 if (squares < area)
2575 return "Not enough data to fill grid";
2576
2577 if (squares > area)
2578 return "Too much data to fit in grid";
2579
2580 if (params->r == 1) {
2581 int pos;
2582
2583 /*
2584 * Now we expect a suffix giving the jigsaw block
2585 * structure. Parse it and validate that it divides the
2586 * grid into the right number of regions which are the
2587 * right size.
2588 */
2589 if (*desc != ',')
2590 return "Expected jigsaw block structure in game description";
2591 pos = 0;
2592
2593 dsf = snew_dsf(area);
2594 desc++;
2595
2596 while (*desc) {
2597 int c, adv;
2598
2599 if (*desc == '_')
2600 c = 0;
2601 else if (*desc >= 'a' && *desc <= 'z')
2602 c = *desc - 'a' + 1;
2603 else {
2604 sfree(dsf);
2605 return "Invalid character in game description";
2606 }
2607 desc++;
2608
2609 adv = (c != 25); /* 'z' is a special case */
2610
2611 while (c-- > 0) {
2612 int p0, p1;
2613
2614 /*
2615 * Non-edge; merge the two dsf classes on either
2616 * side of it.
2617 */
2618 if (pos >= 2*cr*(cr-1)) {
2619 sfree(dsf);
2620 return "Too much data in block structure specification";
2621 } else if (pos < cr*(cr-1)) {
2622 int y = pos/(cr-1);
2623 int x = pos%(cr-1);
2624 p0 = y*cr+x;
2625 p1 = y*cr+x+1;
2626 } else {
2627 int x = pos/(cr-1) - cr;
2628 int y = pos%(cr-1);
2629 p0 = y*cr+x;
2630 p1 = (y+1)*cr+x;
2631 }
2632 dsf_merge(dsf, p0, p1);
2633
2634 pos++;
2635 }
2636 if (adv)
2637 pos++;
2638 }
2639
2640 /*
2641 * When desc is exhausted, we expect to have gone exactly
2642 * one space _past_ the end of the grid, due to the dummy
2643 * edge at the end.
2644 */
2645 if (pos != 2*cr*(cr-1)+1) {
2646 sfree(dsf);
2647 return "Not enough data in block structure specification";
2648 }
2649
2650 /*
2651 * Now we've got our dsf. Verify that it matches
2652 * expectations.
2653 */
2654 {
2655 int *canons, *counts;
2656 int i, j, c, ncanons = 0;
2657
2658 canons = snewn(cr, int);
2659 counts = snewn(cr, int);
2660
2661 for (i = 0; i < area; i++) {
2662 j = dsf_canonify(dsf, i);
2663
2664 for (c = 0; c < ncanons; c++)
2665 if (canons[c] == j) {
2666 counts[c]++;
2667 if (counts[c] > cr) {
2668 sfree(dsf);
2669 sfree(canons);
2670 sfree(counts);
2671 return "A jigsaw block is too big";
2672 }
2673 break;
2674 }
2675
2676 if (c == ncanons) {
2677 if (ncanons >= cr) {
2678 sfree(dsf);
2679 sfree(canons);
2680 sfree(counts);
2681 return "Too many distinct jigsaw blocks";
2682 }
2683 canons[ncanons] = j;
2684 counts[ncanons] = 1;
2685 ncanons++;
2686 }
2687 }
2688
2689 /*
2690 * If we've managed to get through that loop without
2691 * tripping either of the error conditions, then we
2692 * must have partitioned the entire grid into at most
2693 * cr blocks of at most cr squares each; therefore we
2694 * must have _exactly_ cr blocks of _exactly_ cr
2695 * squares each. I'll verify that by assertion just in
2696 * case something has gone horribly wrong, but it
2697 * shouldn't have been able to happen by duff input,
2698 * only by a bug in the above code.
2699 */
2700 assert(ncanons == cr);
2701 for (c = 0; c < ncanons; c++)
2702 assert(counts[c] == cr);
2703
2704 sfree(canons);
2705 sfree(counts);
2706 }
2707
2708 sfree(dsf);
2709 } else {
2710 if (*desc)
2711 return "Unexpected jigsaw block structure in game description";
2712 }
2713
2714 return NULL;
2715 }
2716
2717 static game_state *new_game(midend *me, game_params *params, char *desc)
2718 {
2719 game_state *state = snew(game_state);
2720 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2721 int i;
2722
2723 state->cr = cr;
2724 state->xtype = params->xtype;
2725
2726 state->grid = snewn(area, digit);
2727 state->pencil = snewn(area * cr, unsigned char);
2728 memset(state->pencil, 0, area * cr);
2729 state->immutable = snewn(area, unsigned char);
2730 memset(state->immutable, FALSE, area);
2731
2732 state->blocks = snew(struct block_structure);
2733 state->blocks->c = c; state->blocks->r = r;
2734 state->blocks->refcount = 1;
2735 state->blocks->whichblock = snewn(area*2, int);
2736 state->blocks->blocks = snewn(cr, int *);
2737 for (i = 0; i < cr; i++)
2738 state->blocks->blocks[i] = state->blocks->whichblock + area + i*cr;
2739 #ifdef STANDALONE_SOLVER
2740 state->blocks->blocknames = (char **)smalloc(cr*(sizeof(char *)+80));
2741 #endif
2742
2743 state->completed = state->cheated = FALSE;
2744
2745 i = 0;
2746 while (*desc && *desc != ',') {
2747 int n = *desc++;
2748 if (n >= 'a' && n <= 'z') {
2749 int run = n - 'a' + 1;
2750 assert(i + run <= area);
2751 while (run-- > 0)
2752 state->grid[i++] = 0;
2753 } else if (n == '_') {
2754 /* do nothing */;
2755 } else if (n > '0' && n <= '9') {
2756 assert(i < area);
2757 state->immutable[i] = TRUE;
2758 state->grid[i++] = atoi(desc-1);
2759 while (*desc >= '0' && *desc <= '9')
2760 desc++;
2761 } else {
2762 assert(!"We can't get here");
2763 }
2764 }
2765 assert(i == area);
2766
2767 if (r == 1) {
2768 int pos = 0;
2769 int *dsf;
2770 int nb;
2771
2772 assert(*desc == ',');
2773
2774 dsf = snew_dsf(area);
2775 desc++;
2776
2777 while (*desc) {
2778 int c, adv;
2779
2780 if (*desc == '_')
2781 c = 0;
2782 else {
2783 assert(*desc >= 'a' && *desc <= 'z');
2784 c = *desc - 'a' + 1;
2785 }
2786 desc++;
2787
2788 adv = (c != 25); /* 'z' is a special case */
2789
2790 while (c-- > 0) {
2791 int p0, p1;
2792
2793 /*
2794 * Non-edge; merge the two dsf classes on either
2795 * side of it.
2796 */
2797 assert(pos < 2*cr*(cr-1));
2798 if (pos < cr*(cr-1)) {
2799 int y = pos/(cr-1);
2800 int x = pos%(cr-1);
2801 p0 = y*cr+x;
2802 p1 = y*cr+x+1;
2803 } else {
2804 int x = pos/(cr-1) - cr;
2805 int y = pos%(cr-1);
2806 p0 = y*cr+x;
2807 p1 = (y+1)*cr+x;
2808 }
2809 dsf_merge(dsf, p0, p1);
2810
2811 pos++;
2812 }
2813 if (adv)
2814 pos++;
2815 }
2816
2817 /*
2818 * When desc is exhausted, we expect to have gone exactly
2819 * one space _past_ the end of the grid, due to the dummy
2820 * edge at the end.
2821 */
2822 assert(pos == 2*cr*(cr-1)+1);
2823
2824 /*
2825 * Now we've got our dsf. Translate it into a block
2826 * structure.
2827 */
2828 nb = 0;
2829 for (i = 0; i < area; i++)
2830 state->blocks->whichblock[i] = -1;
2831 for (i = 0; i < area; i++) {
2832 int j = dsf_canonify(dsf, i);
2833 if (state->blocks->whichblock[j] < 0)
2834 state->blocks->whichblock[j] = nb++;
2835 state->blocks->whichblock[i] = state->blocks->whichblock[j];
2836 }
2837 assert(nb == cr);
2838
2839 sfree(dsf);
2840 } else {
2841 int x, y;
2842
2843 assert(!*desc);
2844
2845 for (y = 0; y < cr; y++)
2846 for (x = 0; x < cr; x++)
2847 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2848 }
2849
2850 /*
2851 * Having sorted out whichblock[], set up the block index arrays.
2852 */
2853 for (i = 0; i < cr; i++)
2854 state->blocks->blocks[i][cr-1] = 0;
2855 for (i = 0; i < area; i++) {
2856 int b = state->blocks->whichblock[i];
2857 int j = state->blocks->blocks[b][cr-1]++;
2858 assert(j < cr);
2859 state->blocks->blocks[b][j] = i;
2860 }
2861
2862 #ifdef STANDALONE_SOLVER
2863 /*
2864 * Set up the block names for solver diagnostic output.
2865 */
2866 {
2867 char *p = (char *)(state->blocks->blocknames + cr);
2868
2869 if (r == 1) {
2870 for (i = 0; i < cr; i++)
2871 state->blocks->blocknames[i] = NULL;
2872
2873 for (i = 0; i < area; i++) {
2874 int j = state->blocks->whichblock[i];
2875 if (!state->blocks->blocknames[j]) {
2876 state->blocks->blocknames[j] = p;
2877 p += 1 + sprintf(p, "starting at (%d,%d)",
2878 1 + i%cr, 1 + i/cr);
2879 }
2880 }
2881 } else {
2882 int bx, by;
2883 for (by = 0; by < r; by++)
2884 for (bx = 0; bx < c; bx++) {
2885 state->blocks->blocknames[by*c+bx] = p;
2886 p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
2887 }
2888 }
2889 assert(p - (char *)state->blocks->blocknames < cr*(sizeof(char *)+80));
2890 for (i = 0; i < cr; i++)
2891 assert(state->blocks->blocknames[i]);
2892 }
2893 #endif
2894
2895 return state;
2896 }
2897
2898 static game_state *dup_game(game_state *state)
2899 {
2900 game_state *ret = snew(game_state);
2901 int cr = state->cr, area = cr * cr;
2902
2903 ret->cr = state->cr;
2904 ret->xtype = state->xtype;
2905
2906 ret->blocks = state->blocks;
2907 ret->blocks->refcount++;
2908
2909 ret->grid = snewn(area, digit);
2910 memcpy(ret->grid, state->grid, area);
2911
2912 ret->pencil = snewn(area * cr, unsigned char);
2913 memcpy(ret->pencil, state->pencil, area * cr);
2914
2915 ret->immutable = snewn(area, unsigned char);
2916 memcpy(ret->immutable, state->immutable, area);
2917
2918 ret->completed = state->completed;
2919 ret->cheated = state->cheated;
2920
2921 return ret;
2922 }
2923
2924 static void free_game(game_state *state)
2925 {
2926 if (--state->blocks->refcount == 0) {
2927 sfree(state->blocks->whichblock);
2928 sfree(state->blocks->blocks);
2929 #ifdef STANDALONE_SOLVER
2930 sfree(state->blocks->blocknames);
2931 #endif
2932 sfree(state->blocks);
2933 }
2934 sfree(state->immutable);
2935 sfree(state->pencil);
2936 sfree(state->grid);
2937 sfree(state);
2938 }
2939
2940 static char *solve_game(game_state *state, game_state *currstate,
2941 char *ai, char **error)
2942 {
2943 int cr = state->cr;
2944 char *ret;
2945 digit *grid;
2946 int solve_ret;
2947
2948 /*
2949 * If we already have the solution in ai, save ourselves some
2950 * time.
2951 */
2952 if (ai)
2953 return dupstr(ai);
2954
2955 grid = snewn(cr*cr, digit);
2956 memcpy(grid, state->grid, cr*cr);
2957 solve_ret = solver(cr, state->blocks, state->xtype, grid, DIFF_RECURSIVE);
2958
2959 *error = NULL;
2960
2961 if (solve_ret == DIFF_IMPOSSIBLE)
2962 *error = "No solution exists for this puzzle";
2963 else if (solve_ret == DIFF_AMBIGUOUS)
2964 *error = "Multiple solutions exist for this puzzle";
2965
2966 if (*error) {
2967 sfree(grid);
2968 return NULL;
2969 }
2970
2971 ret = encode_solve_move(cr, grid);
2972
2973 sfree(grid);
2974
2975 return ret;
2976 }
2977
2978 static char *grid_text_format(int cr, struct block_structure *blocks,
2979 int xtype, digit *grid)
2980 {
2981 int vmod, hmod;
2982 int x, y;
2983 int totallen, linelen, nlines;
2984 char *ret, *p, ch;
2985
2986 /*
2987 * For non-jigsaw Sudoku, we format in the way we always have,
2988 * by having the digits unevenly spaced so that the dividing
2989 * lines can fit in:
2990 *
2991 * . . | . .
2992 * . . | . .
2993 * ----+----
2994 * . . | . .
2995 * . . | . .
2996 *
2997 * For jigsaw puzzles, however, we must leave space between
2998 * _all_ pairs of digits for an optional dividing line, so we
2999 * have to move to the rather ugly
3000 *
3001 * . . . .
3002 * ------+------
3003 * . . | . .
3004 * +---+
3005 * . . | . | .
3006 * ------+ |
3007 * . . . | .
3008 *
3009 * We deal with both cases using the same formatting code; we
3010 * simply invent a vmod value such that there's a vertical
3011 * dividing line before column i iff i is divisible by vmod
3012 * (so it's r in the first case and 1 in the second), and hmod
3013 * likewise for horizontal dividing lines.
3014 */
3015
3016 if (blocks->r != 1) {
3017 vmod = blocks->r;
3018 hmod = blocks->c;
3019 } else {
3020 vmod = hmod = 1;
3021 }
3022
3023 /*
3024 * Line length: we have cr digits, each with a space after it,
3025 * and (cr-1)/vmod dividing lines, each with a space after it.
3026 * The final space is replaced by a newline, but that doesn't
3027 * affect the length.
3028 */
3029 linelen = 2*(cr + (cr-1)/vmod);
3030
3031 /*
3032 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3033 * dividing rows.
3034 */
3035 nlines = cr + (cr-1)/hmod;
3036
3037 /*
3038 * Allocate the space.
3039 */
3040 totallen = linelen * nlines;
3041 ret = snewn(totallen+1, char); /* leave room for terminating NUL */
3042
3043 /*
3044 * Write the text.
3045 */
3046 p = ret;
3047 for (y = 0; y < cr; y++) {
3048 /*
3049 * Row of digits.
3050 */
3051 for (x = 0; x < cr; x++) {
3052 /*
3053 * Digit.
3054 */
3055 digit d = grid[y*cr+x];
3056
3057 if (d == 0) {
3058 /*
3059 * Empty space: we usually write a dot, but we'll
3060 * highlight spaces on the X-diagonals (in X mode)
3061 * by using underscores instead.
3062 */
3063 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
3064 ch = '_';
3065 else
3066 ch = '.';
3067 } else if (d <= 9) {
3068 ch = '0' + d;
3069 } else {
3070 ch = 'a' + d-10;
3071 }
3072
3073 *p++ = ch;
3074 if (x == cr-1) {
3075 *p++ = '\n';
3076 continue;
3077 }
3078 *p++ = ' ';
3079
3080 if ((x+1) % vmod)
3081 continue;
3082
3083 /*
3084 * Optional dividing line.
3085 */
3086 if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
3087 ch = '|';
3088 else
3089 ch = ' ';
3090 *p++ = ch;
3091 *p++ = ' ';
3092 }
3093 if (y == cr-1 || (y+1) % hmod)
3094 continue;
3095
3096 /*
3097 * Dividing row.
3098 */
3099 for (x = 0; x < cr; x++) {
3100 int dwid;
3101 int tl, tr, bl, br;
3102
3103 /*
3104 * Division between two squares. This varies
3105 * complicatedly in length.
3106 */
3107 dwid = 2; /* digit and its following space */
3108 if (x == cr-1)
3109 dwid--; /* no following space at end of line */
3110 if (x > 0 && x % vmod == 0)
3111 dwid++; /* preceding space after a divider */
3112
3113 if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
3114 ch = '-';
3115 else
3116 ch = ' ';
3117
3118 while (dwid-- > 0)
3119 *p++ = ch;
3120
3121 if (x == cr-1) {
3122 *p++ = '\n';
3123 break;
3124 }
3125
3126 if ((x+1) % vmod)
3127 continue;
3128
3129 /*
3130 * Corner square. This is:
3131 * - a space if all four surrounding squares are in
3132 * the same block
3133 * - a vertical line if the two left ones are in one
3134 * block and the two right in another
3135 * - a horizontal line if the two top ones are in one
3136 * block and the two bottom in another
3137 * - a plus sign in all other cases. (If we had a
3138 * richer character set available we could break
3139 * this case up further by doing fun things with
3140 * line-drawing T-pieces.)
3141 */
3142 tl = blocks->whichblock[y*cr+x];
3143 tr = blocks->whichblock[y*cr+x+1];
3144 bl = blocks->whichblock[(y+1)*cr+x];
3145 br = blocks->whichblock[(y+1)*cr+x+1];
3146
3147 if (tl == tr && tr == bl && bl == br)
3148 ch = ' ';
3149 else if (tl == bl && tr == br)
3150 ch = '|';
3151 else if (tl == tr && bl == br)
3152 ch = '-';
3153 else
3154 ch = '+';
3155
3156 *p++ = ch;
3157 }
3158 }
3159
3160 assert(p - ret == totallen);
3161 *p = '\0';
3162 return ret;
3163 }
3164
3165 static int game_can_format_as_text_now(game_params *params)
3166 {
3167 return TRUE;
3168 }
3169
3170 static char *game_text_format(game_state *state)
3171 {
3172 return grid_text_format(state->cr, state->blocks, state->xtype,
3173 state->grid);
3174 }
3175
3176 struct game_ui {
3177 /*
3178 * These are the coordinates of the currently highlighted
3179 * square on the grid, or -1,-1 if there isn't one. When there
3180 * is, pressing a valid number or letter key or Space will
3181 * enter that number or letter in the grid.
3182 */
3183 int hx, hy;
3184 /*
3185 * This indicates whether the current highlight is a
3186 * pencil-mark one or a real one.
3187 */
3188 int hpencil;
3189 };
3190
3191 static game_ui *new_ui(game_state *state)
3192 {
3193 game_ui *ui = snew(game_ui);
3194
3195 ui->hx = ui->hy = -1;
3196 ui->hpencil = 0;
3197
3198 return ui;
3199 }
3200
3201 static void free_ui(game_ui *ui)
3202 {
3203 sfree(ui);
3204 }
3205
3206 static char *encode_ui(game_ui *ui)
3207 {
3208 return NULL;
3209 }
3210
3211 static void decode_ui(game_ui *ui, char *encoding)
3212 {
3213 }
3214
3215 static void game_changed_state(game_ui *ui, game_state *oldstate,
3216 game_state *newstate)
3217 {
3218 int cr = newstate->cr;
3219 /*
3220 * We prevent pencil-mode highlighting of a filled square. So
3221 * if the user has just filled in a square which we had a
3222 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3223 * then we cancel the highlight.
3224 */
3225 if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
3226 newstate->grid[ui->hy * cr + ui->hx] != 0) {
3227 ui->hx = ui->hy = -1;
3228 }
3229 }
3230
3231 struct game_drawstate {
3232 int started;
3233 int cr, xtype;
3234 int tilesize;
3235 digit *grid;
3236 unsigned char *pencil;
3237 unsigned char *hl;
3238 /* This is scratch space used within a single call to game_redraw. */
3239 int *entered_items;
3240 };
3241
3242 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3243 int x, int y, int button)
3244 {
3245 int cr = state->cr;
3246 int tx, ty;
3247 char buf[80];
3248
3249 button &= ~MOD_MASK;
3250
3251 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3252 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3253
3254 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
3255 if (button == LEFT_BUTTON) {
3256 if (state->immutable[ty*cr+tx]) {
3257 ui->hx = ui->hy = -1;
3258 } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
3259 ui->hx = ui->hy = -1;
3260 } else {
3261 ui->hx = tx;
3262 ui->hy = ty;
3263 ui->hpencil = 0;
3264 }
3265 return ""; /* UI activity occurred */
3266 }
3267 if (button == RIGHT_BUTTON) {
3268 /*
3269 * Pencil-mode highlighting for non filled squares.
3270 */
3271 if (state->grid[ty*cr+tx] == 0) {
3272 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
3273 ui->hx = ui->hy = -1;
3274 } else {
3275 ui->hpencil = 1;
3276 ui->hx = tx;
3277 ui->hy = ty;
3278 }
3279 } else {
3280 ui->hx = ui->hy = -1;
3281 }
3282 return ""; /* UI activity occurred */
3283 }
3284 }
3285
3286 if (ui->hx != -1 && ui->hy != -1 &&
3287 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
3288 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
3289 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
3290 button == ' ' || button == '\010' || button == '\177')) {
3291 int n = button - '0';
3292 if (button >= 'A' && button <= 'Z')
3293 n = button - 'A' + 10;
3294 if (button >= 'a' && button <= 'z')
3295 n = button - 'a' + 10;
3296 if (button == ' ' || button == '\010' || button == '\177')
3297 n = 0;
3298
3299 /*
3300 * Can't overwrite this square. In principle this shouldn't
3301 * happen anyway because we should never have even been
3302 * able to highlight the square, but it never hurts to be
3303 * careful.
3304 */
3305 if (state->immutable[ui->hy*cr+ui->hx])
3306 return NULL;
3307
3308 /*
3309 * Can't make pencil marks in a filled square. In principle
3310 * this shouldn't happen anyway because we should never
3311 * have even been able to pencil-highlight the square, but
3312 * it never hurts to be careful.
3313 */
3314 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
3315 return NULL;
3316
3317 sprintf(buf, "%c%d,%d,%d",
3318 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
3319
3320 ui->hx = ui->hy = -1;
3321
3322 return dupstr(buf);
3323 }
3324
3325 return NULL;
3326 }
3327
3328 static game_state *execute_move(game_state *from, char *move)
3329 {
3330 int cr = from->cr;
3331 game_state *ret;
3332 int x, y, n;
3333
3334 if (move[0] == 'S') {
3335 char *p;
3336
3337 ret = dup_game(from);
3338 ret->completed = ret->cheated = TRUE;
3339
3340 p = move+1;
3341 for (n = 0; n < cr*cr; n++) {
3342 ret->grid[n] = atoi(p);
3343
3344 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
3345 free_game(ret);
3346 return NULL;
3347 }
3348
3349 while (*p && isdigit((unsigned char)*p)) p++;
3350 if (*p == ',') p++;
3351 }
3352
3353 return ret;
3354 } else if ((move[0] == 'P' || move[0] == 'R') &&
3355 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
3356 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
3357
3358 ret = dup_game(from);
3359 if (move[0] == 'P' && n > 0) {
3360 int index = (y*cr+x) * cr + (n-1);
3361 ret->pencil[index] = !ret->pencil[index];
3362 } else {
3363 ret->grid[y*cr+x] = n;
3364 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
3365
3366 /*
3367 * We've made a real change to the grid. Check to see
3368 * if the game has been completed.
3369 */
3370 if (!ret->completed && check_valid(cr, ret->blocks, ret->xtype,
3371 ret->grid)) {
3372 ret->completed = TRUE;
3373 }
3374 }
3375 return ret;
3376 } else
3377 return NULL; /* couldn't parse move string */
3378 }
3379
3380 /* ----------------------------------------------------------------------
3381 * Drawing routines.
3382 */
3383
3384 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3385 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3386
3387 static void game_compute_size(game_params *params, int tilesize,
3388 int *x, int *y)
3389 {
3390 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3391 struct { int tilesize; } ads, *ds = &ads;
3392 ads.tilesize = tilesize;
3393
3394 *x = SIZE(params->c * params->r);
3395 *y = SIZE(params->c * params->r);
3396 }
3397
3398 static void game_set_size(drawing *dr, game_drawstate *ds,
3399 game_params *params, int tilesize)
3400 {
3401 ds->tilesize = tilesize;
3402 }
3403
3404 static float *game_colours(frontend *fe, int *ncolours)
3405 {
3406 float *ret = snewn(3 * NCOLOURS, float);
3407
3408 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
3409
3410 ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
3411 ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
3412 ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
3413
3414 ret[COL_GRID * 3 + 0] = 0.0F;
3415 ret[COL_GRID * 3 + 1] = 0.0F;
3416 ret[COL_GRID * 3 + 2] = 0.0F;
3417
3418 ret[COL_CLUE * 3 + 0] = 0.0F;
3419 ret[COL_CLUE * 3 + 1] = 0.0F;
3420 ret[COL_CLUE * 3 + 2] = 0.0F;
3421
3422 ret[COL_USER * 3 + 0] = 0.0F;
3423 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
3424 ret[COL_USER * 3 + 2] = 0.0F;
3425
3426 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
3427 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
3428 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
3429
3430 ret[COL_ERROR * 3 + 0] = 1.0F;
3431 ret[COL_ERROR * 3 + 1] = 0.0F;
3432 ret[COL_ERROR * 3 + 2] = 0.0F;
3433
3434 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
3435 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
3436 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
3437
3438 *ncolours = NCOLOURS;
3439 return ret;
3440 }
3441
3442 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
3443 {
3444 struct game_drawstate *ds = snew(struct game_drawstate);
3445 int cr = state->cr;
3446
3447 ds->started = FALSE;
3448 ds->cr = cr;
3449 ds->xtype = state->xtype;
3450 ds->grid = snewn(cr*cr, digit);
3451 memset(ds->grid, cr+2, cr*cr);
3452 ds->pencil = snewn(cr*cr*cr, digit);
3453 memset(ds->pencil, 0, cr*cr*cr);
3454 ds->hl = snewn(cr*cr, unsigned char);
3455 memset(ds->hl, 0, cr*cr);
3456 ds->entered_items = snewn(cr*cr, int);
3457 ds->tilesize = 0; /* not decided yet */
3458 return ds;
3459 }
3460
3461 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3462 {
3463 sfree(ds->hl);
3464 sfree(ds->pencil);
3465 sfree(ds->grid);
3466 sfree(ds->entered_items);
3467 sfree(ds);
3468 }
3469
3470 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
3471 int x, int y, int hl)
3472 {
3473 int cr = state->cr;
3474 int tx, ty;
3475 int cx, cy, cw, ch;
3476 char str[2];
3477
3478 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
3479 ds->hl[y*cr+x] == hl &&
3480 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
3481 return; /* no change required */
3482
3483 tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
3484 ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
3485
3486 cx = tx;
3487 cy = ty;
3488 cw = TILE_SIZE-1-2*GRIDEXTRA;
3489 ch = TILE_SIZE-1-2*GRIDEXTRA;
3490
3491 if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
3492 cx -= GRIDEXTRA, cw += GRIDEXTRA;
3493 if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
3494 cw += GRIDEXTRA;
3495 if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
3496 cy -= GRIDEXTRA, ch += GRIDEXTRA;
3497 if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
3498 ch += GRIDEXTRA;
3499
3500 clip(dr, cx, cy, cw, ch);
3501
3502 /* background needs erasing */
3503 draw_rect(dr, cx, cy, cw, ch,
3504 ((hl & 15) == 1 ? COL_HIGHLIGHT :
3505 (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
3506 COL_BACKGROUND));
3507
3508 /*
3509 * Draw the corners of thick lines in corner-adjacent squares,
3510 * which jut into this square by one pixel.
3511 */
3512 if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
3513 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3514 if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
3515 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3516 if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
3517 draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3518 if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
3519 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3520
3521 /* pencil-mode highlight */
3522 if ((hl & 15) == 2) {
3523 int coords[6];
3524 coords[0] = cx;
3525 coords[1] = cy;
3526 coords[2] = cx+cw/2;
3527 coords[3] = cy;
3528 coords[4] = cx;
3529 coords[5] = cy+ch/2;
3530 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
3531 }
3532
3533 /* new number needs drawing? */
3534 if (state->grid[y*cr+x]) {
3535 str[1] = '\0';
3536 str[0] = state->grid[y*cr+x] + '0';
3537 if (str[0] > '9')
3538 str[0] += 'a' - ('9'+1);
3539 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
3540 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
3541 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
3542 } else {
3543 int i, j, npencil;
3544 int pw, ph, pmax, fontsize;
3545
3546 /* count the pencil marks required */
3547 for (i = npencil = 0; i < cr; i++)
3548 if (state->pencil[(y*cr+x)*cr+i])
3549 npencil++;
3550
3551 /*
3552 * It's not sensible to arrange pencil marks in the same
3553 * layout as the squares within a block, because this leads
3554 * to the font being too small. Instead, we arrange pencil
3555 * marks in the nearest thing we can to a square layout,
3556 * and we adjust the square layout depending on the number
3557 * of pencil marks in the square.
3558 */
3559 for (pw = 1; pw * pw < npencil; pw++);
3560 if (pw < 3) pw = 3; /* otherwise it just looks _silly_ */
3561 ph = (npencil + pw - 1) / pw;
3562 if (ph < 2) ph = 2; /* likewise */
3563 pmax = max(pw, ph);
3564 fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
3565
3566 for (i = j = 0; i < cr; i++)
3567 if (state->pencil[(y*cr+x)*cr+i]) {
3568 int dx = j % pw, dy = j / pw;
3569
3570 str[1] = '\0';
3571 str[0] = i + '1';
3572 if (str[0] > '9')
3573 str[0] += 'a' - ('9'+1);
3574 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
3575 ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
3576 FONT_VARIABLE, fontsize,
3577 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
3578 j++;
3579 }
3580 }
3581
3582 unclip(dr);
3583
3584 draw_update(dr, cx, cy, cw, ch);
3585
3586 ds->grid[y*cr+x] = state->grid[y*cr+x];
3587 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
3588 ds->hl[y*cr+x] = hl;
3589 }
3590
3591 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3592 game_state *state, int dir, game_ui *ui,
3593 float animtime, float flashtime)
3594 {
3595 int cr = state->cr;
3596 int x, y;
3597
3598 if (!ds->started) {
3599 /*
3600 * The initial contents of the window are not guaranteed
3601 * and can vary with front ends. To be on the safe side,
3602 * all games should start by drawing a big
3603 * background-colour rectangle covering the whole window.
3604 */
3605 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
3606
3607 /*
3608 * Draw the grid. We draw it as a big thick rectangle of
3609 * COL_GRID initially; individual calls to draw_number()
3610 * will poke the right-shaped holes in it.
3611 */
3612 draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
3613 cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
3614 COL_GRID);
3615 }
3616
3617 /*
3618 * This array is used to keep track of rows, columns and boxes
3619 * which contain a number more than once.
3620 */
3621 for (x = 0; x < cr * cr; x++)
3622 ds->entered_items[x] = 0;
3623 for (x = 0; x < cr; x++)
3624 for (y = 0; y < cr; y++) {
3625 digit d = state->grid[y*cr+x];
3626 if (d) {
3627 int box = state->blocks->whichblock[y*cr+x];
3628 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
3629 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
3630 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
3631 if (ds->xtype) {
3632 if (ondiag0(y*cr+x))
3633 ds->entered_items[d-1] |= ((ds->entered_items[d-1] & 64) << 1) | 64;
3634 if (ondiag1(y*cr+x))
3635 ds->entered_items[cr+d-1] |= ((ds->entered_items[cr+d-1] & 64) << 1) | 64;
3636 }
3637 }
3638 }
3639
3640 /*
3641 * Draw any numbers which need redrawing.
3642 */
3643 for (x = 0; x < cr; x++) {
3644 for (y = 0; y < cr; y++) {
3645 int highlight = 0;
3646 digit d = state->grid[y*cr+x];
3647
3648 if (flashtime > 0 &&
3649 (flashtime <= FLASH_TIME/3 ||
3650 flashtime >= FLASH_TIME*2/3))
3651 highlight = 1;
3652
3653 /* Highlight active input areas. */
3654 if (x == ui->hx && y == ui->hy)
3655 highlight = ui->hpencil ? 2 : 1;
3656
3657 /* Mark obvious errors (ie, numbers which occur more than once
3658 * in a single row, column, or box). */
3659 if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
3660 (ds->entered_items[y*cr+d-1] & 8) ||
3661 (ds->entered_items[state->blocks->whichblock[y*cr+x]*cr+d-1] & 32) ||
3662 (ds->xtype && ((ondiag0(y*cr+x) && (ds->entered_items[d-1] & 128)) ||
3663 (ondiag1(y*cr+x) && (ds->entered_items[cr+d-1] & 128))))))
3664 highlight |= 16;
3665
3666 draw_number(dr, ds, state, x, y, highlight);
3667 }
3668 }
3669
3670 /*
3671 * Update the _entire_ grid if necessary.
3672 */
3673 if (!ds->started) {
3674 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
3675 ds->started = TRUE;
3676 }
3677 }
3678
3679 static float game_anim_length(game_state *oldstate, game_state *newstate,
3680 int dir, game_ui *ui)
3681 {
3682 return 0.0F;
3683 }
3684
3685 static float game_flash_length(game_state *oldstate, game_state *newstate,
3686 int dir, game_ui *ui)
3687 {
3688 if (!oldstate->completed && newstate->completed &&
3689 !oldstate->cheated && !newstate->cheated)
3690 return FLASH_TIME;
3691 return 0.0F;
3692 }
3693
3694 static int game_timing_state(game_state *state, game_ui *ui)
3695 {
3696 return TRUE;
3697 }
3698
3699 static void game_print_size(game_params *params, float *x, float *y)
3700 {
3701 int pw, ph;
3702
3703 /*
3704 * I'll use 9mm squares by default. They should be quite big
3705 * for this game, because players will want to jot down no end
3706 * of pencil marks in the squares.
3707 */
3708 game_compute_size(params, 900, &pw, &ph);
3709 *x = pw / 100.0;
3710 *y = ph / 100.0;
3711 }
3712
3713 static void game_print(drawing *dr, game_state *state, int tilesize)
3714 {
3715 int cr = state->cr;
3716 int ink = print_mono_colour(dr, 0);
3717 int x, y;
3718
3719 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3720 game_drawstate ads, *ds = &ads;
3721 game_set_size(dr, ds, NULL, tilesize);
3722
3723 /*
3724 * Border.
3725 */
3726 print_line_width(dr, 3 * TILE_SIZE / 40);
3727 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
3728
3729 /*
3730 * Highlight X-diagonal squares.
3731 */
3732 if (state->xtype) {
3733 int i;
3734 int xhighlight = print_grey_colour(dr, 0.90F);
3735
3736 for (i = 0; i < cr; i++)
3737 draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
3738 TILE_SIZE, TILE_SIZE, xhighlight);
3739 for (i = 0; i < cr; i++)
3740 if (i*2 != cr-1) /* avoid redoing centre square, just for fun */
3741 draw_rect(dr, BORDER + i*TILE_SIZE,
3742 BORDER + (cr-1-i)*TILE_SIZE,
3743 TILE_SIZE, TILE_SIZE, xhighlight);
3744 }
3745
3746 /*
3747 * Main grid.
3748 */
3749 for (x = 1; x < cr; x++) {
3750 print_line_width(dr, TILE_SIZE / 40);
3751 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
3752 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
3753 }
3754 for (y = 1; y < cr; y++) {
3755 print_line_width(dr, TILE_SIZE / 40);
3756 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
3757 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
3758 }
3759
3760 /*
3761 * Thick lines between cells. In order to do this using the
3762 * line-drawing rather than rectangle-drawing API (so as to
3763 * get line thicknesses to scale correctly) and yet have
3764 * correctly mitred joins between lines, we must do this by
3765 * tracing the boundary of each sub-block and drawing it in
3766 * one go as a single polygon.
3767 */
3768 {
3769 int *coords;
3770 int bi, i, n;
3771 int x, y, dx, dy, sx, sy, sdx, sdy;
3772
3773 print_line_width(dr, 3 * TILE_SIZE / 40);
3774
3775 /*
3776 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3777 * with k unconnected squares, with total perimeter 4k.
3778 * Now repeatedly join two disconnected components
3779 * together into a larger one; every time you do so you
3780 * remove at least two unit edges, and you require k-1 of
3781 * these operations to create a single connected piece, so
3782 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3783 * afterwards.)
3784 */
3785 coords = snewn(4*cr+4, int); /* 2k+2 points, 2 coords per point */
3786
3787 /*
3788 * Iterate over all the blocks.
3789 */
3790 for (bi = 0; bi < cr; bi++) {
3791
3792 /*
3793 * For each block, find a starting square within it
3794 * which has a boundary at the left.
3795 */
3796 for (i = 0; i < cr; i++) {
3797 int j = state->blocks->blocks[bi][i];
3798 if (j % cr == 0 || state->blocks->whichblock[j-1] != bi)
3799 break;
3800 }
3801 assert(i < cr); /* every block must have _some_ leftmost square */
3802 x = state->blocks->blocks[bi][i] % cr;
3803 y = state->blocks->blocks[bi][i] / cr;
3804 dx = -1;
3805 dy = 0;
3806
3807 /*
3808 * Now begin tracing round the perimeter. At all
3809 * times, (x,y) describes some square within the
3810 * block, and (x+dx,y+dy) is some adjacent square
3811 * outside it; so the edge between those two squares
3812 * is always an edge of the block.
3813 */
3814 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
3815 n = 0;
3816 do {
3817 int cx, cy, tx, ty, nin;
3818
3819 /*
3820 * To begin with, record the point at one end of
3821 * the edge. To do this, we translate (x,y) down
3822 * and right by half a unit (so they're describing
3823 * a point in the _centre_ of the square) and then
3824 * translate back again in a manner rotated by dy
3825 * and dx.
3826 */
3827 assert(n < 2*cr+2);
3828 cx = ((2*x+1) + dy + dx) / 2;
3829 cy = ((2*y+1) - dx + dy) / 2;
3830 coords[2*n+0] = BORDER + cx * TILE_SIZE;
3831 coords[2*n+1] = BORDER + cy * TILE_SIZE;
3832 n++;
3833
3834 /*
3835 * Now advance to the next edge, by looking at the
3836 * two squares beyond it. If they're both outside
3837 * the block, we turn right (by leaving x,y the
3838 * same and rotating dx,dy clockwise); if they're
3839 * both inside, we turn left (by rotating dx,dy
3840 * anticlockwise and contriving to leave x+dx,y+dy
3841 * unchanged); if one of each, we go straight on
3842 * (and may enforce by assertion that they're one
3843 * of each the _right_ way round).
3844 */
3845 nin = 0;
3846 tx = x - dy + dx;
3847 ty = y + dx + dy;
3848 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3849 state->blocks->whichblock[ty*cr+tx] == bi);
3850 tx = x - dy;
3851 ty = y + dx;
3852 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3853 state->blocks->whichblock[ty*cr+tx] == bi);
3854 if (nin == 0) {
3855 /*
3856 * Turn right.
3857 */
3858 int tmp;
3859 tmp = dx;
3860 dx = -dy;
3861 dy = tmp;
3862 } else if (nin == 2) {
3863 /*
3864 * Turn left.
3865 */
3866 int tmp;
3867
3868 x += dx;
3869 y += dy;
3870
3871 tmp = dx;
3872 dx = dy;
3873 dy = -tmp;
3874
3875 x -= dx;
3876 y -= dy;
3877 } else {
3878 /*
3879 * Go straight on.
3880 */
3881 x -= dy;
3882 y += dx;
3883 }
3884
3885 /*
3886 * Now enforce by assertion that we ended up
3887 * somewhere sensible.
3888 */
3889 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
3890 state->blocks->whichblock[y*cr+x] == bi);
3891 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
3892 state->blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
3893
3894 } while (x != sx || y != sy || dx != sdx || dy != sdy);
3895
3896 /*
3897 * That's our polygon; now draw it.
3898 */
3899 draw_polygon(dr, coords, n, -1, ink);
3900 }
3901
3902 sfree(coords);
3903 }
3904
3905 /*
3906 * Numbers.
3907 */
3908 for (y = 0; y < cr; y++)
3909 for (x = 0; x < cr; x++)
3910 if (state->grid[y*cr+x]) {
3911 char str[2];
3912 str[1] = '\0';
3913 str[0] = state->grid[y*cr+x] + '0';
3914 if (str[0] > '9')
3915 str[0] += 'a' - ('9'+1);
3916 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
3917 BORDER + y*TILE_SIZE + TILE_SIZE/2,
3918 FONT_VARIABLE, TILE_SIZE/2,
3919 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
3920 }
3921 }
3922
3923 #ifdef COMBINED
3924 #define thegame solo
3925 #endif
3926
3927 const struct game thegame = {
3928 "Solo", "games.solo", "solo",
3929 default_params,
3930 game_fetch_preset,
3931 decode_params,
3932 encode_params,
3933 free_params,
3934 dup_params,
3935 TRUE, game_configure, custom_params,
3936 validate_params,
3937 new_game_desc,
3938 validate_desc,
3939 new_game,
3940 dup_game,
3941 free_game,
3942 TRUE, solve_game,
3943 TRUE, game_can_format_as_text_now, game_text_format,
3944 new_ui,
3945 free_ui,
3946 encode_ui,
3947 decode_ui,
3948 game_changed_state,
3949 interpret_move,
3950 execute_move,
3951 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3952 game_colours,
3953 game_new_drawstate,
3954 game_free_drawstate,
3955 game_redraw,
3956 game_anim_length,
3957 game_flash_length,
3958 TRUE, FALSE, game_print_size, game_print,
3959 FALSE, /* wants_statusbar */
3960 FALSE, game_timing_state,
3961 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
3962 };
3963
3964 #ifdef STANDALONE_SOLVER
3965
3966 int main(int argc, char **argv)
3967 {
3968 game_params *p;
3969 game_state *s;
3970 char *id = NULL, *desc, *err;
3971 int grade = FALSE;
3972 int ret;
3973
3974 while (--argc > 0) {
3975 char *p = *++argv;
3976 if (!strcmp(p, "-v")) {
3977 solver_show_working = TRUE;
3978 } else if (!strcmp(p, "-g")) {
3979 grade = TRUE;
3980 } else if (*p == '-') {
3981 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3982 return 1;
3983 } else {
3984 id = p;
3985 }
3986 }
3987
3988 if (!id) {
3989 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3990 return 1;
3991 }
3992
3993 desc = strchr(id, ':');
3994 if (!desc) {
3995 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3996 return 1;
3997 }
3998 *desc++ = '\0';
3999
4000 p = default_params();
4001 decode_params(p, id);
4002 err = validate_desc(p, desc);
4003 if (err) {
4004 fprintf(stderr, "%s: %s\n", argv[0], err);
4005 return 1;
4006 }
4007 s = new_game(NULL, p, desc);
4008
4009 ret = solver(s->cr, s->blocks, s->xtype, s->grid, DIFF_RECURSIVE);
4010 if (grade) {
4011 printf("Difficulty rating: %s\n",
4012 ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
4013 ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
4014 ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
4015 ret==DIFF_SET ? "Advanced (set elimination required)":
4016 ret==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
4017 ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
4018 ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
4019 ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
4020 "INTERNAL ERROR: unrecognised difficulty code");
4021 } else {
4022 printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
4023 }
4024
4025 return 0;
4026 }
4027
4028 #endif