2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
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
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
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.
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.
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
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.
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:
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.)
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
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.
92 #ifdef STANDALONE_SOLVER
94 int solver_show_working
, solver_recurse_depth
;
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.
107 typedef unsigned char digit
;
108 #define ORDER_MAX 255
110 #define PREFERRED_TILE_SIZE 32
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113 #define GRIDEXTRA max((TILE_SIZE / 32),1)
115 #define FLASH_TIME 0.4F
117 enum { SYMM_NONE
, SYMM_ROT2
, SYMM_ROT4
, SYMM_REF2
, SYMM_REF2D
, SYMM_REF4
,
118 SYMM_REF4D
, SYMM_REF8
};
120 enum { DIFF_BLOCK
, DIFF_SIMPLE
, DIFF_INTERSECT
, DIFF_SET
, DIFF_EXTREME
,
121 DIFF_RECURSIVE
, DIFF_AMBIGUOUS
, DIFF_IMPOSSIBLE
};
137 * For a square puzzle, `c' and `r' indicate the puzzle
138 * parameters as described above.
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).
144 int c
, r
, symm
, diff
;
145 int xtype
; /* require all digits in X-diagonals */
148 struct block_structure
{
152 * For text formatting, we do need c and r here.
157 * For any square index, whichblock[i] gives its block index.
159 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
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
167 int *whichblock
, **blocks
;
169 #ifdef STANDALONE_SOLVER
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.
176 * Only blocknames itself needs individually freeing; it's all
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.
193 struct block_structure
*blocks
;
196 unsigned char *pencil
; /* c*r*c*r elements */
197 unsigned char *immutable
; /* marks which digits are clues */
198 int completed
, cheated
;
201 static game_params
*default_params(void)
203 game_params
*ret
= snew(game_params
);
207 ret
->symm
= SYMM_ROT2
; /* a plausible default */
208 ret
->diff
= DIFF_BLOCK
; /* so is this */
213 static void free_params(game_params
*params
)
218 static game_params
*dup_params(game_params
*params
)
220 game_params
*ret
= snew(game_params
);
221 *ret
= *params
; /* structure copy */
225 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
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
} },
245 { "3x4 Basic", { 3, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
246 { "4x4 Basic", { 4, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
250 if (i
< 0 || i
>= lenof(presets
))
253 *name
= dupstr(presets
[i
].title
);
254 *params
= dup_params(&presets
[i
].params
);
259 static void decode_params(game_params
*ret
, char const *string
)
263 ret
->c
= ret
->r
= atoi(string
);
265 while (*string
&& isdigit((unsigned char)*string
)) string
++;
266 if (*string
== 'x') {
268 ret
->r
= atoi(string
);
270 while (*string
&& isdigit((unsigned char)*string
)) string
++;
273 if (*string
== 'j') {
278 } else if (*string
== 'x') {
281 } else if (*string
== 'r' || *string
== 'm' || *string
== 'a') {
284 if (sc
== 'm' && *string
== 'd') {
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
;
303 ret
->symm
= SYMM_NONE
;
304 } else if (*string
== 'd') {
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
;
319 string
++; /* eat unknown character */
323 static char *encode_params(game_params
*params
, int full
)
328 sprintf(str
, "%dx%d", params
->c
, params
->r
);
330 sprintf(str
, "%dj", params
->c
);
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;
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;
357 static config_item
*game_configure(game_params
*params
)
362 ret
= snewn(7, config_item
);
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
);
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
);
376 ret
[2].name
= "\"X\" (require every number in each main diagonal)";
377 ret
[2].type
= C_BOOLEAN
;
379 ret
[2].ival
= params
->xtype
;
381 ret
[3].name
= "Jigsaw (irregularly shaped sub-blocks)";
382 ret
[3].type
= C_BOOLEAN
;
384 ret
[3].ival
= (params
->r
== 1);
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:"
391 ret
[4].ival
= params
->symm
;
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
;
406 static game_params
*custom_params(config_item
*cfg
)
408 game_params
*ret
= snew(game_params
);
410 ret
->c
= atoi(cfg
[0].sval
);
411 ret
->r
= atoi(cfg
[1].sval
);
412 ret
->xtype
= cfg
[2].ival
;
417 ret
->symm
= cfg
[4].ival
;
418 ret
->diff
= cfg
[5].ival
;
423 static char *validate_params(game_params
*params
, int full
)
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";
434 /* ----------------------------------------------------------------------
437 * This solver is used for two purposes:
438 * + to check solubility of a grid as we gradually remove numbers
440 * + to solve an externally generated puzzle when the user selects
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.
449 * Modes of reasoning currently supported:
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.
455 * - Numeric elimination: a square must have a particular number
456 * in because all the other numbers that could go in it are
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.
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
489 * - Forcing chains (see comment for solver_forcing().)
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
497 struct solver_usage
{
499 struct block_structure
*blocks
;
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.
505 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
506 * are macros below to help with this.
510 * This is the grid in which we write down our final
511 * deductions. y-coordinates in here are _not_ transformed.
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
519 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
521 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
523 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
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 / */
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)])
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))
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
543 static void solver_place(struct solver_usage
*usage
, int x
, int y
, int n
)
546 int sqindex
= y
*cr
+x
;
552 * Rule out all other numbers in this square.
554 for (i
= 1; i
<= cr
; i
++)
559 * Rule out this number in all other positions in the row.
561 for (i
= 0; i
< cr
; i
++)
566 * Rule out this number in all other positions in the column.
568 for (i
= 0; i
< cr
; i
++)
573 * Rule out this number in all other positions in the block.
575 bi
= usage
->blocks
->whichblock
[sqindex
];
576 for (i
= 0; i
< cr
; i
++) {
577 int bp
= usage
->blocks
->blocks
[bi
][i
];
583 * Enter the number in the result grid.
585 usage
->grid
[sqindex
] = n
;
588 * Cross out this number from the list of numbers left to place
589 * in its row, its column and its block.
591 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
592 usage
->blk
[bi
*cr
+n
-1] = TRUE
;
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
;
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
;
610 static int solver_elim(struct solver_usage
*usage
, int *indices
611 #ifdef STANDALONE_SOLVER
620 * Count the number of set bits within this section of the
625 for (i
= 0; i
< cr
; i
++)
626 if (usage
->cube
[indices
[i
]]) {
640 if (!usage
->grid
[y
*cr
+x
]) {
641 #ifdef STANDALONE_SOLVER
642 if (solver_show_working
) {
644 printf("%*s", solver_recurse_depth
*4, "");
648 printf(":\n%*s placing %d at (%d,%d)\n",
649 solver_recurse_depth
*4, "", n
, 1+x
, 1+y
);
652 solver_place(usage
, x
, y
, n
);
656 #ifdef STANDALONE_SOLVER
657 if (solver_show_working
) {
659 printf("%*s", solver_recurse_depth
*4, "");
663 printf(":\n%*s no possibilities available\n",
664 solver_recurse_depth
*4, "");
673 static int solver_intersect(struct solver_usage
*usage
,
674 int *indices1
, int *indices2
675 #ifdef STANDALONE_SOLVER
684 * Loop over the first domain and see if there's any set bit
685 * not also in the second.
687 for (i
= j
= 0; i
< cr
; i
++) {
689 while (j
< cr
&& indices2
[j
] < p
)
691 if (usage
->cube
[p
]) {
692 if (j
< cr
&& indices2
[j
] == p
)
693 continue; /* both domains contain this index */
695 return 0; /* there is, so we can't deduce */
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.
706 for (i
= j
= 0; i
< cr
; i
++) {
708 while (j
< cr
&& indices1
[j
] < p
)
710 if (usage
->cube
[p
] && (j
>= cr
|| indices1
[j
] != p
)) {
711 #ifdef STANDALONE_SOLVER
712 if (solver_show_working
) {
717 printf("%*s", solver_recurse_depth
*4, "");
729 printf("%*s ruling out %d at (%d,%d)\n",
730 solver_recurse_depth
*4, "", pn
, 1+px
, 1+py
);
733 ret
= +1; /* we did something */
741 struct solver_scratch
{
742 unsigned char *grid
, *rowidx
, *colidx
, *set
;
743 int *neighbours
, *bfsqueue
;
744 int *indexlist
, *indexlist2
;
745 #ifdef STANDALONE_SOLVER
750 static int solver_set(struct solver_usage
*usage
,
751 struct solver_scratch
*scratch
,
753 #ifdef STANDALONE_SOLVER
760 unsigned char *grid
= scratch
->grid
;
761 unsigned char *rowidx
= scratch
->rowidx
;
762 unsigned char *colidx
= scratch
->colidx
;
763 unsigned char *set
= scratch
->set
;
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.
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
]])
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
788 rowidx
[i
] = colidx
[first
] = FALSE
;
792 * Convert each of rowidx/colidx from a list of 0s and 1s to a
793 * list of the indices of the 1s.
795 for (i
= j
= 0; i
< cr
; i
++)
799 for (i
= j
= 0; i
< cr
; i
++)
805 * And create the smaller matrix.
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
]]];
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.
823 * We have a candidate set. If its size is <=1 or >=n-1
824 * then we move on immediately.
826 if (count
> 1 && count
< n
-1) {
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'.
833 for (i
= 0; i
< n
; i
++) {
835 for (j
= 0; j
< n
; j
++)
836 if (set
[j
] && grid
[i
*cr
+j
]) {
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
852 if (rows
> n
- count
) {
853 #ifdef STANDALONE_SOLVER
854 if (solver_show_working
) {
856 printf("%*s", solver_recurse_depth
*4,
861 printf(":\n%*s contradiction reached\n",
862 solver_recurse_depth
*4, "");
868 if (rows
>= n
- count
) {
869 int progress
= FALSE
;
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.
878 * This involves referring back through
879 * rowidx/colidx in order to work out which actual
880 * positions in the cube to meddle with.
882 for (i
= 0; i
< n
; i
++) {
884 for (j
= 0; j
< n
; j
++)
885 if (set
[j
] && grid
[i
*cr
+j
]) {
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
) {
899 printf("%*s", solver_recurse_depth
*4,
912 printf("%*s ruling out %d at (%d,%d)\n",
913 solver_recurse_depth
*4, "",
918 usage
->cube
[fpos
] = FALSE
;
930 * Binary increment: change the rightmost 0 to a 1, and
931 * change all 1s to the right of it to 0s.
934 while (i
> 0 && set
[i
-1])
935 set
[--i
] = 0, count
--;
937 set
[--i
] = 1, count
++;
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:
951 * (a) Each square on the path has precisely two possible numbers.
953 * (b) Each pair of squares which are adjacent on the path share
954 * at least one possible number in common.
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).
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:
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
969 * (d) The two end squares are both in line with some third
972 * (e) That third square currently has N as a possibility.
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.
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.
981 static int solver_forcing(struct solver_usage
*usage
,
982 struct solver_scratch
*scratch
)
985 int *bfsqueue
= scratch
->bfsqueue
;
986 #ifdef STANDALONE_SOLVER
987 int *bfsprev
= scratch
->bfsprev
;
989 unsigned char *number
= scratch
->grid
;
990 int *neighbours
= scratch
->neighbours
;
993 for (y
= 0; y
< cr
; y
++)
994 for (x
= 0; x
< cr
; x
++) {
998 * If this square doesn't have exactly two candidate
999 * numbers, don't try it.
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
1006 for (count
= t
= 0, n
= 1; n
<= cr
; n
++)
1013 * Now attempt a bfs for each candidate.
1015 for (n
= 1; n
<= cr
; n
++)
1016 if (cube(x
, y
, n
)) {
1017 int orign
, currn
, head
, tail
;
1024 memset(number
, cr
+1, cr
*cr
);
1026 bfsqueue
[tail
++] = y
*cr
+x
;
1027 #ifdef STANDALONE_SOLVER
1028 bfsprev
[y
*cr
+x
] = -1;
1030 number
[y
*cr
+x
] = t
- n
;
1032 while (head
< tail
) {
1033 int xx
, yy
, nneighbours
, xt
, yt
, i
;
1035 xx
= bfsqueue
[head
++];
1039 currn
= number
[yy
*cr
+xx
];
1042 * Find neighbours of yy,xx.
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
];
1053 int sqindex
= yy
*cr
+xx
;
1054 if (ondiag0(sqindex
)) {
1055 for (i
= 0; i
< cr
; i
++)
1056 neighbours
[nneighbours
++] = diag0(i
);
1058 if (ondiag1(sqindex
)) {
1059 for (i
= 0; i
< cr
; i
++)
1060 neighbours
[nneighbours
++] = diag1(i
);
1065 * Try visiting each of those neighbours.
1067 for (i
= 0; i
< nneighbours
; i
++) {
1070 xt
= neighbours
[i
] % cr
;
1071 yt
= neighbours
[i
] / cr
;
1074 * We need this square to not be
1075 * already visited, and to include
1076 * currn as a possible number.
1078 if (number
[yt
*cr
+xt
] <= cr
)
1080 if (!cube(xt
, yt
, currn
))
1084 * Don't visit _this_ square a second
1087 if (xt
== xx
&& yt
== yy
)
1091 * To continue with the bfs, we need
1092 * this square to have exactly two
1095 for (cc
= tt
= 0, nn
= 1; nn
<= cr
; nn
++)
1096 if (cube(xt
, yt
, nn
))
1099 bfsqueue
[tail
++] = yt
*cr
+xt
;
1100 #ifdef STANDALONE_SOLVER
1101 bfsprev
[yt
*cr
+xt
] = yy
*cr
+xx
;
1103 number
[yt
*cr
+xt
] = tt
- currn
;
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.
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
) {
1122 printf("%*sforcing chain, %d at ends of ",
1123 solver_recurse_depth
*4, "", orign
);
1127 printf("%s(%d,%d)", sep
, 1+xl
,
1129 xl
= bfsprev
[yl
*cr
+xl
];
1136 printf("\n%*s ruling out %d at (%d,%d)\n",
1137 solver_recurse_depth
*4, "",
1141 cube(xt
, yt
, orign
) = FALSE
;
1152 static struct solver_scratch
*solver_new_scratch(struct solver_usage
*usage
)
1154 struct solver_scratch
*scratch
= snew(struct solver_scratch
);
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);
1165 scratch
->indexlist
= snewn(cr
*cr
, int); /* used for set elimination */
1166 scratch
->indexlist2
= snewn(cr
, int); /* only used for intersect() */
1170 static void solver_free_scratch(struct solver_scratch
*scratch
)
1172 #ifdef STANDALONE_SOLVER
1173 sfree(scratch
->bfsprev
);
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
);
1186 static int solver(int cr
, struct block_structure
*blocks
, int xtype
,
1187 digit
*grid
, int maxdiff
)
1189 struct solver_usage
*usage
;
1190 struct solver_scratch
*scratch
;
1191 int x
, y
, b
, i
, n
, ret
;
1192 int diff
= DIFF_BLOCK
;
1195 * Set up a usage structure as a clean slate (everything
1198 usage
= snew(struct solver_usage
);
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
);
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
);
1213 usage
->diag
= snewn(cr
* 2, unsigned char);
1214 memset(usage
->diag
, FALSE
, cr
* 2);
1218 scratch
= solver_new_scratch(usage
);
1221 * Place all the clue numbers we are given.
1223 for (x
= 0; x
< cr
; x
++)
1224 for (y
= 0; y
< cr
; y
++)
1226 solver_place(usage
, x
, y
, grid
[y
*cr
+x
]);
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
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.
1246 * Blockwise positional elimination.
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
]
1261 diff
= DIFF_IMPOSSIBLE
;
1263 } else if (ret
> 0) {
1264 diff
= max(diff
, DIFF_BLOCK
);
1269 if (maxdiff
<= DIFF_BLOCK
)
1273 * Row-wise positional elimination.
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
1287 diff
= DIFF_IMPOSSIBLE
;
1289 } else if (ret
> 0) {
1290 diff
= max(diff
, DIFF_SIMPLE
);
1295 * Column-wise positional elimination.
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
1309 diff
= DIFF_IMPOSSIBLE
;
1311 } else if (ret
> 0) {
1312 diff
= max(diff
, DIFF_SIMPLE
);
1318 * X-diagonal positional elimination.
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
1332 diff
= DIFF_IMPOSSIBLE
;
1334 } else if (ret
> 0) {
1335 diff
= max(diff
, DIFF_SIMPLE
);
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
1350 diff
= DIFF_IMPOSSIBLE
;
1352 } else if (ret
> 0) {
1353 diff
= max(diff
, DIFF_SIMPLE
);
1360 * Numeric elimination.
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)",
1374 diff
= DIFF_IMPOSSIBLE
;
1376 } else if (ret
> 0) {
1377 diff
= max(diff
, DIFF_SIMPLE
);
1382 if (maxdiff
<= DIFF_SIMPLE
)
1386 * Intersectional analysis, rows vs blocks.
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])
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
);
1399 * solver_intersect() never returns -1.
1401 if (solver_intersect(usage
, scratch
->indexlist
,
1403 #ifdef STANDALONE_SOLVER
1404 , "intersectional analysis,"
1405 " %d in row %d vs block %s",
1406 n
, 1+y
, usage
->blocks
->blocknames
[b
]
1409 solver_intersect(usage
, scratch
->indexlist2
,
1411 #ifdef STANDALONE_SOLVER
1412 , "intersectional analysis,"
1413 " %d in block %s vs row %d",
1414 n
, usage
->blocks
->blocknames
[b
], 1+y
1417 diff
= max(diff
, DIFF_INTERSECT
);
1423 * Intersectional analysis, columns vs blocks.
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])
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
);
1435 if (solver_intersect(usage
, scratch
->indexlist
,
1437 #ifdef STANDALONE_SOLVER
1438 , "intersectional analysis,"
1439 " %d in column %d vs block %s",
1440 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1443 solver_intersect(usage
, scratch
->indexlist2
,
1445 #ifdef STANDALONE_SOLVER
1446 , "intersectional analysis,"
1447 " %d in block %s vs column %d",
1448 n
, usage
->blocks
->blocknames
[b
], 1+x
1451 diff
= max(diff
, DIFF_INTERSECT
);
1458 * Intersectional analysis, \-diagonal vs blocks.
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])
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
);
1469 if (solver_intersect(usage
, scratch
->indexlist
,
1471 #ifdef STANDALONE_SOLVER
1472 , "intersectional analysis,"
1473 " %d in \\-diagonal vs block %s",
1474 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1477 solver_intersect(usage
, scratch
->indexlist2
,
1479 #ifdef STANDALONE_SOLVER
1480 , "intersectional analysis,"
1481 " %d in block %s vs \\-diagonal",
1482 n
, usage
->blocks
->blocknames
[b
], 1+x
1485 diff
= max(diff
, DIFF_INTERSECT
);
1491 * Intersectional analysis, /-diagonal vs blocks.
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])
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
);
1502 if (solver_intersect(usage
, scratch
->indexlist
,
1504 #ifdef STANDALONE_SOLVER
1505 , "intersectional analysis,"
1506 " %d in /-diagonal vs block %s",
1507 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1510 solver_intersect(usage
, scratch
->indexlist2
,
1512 #ifdef STANDALONE_SOLVER
1513 , "intersectional analysis,"
1514 " %d in block %s vs /-diagonal",
1515 n
, usage
->blocks
->blocknames
[b
], 1+x
1518 diff
= max(diff
, DIFF_INTERSECT
);
1524 if (maxdiff
<= DIFF_INTERSECT
)
1528 * Blockwise set elimination.
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
]
1541 diff
= DIFF_IMPOSSIBLE
;
1543 } else if (ret
> 0) {
1544 diff
= max(diff
, DIFF_SET
);
1550 * Row-wise set elimination.
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
1562 diff
= DIFF_IMPOSSIBLE
;
1564 } else if (ret
> 0) {
1565 diff
= max(diff
, DIFF_SET
);
1571 * Column-wise set elimination.
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
1583 diff
= DIFF_IMPOSSIBLE
;
1585 } else if (ret
> 0) {
1586 diff
= max(diff
, DIFF_SET
);
1593 * \-diagonal set elimination.
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"
1604 diff
= DIFF_IMPOSSIBLE
;
1606 } else if (ret
> 0) {
1607 diff
= max(diff
, DIFF_SET
);
1612 * /-diagonal set elimination.
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"
1623 diff
= DIFF_IMPOSSIBLE
;
1625 } else if (ret
> 0) {
1626 diff
= max(diff
, DIFF_SET
);
1631 if (maxdiff
<= DIFF_SET
)
1635 * Row-vs-column set elimination on a single number.
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
1647 diff
= DIFF_IMPOSSIBLE
;
1649 } else if (ret
> 0) {
1650 diff
= max(diff
, DIFF_EXTREME
);
1658 if (solver_forcing(usage
, scratch
)) {
1659 diff
= max(diff
, DIFF_EXTREME
);
1664 * If we reach here, we have made no deductions in this
1665 * iteration, so the algorithm terminates.
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
1677 if (maxdiff
>= DIFF_RECURSIVE
) {
1678 int best
, bestcount
;
1683 for (y
= 0; y
< cr
; y
++)
1684 for (x
= 0; x
< cr
; x
++)
1685 if (!grid
[y
*cr
+x
]) {
1689 * An unfilled square. Count the number of
1690 * possible digits in it.
1693 for (n
= 1; n
<= cr
; n
++)
1698 * We should have found any impossibilities
1699 * already, so this can safely be an assert.
1703 if (count
< bestcount
) {
1711 digit
*list
, *ingrid
, *outgrid
;
1713 diff
= DIFF_IMPOSSIBLE
; /* no solution found yet */
1716 * Attempt recursion.
1721 list
= snewn(cr
, digit
);
1722 ingrid
= snewn(cr
* cr
, digit
);
1723 outgrid
= snewn(cr
* cr
, digit
);
1724 memcpy(ingrid
, grid
, cr
* cr
);
1726 /* Make a list of the possible digits. */
1727 for (j
= 0, n
= 1; n
<= cr
; n
++)
1731 #ifdef STANDALONE_SOLVER
1732 if (solver_show_working
) {
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
]);
1745 * And step along the list, recursing back into the
1746 * main solver at every stage.
1748 for (i
= 0; i
< j
; i
++) {
1751 memcpy(outgrid
, ingrid
, cr
* cr
);
1752 outgrid
[y
*cr
+x
] = list
[i
];
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
++;
1761 ret
= solver(cr
, blocks
, xtype
, outgrid
, maxdiff
);
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);
1772 * If we have our first solution, copy it into the
1773 * grid we will return.
1775 if (diff
== DIFF_IMPOSSIBLE
&& ret
!= DIFF_IMPOSSIBLE
)
1776 memcpy(grid
, outgrid
, cr
*cr
);
1778 if (ret
== DIFF_AMBIGUOUS
)
1779 diff
= DIFF_AMBIGUOUS
;
1780 else if (ret
== DIFF_IMPOSSIBLE
)
1781 /* do not change our return value */;
1783 /* the recursion turned up exactly one solution */
1784 if (diff
== DIFF_IMPOSSIBLE
)
1785 diff
= DIFF_RECURSIVE
;
1787 diff
= DIFF_AMBIGUOUS
;
1791 * As soon as we've found more than one solution,
1792 * give up immediately.
1794 if (diff
== DIFF_AMBIGUOUS
)
1805 * We're forbidden to use recursion, so we just see whether
1806 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1809 for (y
= 0; y
< cr
; y
++)
1810 for (x
= 0; x
< cr
; x
++)
1812 diff
= DIFF_IMPOSSIBLE
;
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" :
1832 solver_free_scratch(scratch
);
1837 /* ----------------------------------------------------------------------
1838 * End of solver code.
1841 /* ----------------------------------------------------------------------
1842 * Solo filled-grid generator.
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.
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.
1868 * Internal data structure used in gridgen to keep track of
1871 struct gridgen_coord
{ int x
, y
, r
; };
1872 struct gridgen_usage
{
1874 struct block_structure
*blocks
;
1875 /* grid is a copy of the input grid, modified as we go along */
1877 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1879 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1881 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
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
;
1888 /* If we need randomisation in the solve, this is our random state. */
1892 static void gridgen_place(struct gridgen_usage
*usage
, int x
, int y
, digit n
,
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
;
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
;
1904 usage
->grid
[y
*cr
+x
] = placing
? n
: 0;
1908 * The real recursive step in the generating function.
1910 * Return values: 1 means solution found, 0 means no solution
1911 * found on this branch.
1913 static int gridgen_real(struct gridgen_usage
*usage
, digit
*grid
, int *steps
)
1916 int i
, j
, n
, sx
, sy
, bestm
, bestr
, ret
;
1920 * Firstly, check for completion! If there are no spaces left
1921 * in the grid, we have a solution.
1923 if (usage
->nspaces
== 0)
1927 * Next, abandon generation if we went over our steps limit.
1934 * Otherwise, there must be at least one space. Find the most
1935 * constrained space, using the `r' field as a tie-breaker.
1937 bestm
= cr
+1; /* so that any space will beat it */
1940 for (j
= 0; j
< usage
->nspaces
; j
++) {
1941 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
1945 * Find the number of digits that could go in this space.
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
]))))
1955 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
1957 bestr
= usage
->spaces
[j
].r
;
1965 * Swap that square into the final place in the spaces array,
1966 * so that decrementing nspaces will remove it from the list.
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
;
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.
1980 digits
= snewn(bestm
, int);
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
])))) {
1991 shuffle(digits
, j
, sizeof(*digits
), usage
->rs
);
1993 /* And finally, go through the digit list and actually recurse. */
1995 for (i
= 0; i
< j
; i
++) {
1998 /* Update the usage structure to reflect the placing of this digit. */
1999 gridgen_place(usage
, sx
, sy
, n
, TRUE
);
2002 /* Call the solver recursively. Stop when we find a solution. */
2003 if (gridgen_real(usage
, grid
, steps
)) {
2008 /* Revert the usage structure. */
2009 gridgen_place(usage
, sx
, sy
, n
, FALSE
);
2018 * Entry point to generator. You give it parameters and a starting
2019 * grid, which is simply an array of cr*cr digits.
2021 static int gridgen(int cr
, struct block_structure
*blocks
, int xtype
,
2022 digit
*grid
, random_state
*rs
, int maxsteps
)
2024 struct gridgen_usage
*usage
;
2028 * Clear the grid to start with.
2030 memset(grid
, 0, cr
*cr
);
2033 * Create a gridgen_usage structure.
2035 usage
= snew(struct gridgen_usage
);
2038 usage
->blocks
= blocks
;
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
);
2050 usage
->diag
= snewn(2 * cr
, unsigned char);
2051 memset(usage
->diag
, FALSE
, 2 * cr
);
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
2063 for (x
= 0; x
< cr
; x
++)
2065 shuffle(grid
, cr
, sizeof(*grid
), rs
);
2066 for (x
= 0; x
< cr
; x
++)
2067 gridgen_place(usage
, x
, 0, grid
[x
], TRUE
);
2069 usage
->spaces
= snewn(cr
* cr
, struct gridgen_coord
);
2075 * Initialise the list of grid spaces, taking care to leave
2076 * out the row I've already filled in above.
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);
2088 * Run the real generator function.
2090 ret
= gridgen_real(usage
, grid
, &maxsteps
);
2093 * Clean up the usage structure now we have our answer.
2095 sfree(usage
->spaces
);
2104 /* ----------------------------------------------------------------------
2105 * End of grid generator code.
2109 * Check whether a grid contains a valid complete puzzle.
2111 static int check_valid(int cr
, struct block_structure
*blocks
, int xtype
,
2114 unsigned char *used
;
2117 used
= snewn(cr
, unsigned char);
2120 * Check that each row contains precisely one of everything.
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
++)
2135 * Check that each column contains precisely one of everything.
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
++)
2150 * Check that each block contains precisely one of everything.
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
++)
2166 * Check that each diagonal contains precisely one of everything.
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
++)
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
++)
2192 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
2194 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2197 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2203 break; /* just x,y is all we need */
2205 ADD(cr
- 1 - x
, cr
- 1 - y
);
2210 ADD(cr
- 1 - x
, cr
- 1 - y
);
2221 ADD(cr
- 1 - x
, cr
- 1 - y
);
2225 ADD(cr
- 1 - x
, cr
- 1 - y
);
2226 ADD(cr
- 1 - y
, cr
- 1 - x
);
2231 ADD(cr
- 1 - x
, cr
- 1 - y
);
2235 ADD(cr
- 1 - y
, cr
- 1 - x
);
2244 static char *encode_solve_move(int cr
, digit
*grid
)
2247 char *ret
, *p
, *sep
;
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
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).
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 */
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.
2273 ret
= snewn(len
, char);
2277 for (i
= 0; i
< cr
*cr
; i
++) {
2278 p
+= sprintf(p
, "%s%d", sep
, grid
[i
]);
2282 assert(p
- ret
== len
);
2287 static char *new_game_desc(game_params
*params
, random_state
*rs
,
2288 char **aux
, int interactive
)
2290 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2292 struct block_structure
*blocks
;
2293 digit
*grid
, *grid2
;
2294 struct xy
{ int x
, y
; } *locs
;
2297 int coords
[16], ncoords
;
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.
2307 maxdiff
= params
->diff
;
2308 if (c
== 2 && r
== 2)
2309 maxdiff
= DIFF_BLOCK
;
2311 grid
= snewn(area
, digit
);
2312 locs
= snewn(area
, struct xy
);
2313 grid2
= snewn(area
, digit
);
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");
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.
2332 * Generate a random solved state, starting by
2333 * constructing the block structure.
2335 if (r
== 1) { /* jigsaw mode */
2336 int *dsf
= divvy_rectangle(cr
, cr
, cr
, rs
);
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
];
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
);
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]++;
2361 blocks
->blocks
[b
][j
] = i
;
2364 if (!gridgen(cr
, blocks
, params
->xtype
, grid
, rs
, area
*area
))
2366 assert(check_valid(cr
, blocks
, params
->xtype
, grid
));
2369 * Save the solved grid in aux.
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.
2381 *aux
= encode_solve_move(cr
, grid
);
2385 * Now we have a solved grid, start removing things from it
2386 * while preserving solubility.
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.
2396 for (y
= 0; y
< cr
; y
++)
2397 for (x
= 0; x
< cr
; x
++) {
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
)
2413 * Now shuffle that list.
2415 shuffle(locs
, nlocs
, sizeof(*locs
), rs
);
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.
2422 for (i
= 0; i
< nlocs
; i
++) {
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;
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;
2440 memcpy(grid2
, grid
, area
);
2442 if (solver(cr
, blocks
, params
->xtype
, grid2
, maxdiff
) == maxdiff
)
2443 break; /* found one! */
2450 * Now we have the grid as it will be presented to the user.
2451 * Encode it in a game desc.
2457 desc
= snewn(7 * area
, char);
2460 for (i
= 0; i
<= area
; i
++) {
2461 int n
= (i
< area
? grid
[i
] : -1);
2468 int c
= 'a' - 1 + run
;
2472 run
-= c
- ('a' - 1);
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.
2480 if (p
> desc
&& n
> 0)
2484 p
+= sprintf(p
, "%d", n
);
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
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
2508 for (i
= 0; i
<= 2*cr
*(cr
-1); i
++) {
2511 if (i
== 2*cr
*(cr
-1)) {
2512 edge
= TRUE
; /* terminating virtual edge */
2514 if (i
< cr
*(cr
-1)) {
2525 edge
= (blocks
->whichblock
[p0
] != blocks
->whichblock
[p1
]);
2529 while (currrun
> 25)
2530 *p
++ = 'z', currrun
-= 25;
2532 *p
++ = 'a'-1 + currrun
;
2541 assert(p
- desc
< 7 * area
);
2543 desc
= sresize(desc
, p
- desc
, char);
2551 static char *validate_desc(game_params
*params
, char *desc
)
2553 int cr
= params
->c
* params
->r
, area
= cr
*cr
;
2557 while (*desc
&& *desc
!= ',') {
2559 if (n
>= 'a' && n
<= 'z') {
2560 squares
+= n
- 'a' + 1;
2561 } else if (n
== '_') {
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";
2568 while (*desc
>= '0' && *desc
<= '9')
2571 return "Invalid character in game description";
2575 return "Not enough data to fill grid";
2578 return "Too much data to fit in grid";
2580 if (params
->r
== 1) {
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
2590 return "Expected jigsaw block structure in game description";
2593 dsf
= snew_dsf(area
);
2601 else if (*desc
>= 'a' && *desc
<= 'z')
2602 c
= *desc
- 'a' + 1;
2605 return "Invalid character in game description";
2609 adv
= (c
!= 25); /* 'z' is a special case */
2615 * Non-edge; merge the two dsf classes on either
2618 if (pos
>= 2*cr
*(cr
-1)) {
2620 return "Too much data in block structure specification";
2621 } else if (pos
< cr
*(cr
-1)) {
2627 int x
= pos
/(cr
-1) - cr
;
2632 dsf_merge(dsf
, p0
, p1
);
2641 * When desc is exhausted, we expect to have gone exactly
2642 * one space _past_ the end of the grid, due to the dummy
2645 if (pos
!= 2*cr
*(cr
-1)+1) {
2647 return "Not enough data in block structure specification";
2651 * Now we've got our dsf. Verify that it matches
2655 int *canons
, *counts
;
2656 int i
, j
, c
, ncanons
= 0;
2658 canons
= snewn(cr
, int);
2659 counts
= snewn(cr
, int);
2661 for (i
= 0; i
< area
; i
++) {
2662 j
= dsf_canonify(dsf
, i
);
2664 for (c
= 0; c
< ncanons
; c
++)
2665 if (canons
[c
] == j
) {
2667 if (counts
[c
] > cr
) {
2671 return "A jigsaw block is too big";
2677 if (ncanons
>= cr
) {
2681 return "Too many distinct jigsaw blocks";
2683 canons
[ncanons
] = j
;
2684 counts
[ncanons
] = 1;
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.
2700 assert(ncanons
== cr
);
2701 for (c
= 0; c
< ncanons
; c
++)
2702 assert(counts
[c
] == cr
);
2711 return "Unexpected jigsaw block structure in game description";
2717 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
2719 game_state
*state
= snew(game_state
);
2720 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
2724 state
->xtype
= params
->xtype
;
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
);
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));
2743 state
->completed
= state
->cheated
= FALSE
;
2746 while (*desc
&& *desc
!= ',') {
2748 if (n
>= 'a' && n
<= 'z') {
2749 int run
= n
- 'a' + 1;
2750 assert(i
+ run
<= area
);
2752 state
->grid
[i
++] = 0;
2753 } else if (n
== '_') {
2755 } else if (n
> '0' && n
<= '9') {
2757 state
->immutable
[i
] = TRUE
;
2758 state
->grid
[i
++] = atoi(desc
-1);
2759 while (*desc
>= '0' && *desc
<= '9')
2762 assert(!"We can't get here");
2772 assert(*desc
== ',');
2774 dsf
= snew_dsf(area
);
2783 assert(*desc
>= 'a' && *desc
<= 'z');
2784 c
= *desc
- 'a' + 1;
2788 adv
= (c
!= 25); /* 'z' is a special case */
2794 * Non-edge; merge the two dsf classes on either
2797 assert(pos
< 2*cr
*(cr
-1));
2798 if (pos
< cr
*(cr
-1)) {
2804 int x
= pos
/(cr
-1) - cr
;
2809 dsf_merge(dsf
, p0
, p1
);
2818 * When desc is exhausted, we expect to have gone exactly
2819 * one space _past_ the end of the grid, due to the dummy
2822 assert(pos
== 2*cr
*(cr
-1)+1);
2825 * Now we've got our dsf. Translate it into a block
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
];
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
);
2851 * Having sorted out whichblock[], set up the block index arrays.
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]++;
2859 state
->blocks
->blocks
[b
][j
] = i
;
2862 #ifdef STANDALONE_SOLVER
2864 * Set up the block names for solver diagnostic output.
2867 char *p
= (char *)(state
->blocks
->blocknames
+ cr
);
2870 for (i
= 0; i
< cr
; i
++)
2871 state
->blocks
->blocknames
[i
] = NULL
;
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
);
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);
2889 assert(p
- (char *)state
->blocks
->blocknames
< cr
*(sizeof(char *)+80));
2890 for (i
= 0; i
< cr
; i
++)
2891 assert(state
->blocks
->blocknames
[i
]);
2898 static game_state
*dup_game(game_state
*state
)
2900 game_state
*ret
= snew(game_state
);
2901 int cr
= state
->cr
, area
= cr
* cr
;
2903 ret
->cr
= state
->cr
;
2904 ret
->xtype
= state
->xtype
;
2906 ret
->blocks
= state
->blocks
;
2907 ret
->blocks
->refcount
++;
2909 ret
->grid
= snewn(area
, digit
);
2910 memcpy(ret
->grid
, state
->grid
, area
);
2912 ret
->pencil
= snewn(area
* cr
, unsigned char);
2913 memcpy(ret
->pencil
, state
->pencil
, area
* cr
);
2915 ret
->immutable
= snewn(area
, unsigned char);
2916 memcpy(ret
->immutable
, state
->immutable
, area
);
2918 ret
->completed
= state
->completed
;
2919 ret
->cheated
= state
->cheated
;
2924 static void free_game(game_state
*state
)
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
);
2932 sfree(state
->blocks
);
2934 sfree(state
->immutable
);
2935 sfree(state
->pencil
);
2940 static char *solve_game(game_state
*state
, game_state
*currstate
,
2941 char *ai
, char **error
)
2949 * If we already have the solution in ai, save ourselves some
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
);
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";
2971 ret
= encode_solve_move(cr
, grid
);
2978 static char *grid_text_format(int cr
, struct block_structure
*blocks
,
2979 int xtype
, digit
*grid
)
2983 int totallen
, linelen
, nlines
;
2987 * For non-jigsaw Sudoku, we format in the way we always have,
2988 * by having the digits unevenly spaced so that the dividing
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
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.
3016 if (blocks
->r
!= 1) {
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.
3029 linelen
= 2*(cr
+ (cr
-1)/vmod
);
3032 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3035 nlines
= cr
+ (cr
-1)/hmod
;
3038 * Allocate the space.
3040 totallen
= linelen
* nlines
;
3041 ret
= snewn(totallen
+1, char); /* leave room for terminating NUL */
3047 for (y
= 0; y
< cr
; y
++) {
3051 for (x
= 0; x
< cr
; x
++) {
3055 digit d
= grid
[y
*cr
+x
];
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.
3063 if (xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
)))
3067 } else if (d
<= 9) {
3084 * Optional dividing line.
3086 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[y
*cr
+x
+1])
3093 if (y
== cr
-1 || (y
+1) % hmod
)
3099 for (x
= 0; x
< cr
; x
++) {
3104 * Division between two squares. This varies
3105 * complicatedly in length.
3107 dwid
= 2; /* digit and its following space */
3109 dwid
--; /* no following space at end of line */
3110 if (x
> 0 && x
% vmod
== 0)
3111 dwid
++; /* preceding space after a divider */
3113 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[(y
+1)*cr
+x
])
3130 * Corner square. This is:
3131 * - a space if all four surrounding squares are in
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.)
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];
3147 if (tl
== tr
&& tr
== bl
&& bl
== br
)
3149 else if (tl
== bl
&& tr
== br
)
3151 else if (tl
== tr
&& bl
== br
)
3160 assert(p
- ret
== totallen
);
3165 static int game_can_format_as_text_now(game_params
*params
)
3170 static char *game_text_format(game_state
*state
)
3172 return grid_text_format(state
->cr
, state
->blocks
, state
->xtype
,
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.
3185 * This indicates whether the current highlight is a
3186 * pencil-mark one or a real one.
3191 static game_ui
*new_ui(game_state
*state
)
3193 game_ui
*ui
= snew(game_ui
);
3195 ui
->hx
= ui
->hy
= -1;
3201 static void free_ui(game_ui
*ui
)
3206 static char *encode_ui(game_ui
*ui
)
3211 static void decode_ui(game_ui
*ui
, char *encoding
)
3215 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
3216 game_state
*newstate
)
3218 int cr
= newstate
->cr
;
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.
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;
3231 struct game_drawstate
{
3236 unsigned char *pencil
;
3238 /* This is scratch space used within a single call to game_redraw. */
3242 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
3243 int x
, int y
, int button
)
3249 button
&= ~MOD_MASK
;
3251 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
3252 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
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;
3265 return ""; /* UI activity occurred */
3267 if (button
== RIGHT_BUTTON
) {
3269 * Pencil-mode highlighting for non filled squares.
3271 if (state
->grid
[ty
*cr
+tx
] == 0) {
3272 if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
) {
3273 ui
->hx
= ui
->hy
= -1;
3280 ui
->hx
= ui
->hy
= -1;
3282 return ""; /* UI activity occurred */
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')
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
3305 if (state
->immutable
[ui
->hy
*cr
+ui
->hx
])
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.
3314 if (ui
->hpencil
&& state
->grid
[ui
->hy
*cr
+ui
->hx
])
3317 sprintf(buf
, "%c%d,%d,%d",
3318 (char)(ui
->hpencil
&& n
> 0 ? 'P' : 'R'), ui
->hx
, ui
->hy
, n
);
3320 ui
->hx
= ui
->hy
= -1;
3328 static game_state
*execute_move(game_state
*from
, char *move
)
3334 if (move
[0] == 'S') {
3337 ret
= dup_game(from
);
3338 ret
->completed
= ret
->cheated
= TRUE
;
3341 for (n
= 0; n
< cr
*cr
; n
++) {
3342 ret
->grid
[n
] = atoi(p
);
3344 if (!*p
|| ret
->grid
[n
] < 1 || ret
->grid
[n
] > cr
) {
3349 while (*p
&& isdigit((unsigned char)*p
)) p
++;
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
) {
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
];
3363 ret
->grid
[y
*cr
+x
] = n
;
3364 memset(ret
->pencil
+ (y
*cr
+x
)*cr
, 0, cr
);
3367 * We've made a real change to the grid. Check to see
3368 * if the game has been completed.
3370 if (!ret
->completed
&& check_valid(cr
, ret
->blocks
, ret
->xtype
,
3372 ret
->completed
= TRUE
;
3377 return NULL
; /* couldn't parse move string */
3380 /* ----------------------------------------------------------------------
3384 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3385 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3387 static void game_compute_size(game_params
*params
, int tilesize
,
3390 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3391 struct { int tilesize
; } ads
, *ds
= &ads
;
3392 ads
.tilesize
= tilesize
;
3394 *x
= SIZE(params
->c
* params
->r
);
3395 *y
= SIZE(params
->c
* params
->r
);
3398 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
3399 game_params
*params
, int tilesize
)
3401 ds
->tilesize
= tilesize
;
3404 static float *game_colours(frontend
*fe
, int *ncolours
)
3406 float *ret
= snewn(3 * NCOLOURS
, float);
3408 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
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];
3414 ret
[COL_GRID
* 3 + 0] = 0.0F
;
3415 ret
[COL_GRID
* 3 + 1] = 0.0F
;
3416 ret
[COL_GRID
* 3 + 2] = 0.0F
;
3418 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
3419 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
3420 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
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
;
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];
3430 ret
[COL_ERROR
* 3 + 0] = 1.0F
;
3431 ret
[COL_ERROR
* 3 + 1] = 0.0F
;
3432 ret
[COL_ERROR
* 3 + 2] = 0.0F
;
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];
3438 *ncolours
= NCOLOURS
;
3442 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
3444 struct game_drawstate
*ds
= snew(struct game_drawstate
);
3447 ds
->started
= FALSE
;
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 */
3461 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
3466 sfree(ds
->entered_items
);
3470 static void draw_number(drawing
*dr
, game_drawstate
*ds
, game_state
*state
,
3471 int x
, int y
, int hl
)
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 */
3483 tx
= BORDER
+ x
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3484 ty
= BORDER
+ y
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3488 cw
= TILE_SIZE
-1-2*GRIDEXTRA
;
3489 ch
= TILE_SIZE
-1-2*GRIDEXTRA
;
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])
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
])
3500 clip(dr
, cx
, cy
, cw
, ch
);
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
:
3509 * Draw the corners of thick lines in corner-adjacent squares,
3510 * which jut into this square by one pixel.
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
);
3521 /* pencil-mode highlight */
3522 if ((hl
& 15) == 2) {
3526 coords
[2] = cx
+cw
/2;
3529 coords
[5] = cy
+ch
/2;
3530 draw_polygon(dr
, coords
, 3, COL_HIGHLIGHT
, COL_HIGHLIGHT
);
3533 /* new number needs drawing? */
3534 if (state
->grid
[y
*cr
+x
]) {
3536 str
[0] = state
->grid
[y
*cr
+x
] + '0';
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
);
3544 int pw
, ph
, pmax
, fontsize
;
3546 /* count the pencil marks required */
3547 for (i
= npencil
= 0; i
< cr
; i
++)
3548 if (state
->pencil
[(y
*cr
+x
)*cr
+i
])
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.
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 */
3564 fontsize
= TILE_SIZE
/(pmax
*(11-pmax
)/8);
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
;
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
);
3584 draw_update(dr
, cx
, cy
, cw
, ch
);
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
;
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
)
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.
3605 draw_rect(dr
, 0, 0, SIZE(cr
), SIZE(cr
), COL_BACKGROUND
);
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.
3612 draw_rect(dr
, BORDER
-GRIDEXTRA
, BORDER
-GRIDEXTRA
,
3613 cr
*TILE_SIZE
+1+2*GRIDEXTRA
, cr
*TILE_SIZE
+1+2*GRIDEXTRA
,
3618 * This array is used to keep track of rows, columns and boxes
3619 * which contain a number more than once.
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
];
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;
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;
3641 * Draw any numbers which need redrawing.
3643 for (x
= 0; x
< cr
; x
++) {
3644 for (y
= 0; y
< cr
; y
++) {
3646 digit d
= state
->grid
[y
*cr
+x
];
3648 if (flashtime
> 0 &&
3649 (flashtime
<= FLASH_TIME
/3 ||
3650 flashtime
>= FLASH_TIME
*2/3))
3653 /* Highlight active input areas. */
3654 if (x
== ui
->hx
&& y
== ui
->hy
)
3655 highlight
= ui
->hpencil
? 2 : 1;
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))))))
3666 draw_number(dr
, ds
, state
, x
, y
, highlight
);
3671 * Update the _entire_ grid if necessary.
3674 draw_update(dr
, 0, 0, SIZE(cr
), SIZE(cr
));
3679 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
3680 int dir
, game_ui
*ui
)
3685 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3686 int dir
, game_ui
*ui
)
3688 if (!oldstate
->completed
&& newstate
->completed
&&
3689 !oldstate
->cheated
&& !newstate
->cheated
)
3694 static int game_timing_state(game_state
*state
, game_ui
*ui
)
3699 static void game_print_size(game_params
*params
, float *x
, float *y
)
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.
3708 game_compute_size(params
, 900, &pw
, &ph
);
3713 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3716 int ink
= print_mono_colour(dr
, 0);
3719 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3720 game_drawstate ads
, *ds
= &ads
;
3721 game_set_size(dr
, ds
, NULL
, tilesize
);
3726 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
3727 draw_rect_outline(dr
, BORDER
, BORDER
, cr
*TILE_SIZE
, cr
*TILE_SIZE
, ink
);
3730 * Highlight X-diagonal squares.
3734 int xhighlight
= print_grey_colour(dr
, 0.90F
);
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
);
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
);
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
);
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.
3771 int x
, y
, dx
, dy
, sx
, sy
, sdx
, sdy
;
3773 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
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
3785 coords
= snewn(4*cr
+4, int); /* 2k+2 points, 2 coords per point */
3788 * Iterate over all the blocks.
3790 for (bi
= 0; bi
< cr
; bi
++) {
3793 * For each block, find a starting square within it
3794 * which has a boundary at the left.
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
)
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
;
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.
3814 sx
= x
, sy
= y
, sdx
= dx
, sdy
= dy
; /* save starting position */
3817 int cx
, cy
, tx
, ty
, nin
;
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
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
;
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).
3848 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3849 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3852 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3853 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3862 } else if (nin
== 2) {
3886 * Now enforce by assertion that we ended up
3887 * somewhere sensible.
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
);
3894 } while (x
!= sx
|| y
!= sy
|| dx
!= sdx
|| dy
!= sdy
);
3897 * That's our polygon; now draw it.
3899 draw_polygon(dr
, coords
, n
, -1, ink
);
3908 for (y
= 0; y
< cr
; y
++)
3909 for (x
= 0; x
< cr
; x
++)
3910 if (state
->grid
[y
*cr
+x
]) {
3913 str
[0] = state
->grid
[y
*cr
+x
] + '0';
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
);
3924 #define thegame solo
3927 const struct game thegame
= {
3928 "Solo", "games.solo", "solo",
3935 TRUE
, game_configure
, custom_params
,
3943 TRUE
, game_can_format_as_text_now
, game_text_format
,
3951 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3954 game_free_drawstate
,
3958 TRUE
, FALSE
, game_print_size
, game_print
,
3959 FALSE
, /* wants_statusbar */
3960 FALSE
, game_timing_state
,
3961 REQUIRE_RBUTTON
| REQUIRE_NUMPAD
, /* flags */
3964 #ifdef STANDALONE_SOLVER
3966 int main(int argc
, char **argv
)
3970 char *id
= NULL
, *desc
, *err
;
3974 while (--argc
> 0) {
3976 if (!strcmp(p
, "-v")) {
3977 solver_show_working
= TRUE
;
3978 } else if (!strcmp(p
, "-g")) {
3980 } else if (*p
== '-') {
3981 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
3989 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
3993 desc
= strchr(id
, ':');
3995 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
4000 p
= default_params();
4001 decode_params(p
, id
);
4002 err
= validate_desc(p
, desc
);
4004 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
4007 s
= new_game(NULL
, p
, desc
);
4009 ret
= solver(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
, DIFF_RECURSIVE
);
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");
4022 printf("%s\n", grid_text_format(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
));