2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - Jigsaw Sudoku is currently an undocumented feature enabled
7 * by setting r (`Rows of sub-blocks' in the GUI configurer) to
8 * 1. The reason it's undocumented is because they're rather
9 * erratic to generate, because gridgen tends to hang up for
10 * ages. I think this is because some jigsaw block layouts
11 * simply do not admit very many valid filled grids (and
12 * perhaps some have none at all).
13 * + To fix this, I think probably the solution is a change in
14 * grid generation policy: gridgen needs to have less of an
15 * all-or-nothing attitude and instead make only a limited
16 * amount of effort to construct a filled grid before giving
17 * up and trying a new layout. (Come to think of it, this
18 * same change might also make 5x5 standard Sudoku more
19 * practical to generate, if correctly tuned.)
20 * + If I get this fixed, other work needed on jigsaw mode is:
21 * * introduce a GUI config checkbox. game_configure()
22 * ticks this box iff r==1; if it's ticked in a call to
23 * custom_params(), we replace (c, r) with (c*r, 1).
26 * - reports from users are that `Trivial'-mode puzzles are still
27 * rather hard compared to newspapers' easy ones, so some better
28 * low-end difficulty grading would be nice
29 * + it's possible that really easy puzzles always have
30 * _several_ things you can do, so don't make you hunt too
31 * hard for the one deduction you can currently make
32 * + it's also possible that easy puzzles require fewer
33 * cross-eliminations: perhaps there's a higher incidence of
34 * things you can deduce by looking only at (say) rows,
35 * rather than things you have to check both rows and columns
37 * + but really, what I need to do is find some really easy
38 * puzzles and _play_ them, to see what's actually easy about
40 * + while I'm revamping this area, filling in the _last_
41 * number in a nearly-full row or column should certainly be
42 * permitted even at the lowest difficulty level.
43 * + also Owen noticed that `Basic' grids requiring numeric
44 * elimination are actually very hard, so I wonder if a
45 * difficulty gradation between that and positional-
46 * elimination-only might be in order
47 * + but it's not good to have _too_ many difficulty levels, or
48 * it'll take too long to randomly generate a given level.
50 * - it might still be nice to do some prioritisation on the
51 * removal of numbers from the grid
52 * + one possibility is to try to minimise the maximum number
53 * of filled squares in any block, which in particular ought
54 * to enforce never leaving a completely filled block in the
55 * puzzle as presented.
57 * - alternative interface modes
58 * + sudoku.com's Windows program has a palette of possible
59 * entries; you select a palette entry first and then click
60 * on the square you want it to go in, thus enabling
61 * mouse-only play. Useful for PDAs! I don't think it's
62 * actually incompatible with the current highlight-then-type
63 * approach: you _either_ highlight a palette entry and then
64 * click, _or_ you highlight a square and then type. At most
65 * one thing is ever highlighted at a time, so there's no way
67 * + then again, I don't actually like sudoku.com's interface;
68 * it's too much like a paint package whereas I prefer to
69 * think of Solo as a text editor.
70 * + another PDA-friendly possibility is a drag interface:
71 * _drag_ numbers from the palette into the grid squares.
72 * Thought experiments suggest I'd prefer that to the
73 * sudoku.com approach, but I haven't actually tried it.
77 * Solo puzzles need to be square overall (since each row and each
78 * column must contain one of every digit), but they need not be
79 * subdivided the same way internally. I am going to adopt a
80 * convention whereby I _always_ refer to `r' as the number of rows
81 * of _big_ divisions, and `c' as the number of columns of _big_
82 * divisions. Thus, a 2c by 3r puzzle looks something like this:
86 * ------+------ (Of course, you can't subdivide it the other way
87 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
88 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
89 * ------+------ box down on the left-hand side.)
93 * The need for a strong naming convention should now be clear:
94 * each small box is two rows of digits by three columns, while the
95 * overall puzzle has three rows of small boxes by two columns. So
96 * I will (hopefully) consistently use `r' to denote the number of
97 * rows _of small boxes_ (here 3), which is also the number of
98 * columns of digits in each small box; and `c' vice versa (here
101 * I'm also going to choose arbitrarily to list c first wherever
102 * possible: the above is a 2x3 puzzle, not a 3x2 one.
112 #ifdef STANDALONE_SOLVER
114 int solver_show_working
, solver_recurse_depth
;
120 * To save space, I store digits internally as unsigned char. This
121 * imposes a hard limit of 255 on the order of the puzzle. Since
122 * even a 5x5 takes unacceptably long to generate, I don't see this
123 * as a serious limitation unless something _really_ impressive
124 * happens in computing technology; but here's a typedef anyway for
125 * general good practice.
127 typedef unsigned char digit
;
128 #define ORDER_MAX 255
130 #define PREFERRED_TILE_SIZE 32
131 #define TILE_SIZE (ds->tilesize)
132 #define BORDER (TILE_SIZE / 2)
133 #define GRIDEXTRA (TILE_SIZE / 32)
135 #define FLASH_TIME 0.4F
137 enum { SYMM_NONE
, SYMM_ROT2
, SYMM_ROT4
, SYMM_REF2
, SYMM_REF2D
, SYMM_REF4
,
138 SYMM_REF4D
, SYMM_REF8
};
140 enum { DIFF_BLOCK
, DIFF_SIMPLE
, DIFF_INTERSECT
, DIFF_SET
, DIFF_EXTREME
,
141 DIFF_RECURSIVE
, DIFF_AMBIGUOUS
, DIFF_IMPOSSIBLE
};
157 * For a square puzzle, `c' and `r' indicate the puzzle
158 * parameters as described above.
160 * A jigsaw-style puzzle is indicated by r==1, in which case c
161 * can be whatever it likes (there is no constraint on
162 * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
164 int c
, r
, symm
, diff
;
165 int xtype
; /* require all digits in X-diagonals */
168 struct block_structure
{
172 * For text formatting, we do need c and r here.
177 * For any square index, whichblock[i] gives its block index.
179 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
182 * whichblock and blocks are each dynamically allocated in
183 * their own right, but the subarrays in blocks are appended
184 * to the whichblock array, so shouldn't be freed
187 int *whichblock
, **blocks
;
189 #ifdef STANDALONE_SOLVER
191 * Textual descriptions of each block. For normal Sudoku these
192 * are of the form "(1,3)"; for jigsaw they are "starting at
193 * (5,7)". So the sensible usage in both cases is to say
194 * "elimination within block %s" with one of these strings.
196 * Only blocknames itself needs individually freeing; it's all
205 * For historical reasons, I use `cr' to denote the overall
206 * width/height of the puzzle. It was a natural notation when
207 * all puzzles were divided into blocks in a grid, but doesn't
208 * really make much sense given jigsaw puzzles. However, the
209 * obvious `n' is heavily used in the solver to describe the
210 * index of a number being placed, so `cr' will have to stay.
213 struct block_structure
*blocks
;
216 unsigned char *pencil
; /* c*r*c*r elements */
217 unsigned char *immutable
; /* marks which digits are clues */
218 int completed
, cheated
;
221 static game_params
*default_params(void)
223 game_params
*ret
= snew(game_params
);
227 ret
->symm
= SYMM_ROT2
; /* a plausible default */
228 ret
->diff
= DIFF_BLOCK
; /* so is this */
233 static void free_params(game_params
*params
)
238 static game_params
*dup_params(game_params
*params
)
240 game_params
*ret
= snew(game_params
);
241 *ret
= *params
; /* structure copy */
245 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
251 { "2x2 Trivial", { 2, 2, SYMM_ROT2
, DIFF_BLOCK
, FALSE
} },
252 { "2x3 Basic", { 2, 3, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
253 { "3x3 Trivial", { 3, 3, SYMM_ROT2
, DIFF_BLOCK
, FALSE
} },
254 { "3x3 Basic", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
255 { "3x3 Basic X", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
, TRUE
} },
256 { "3x3 Intermediate", { 3, 3, SYMM_ROT2
, DIFF_INTERSECT
, FALSE
} },
257 { "3x3 Advanced", { 3, 3, SYMM_ROT2
, DIFF_SET
, FALSE
} },
258 { "3x3 Advanced X", { 3, 3, SYMM_ROT2
, DIFF_SET
, TRUE
} },
259 { "3x3 Extreme", { 3, 3, SYMM_ROT2
, DIFF_EXTREME
, FALSE
} },
260 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2
, DIFF_RECURSIVE
, FALSE
} },
262 { "3x4 Basic", { 3, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
263 { "4x4 Basic", { 4, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
267 if (i
< 0 || i
>= lenof(presets
))
270 *name
= dupstr(presets
[i
].title
);
271 *params
= dup_params(&presets
[i
].params
);
276 static void decode_params(game_params
*ret
, char const *string
)
280 ret
->c
= ret
->r
= atoi(string
);
282 while (*string
&& isdigit((unsigned char)*string
)) string
++;
283 if (*string
== 'x') {
285 ret
->r
= atoi(string
);
287 while (*string
&& isdigit((unsigned char)*string
)) string
++;
290 if (*string
== 'j') {
295 } else if (*string
== 'x') {
298 } else if (*string
== 'r' || *string
== 'm' || *string
== 'a') {
301 if (sc
== 'm' && *string
== 'd') {
308 while (*string
&& isdigit((unsigned char)*string
)) string
++;
309 if (sc
== 'm' && sn
== 8)
310 ret
->symm
= SYMM_REF8
;
311 if (sc
== 'm' && sn
== 4)
312 ret
->symm
= sd ? SYMM_REF4D
: SYMM_REF4
;
313 if (sc
== 'm' && sn
== 2)
314 ret
->symm
= sd ? SYMM_REF2D
: SYMM_REF2
;
315 if (sc
== 'r' && sn
== 4)
316 ret
->symm
= SYMM_ROT4
;
317 if (sc
== 'r' && sn
== 2)
318 ret
->symm
= SYMM_ROT2
;
320 ret
->symm
= SYMM_NONE
;
321 } else if (*string
== 'd') {
323 if (*string
== 't') /* trivial */
324 string
++, ret
->diff
= DIFF_BLOCK
;
325 else if (*string
== 'b') /* basic */
326 string
++, ret
->diff
= DIFF_SIMPLE
;
327 else if (*string
== 'i') /* intermediate */
328 string
++, ret
->diff
= DIFF_INTERSECT
;
329 else if (*string
== 'a') /* advanced */
330 string
++, ret
->diff
= DIFF_SET
;
331 else if (*string
== 'e') /* extreme */
332 string
++, ret
->diff
= DIFF_EXTREME
;
333 else if (*string
== 'u') /* unreasonable */
334 string
++, ret
->diff
= DIFF_RECURSIVE
;
336 string
++; /* eat unknown character */
340 static char *encode_params(game_params
*params
, int full
)
345 sprintf(str
, "%dx%d", params
->c
, params
->r
);
347 sprintf(str
, "%dj", params
->c
);
352 switch (params
->symm
) {
353 case SYMM_REF8
: strcat(str
, "m8"); break;
354 case SYMM_REF4
: strcat(str
, "m4"); break;
355 case SYMM_REF4D
: strcat(str
, "md4"); break;
356 case SYMM_REF2
: strcat(str
, "m2"); break;
357 case SYMM_REF2D
: strcat(str
, "md2"); break;
358 case SYMM_ROT4
: strcat(str
, "r4"); break;
359 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
360 case SYMM_NONE
: strcat(str
, "a"); break;
362 switch (params
->diff
) {
363 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
364 case DIFF_SIMPLE
: strcat(str
, "db"); break;
365 case DIFF_INTERSECT
: strcat(str
, "di"); break;
366 case DIFF_SET
: strcat(str
, "da"); break;
367 case DIFF_EXTREME
: strcat(str
, "de"); break;
368 case DIFF_RECURSIVE
: strcat(str
, "du"); break;
374 static config_item
*game_configure(game_params
*params
)
379 ret
= snewn(6, config_item
);
381 ret
[0].name
= "Columns of sub-blocks";
382 ret
[0].type
= C_STRING
;
383 sprintf(buf
, "%d", params
->c
);
384 ret
[0].sval
= dupstr(buf
);
387 ret
[1].name
= "Rows of sub-blocks";
388 ret
[1].type
= C_STRING
;
389 sprintf(buf
, "%d", params
->r
);
390 ret
[1].sval
= dupstr(buf
);
393 ret
[2].name
= "\"X\" (require every number in each main diagonal)";
394 ret
[2].type
= C_BOOLEAN
;
396 ret
[2].ival
= params
->xtype
;
398 ret
[3].name
= "Symmetry";
399 ret
[3].type
= C_CHOICES
;
400 ret
[3].sval
= ":None:2-way rotation:4-way rotation:2-way mirror:"
401 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
403 ret
[3].ival
= params
->symm
;
405 ret
[4].name
= "Difficulty";
406 ret
[4].type
= C_CHOICES
;
407 ret
[4].sval
= ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
408 ret
[4].ival
= params
->diff
;
418 static game_params
*custom_params(config_item
*cfg
)
420 game_params
*ret
= snew(game_params
);
422 ret
->c
= atoi(cfg
[0].sval
);
423 ret
->r
= atoi(cfg
[1].sval
);
424 ret
->xtype
= cfg
[2].ival
;
425 ret
->symm
= cfg
[3].ival
;
426 ret
->diff
= cfg
[4].ival
;
431 static char *validate_params(game_params
*params
, int full
)
434 return "Both dimensions must be at least 2";
435 if (params
->c
> ORDER_MAX
|| params
->r
> ORDER_MAX
)
436 return "Dimensions greater than "STR(ORDER_MAX
)" are not supported";
437 if ((params
->c
* params
->r
) > 35)
438 return "Unable to support more than 35 distinct symbols in a puzzle";
442 /* ----------------------------------------------------------------------
445 * This solver is used for two purposes:
446 * + to check solubility of a grid as we gradually remove numbers
448 * + to solve an externally generated puzzle when the user selects
451 * It supports a variety of specific modes of reasoning. By
452 * enabling or disabling subsets of these modes we can arrange a
453 * range of difficulty levels.
457 * Modes of reasoning currently supported:
459 * - Positional elimination: a number must go in a particular
460 * square because all the other empty squares in a given
461 * row/col/blk are ruled out.
463 * - Numeric elimination: a square must have a particular number
464 * in because all the other numbers that could go in it are
467 * - Intersectional analysis: given two domains which overlap
468 * (hence one must be a block, and the other can be a row or
469 * col), if the possible locations for a particular number in
470 * one of the domains can be narrowed down to the overlap, then
471 * that number can be ruled out everywhere but the overlap in
472 * the other domain too.
474 * - Set elimination: if there is a subset of the empty squares
475 * within a domain such that the union of the possible numbers
476 * in that subset has the same size as the subset itself, then
477 * those numbers can be ruled out everywhere else in the domain.
478 * (For example, if there are five empty squares and the
479 * possible numbers in each are 12, 23, 13, 134 and 1345, then
480 * the first three empty squares form such a subset: the numbers
481 * 1, 2 and 3 _must_ be in those three squares in some
482 * permutation, and hence we can deduce none of them can be in
483 * the fourth or fifth squares.)
484 * + You can also see this the other way round, concentrating
485 * on numbers rather than squares: if there is a subset of
486 * the unplaced numbers within a domain such that the union
487 * of all their possible positions has the same size as the
488 * subset itself, then all other numbers can be ruled out for
489 * those positions. However, it turns out that this is
490 * exactly equivalent to the first formulation at all times:
491 * there is a 1-1 correspondence between suitable subsets of
492 * the unplaced numbers and suitable subsets of the unfilled
493 * places, found by taking the _complement_ of the union of
494 * the numbers' possible positions (or the spaces' possible
497 * - Forcing chains (see comment for solver_forcing().)
499 * - Recursion. If all else fails, we pick one of the currently
500 * most constrained empty squares and take a random guess at its
501 * contents, then continue solving on that basis and see if we
505 struct solver_usage
{
507 struct block_structure
*blocks
;
509 * We set up a cubic array, indexed by x, y and digit; each
510 * element of this array is TRUE or FALSE according to whether
511 * or not that digit _could_ in principle go in that position.
513 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
514 * are macros below to help with this.
518 * This is the grid in which we write down our final
519 * deductions. y-coordinates in here are _not_ transformed.
523 * Now we keep track, at a slightly higher level, of what we
524 * have yet to work out, to prevent doing the same deduction
527 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
529 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
531 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
533 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
534 unsigned char *diag
; /* diag 0 is \, 1 is / */
536 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
537 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
538 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
539 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
541 #define ondiag0(xy) ((xy) % (cr+1) == 0)
542 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
543 #define diag0(i) ((i) * (cr+1))
544 #define diag1(i) ((i+1) * (cr-1))
547 * Function called when we are certain that a particular square has
548 * a particular number in it. The y-coordinate passed in here is
551 static void solver_place(struct solver_usage
*usage
, int x
, int y
, int n
)
554 int sqindex
= y
*cr
+x
;
560 * Rule out all other numbers in this square.
562 for (i
= 1; i
<= cr
; i
++)
567 * Rule out this number in all other positions in the row.
569 for (i
= 0; i
< cr
; i
++)
574 * Rule out this number in all other positions in the column.
576 for (i
= 0; i
< cr
; i
++)
581 * Rule out this number in all other positions in the block.
583 bi
= usage
->blocks
->whichblock
[sqindex
];
584 for (i
= 0; i
< cr
; i
++) {
585 int bp
= usage
->blocks
->blocks
[bi
][i
];
591 * Enter the number in the result grid.
593 usage
->grid
[sqindex
] = n
;
596 * Cross out this number from the list of numbers left to place
597 * in its row, its column and its block.
599 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
600 usage
->blk
[bi
*cr
+n
-1] = TRUE
;
603 if (ondiag0(sqindex
)) {
604 for (i
= 0; i
< cr
; i
++)
605 if (diag0(i
) != sqindex
)
606 cube2(diag0(i
),n
) = FALSE
;
607 usage
->diag
[n
-1] = TRUE
;
609 if (ondiag1(sqindex
)) {
610 for (i
= 0; i
< cr
; i
++)
611 if (diag1(i
) != sqindex
)
612 cube2(diag1(i
),n
) = FALSE
;
613 usage
->diag
[cr
+n
-1] = TRUE
;
618 static int solver_elim(struct solver_usage
*usage
, int *indices
619 #ifdef STANDALONE_SOLVER
628 * Count the number of set bits within this section of the
633 for (i
= 0; i
< cr
; i
++)
634 if (usage
->cube
[indices
[i
]]) {
648 if (!usage
->grid
[y
*cr
+x
]) {
649 #ifdef STANDALONE_SOLVER
650 if (solver_show_working
) {
652 printf("%*s", solver_recurse_depth
*4, "");
656 printf(":\n%*s placing %d at (%d,%d)\n",
657 solver_recurse_depth
*4, "", n
, 1+x
, 1+y
);
660 solver_place(usage
, x
, y
, n
);
664 #ifdef STANDALONE_SOLVER
665 if (solver_show_working
) {
667 printf("%*s", solver_recurse_depth
*4, "");
671 printf(":\n%*s no possibilities available\n",
672 solver_recurse_depth
*4, "");
681 static int solver_intersect(struct solver_usage
*usage
,
682 int *indices1
, int *indices2
683 #ifdef STANDALONE_SOLVER
692 * Loop over the first domain and see if there's any set bit
693 * not also in the second.
695 for (i
= j
= 0; i
< cr
; i
++) {
697 while (j
< cr
&& indices2
[j
] < p
)
699 if (usage
->cube
[p
]) {
700 if (j
< cr
&& indices2
[j
] == p
)
701 continue; /* both domains contain this index */
703 return 0; /* there is, so we can't deduce */
708 * We have determined that all set bits in the first domain are
709 * within its overlap with the second. So loop over the second
710 * domain and remove all set bits that aren't also in that
711 * overlap; return +1 iff we actually _did_ anything.
714 for (i
= j
= 0; i
< cr
; i
++) {
716 while (j
< cr
&& indices1
[j
] < p
)
718 if (usage
->cube
[p
] && (j
>= cr
|| indices1
[j
] != p
)) {
719 #ifdef STANDALONE_SOLVER
720 if (solver_show_working
) {
725 printf("%*s", solver_recurse_depth
*4, "");
737 printf("%*s ruling out %d at (%d,%d)\n",
738 solver_recurse_depth
*4, "", pn
, 1+px
, 1+py
);
741 ret
= +1; /* we did something */
749 struct solver_scratch
{
750 unsigned char *grid
, *rowidx
, *colidx
, *set
;
751 int *neighbours
, *bfsqueue
;
752 int *indexlist
, *indexlist2
;
753 #ifdef STANDALONE_SOLVER
758 static int solver_set(struct solver_usage
*usage
,
759 struct solver_scratch
*scratch
,
761 #ifdef STANDALONE_SOLVER
768 unsigned char *grid
= scratch
->grid
;
769 unsigned char *rowidx
= scratch
->rowidx
;
770 unsigned char *colidx
= scratch
->colidx
;
771 unsigned char *set
= scratch
->set
;
774 * We are passed a cr-by-cr matrix of booleans. Our first job
775 * is to winnow it by finding any definite placements - i.e.
776 * any row with a solitary 1 - and discarding that row and the
777 * column containing the 1.
779 memset(rowidx
, TRUE
, cr
);
780 memset(colidx
, TRUE
, cr
);
781 for (i
= 0; i
< cr
; i
++) {
782 int count
= 0, first
= -1;
783 for (j
= 0; j
< cr
; j
++)
784 if (usage
->cube
[indices
[i
*cr
+j
]])
788 * If count == 0, then there's a row with no 1s at all and
789 * the puzzle is internally inconsistent. However, we ought
790 * to have caught this already during the simpler reasoning
791 * methods, so we can safely fail an assertion if we reach
796 rowidx
[i
] = colidx
[first
] = FALSE
;
800 * Convert each of rowidx/colidx from a list of 0s and 1s to a
801 * list of the indices of the 1s.
803 for (i
= j
= 0; i
< cr
; i
++)
807 for (i
= j
= 0; i
< cr
; i
++)
813 * And create the smaller matrix.
815 for (i
= 0; i
< n
; i
++)
816 for (j
= 0; j
< n
; j
++)
817 grid
[i
*cr
+j
] = usage
->cube
[indices
[rowidx
[i
]*cr
+colidx
[j
]]];
820 * Having done that, we now have a matrix in which every row
821 * has at least two 1s in. Now we search to see if we can find
822 * a rectangle of zeroes (in the set-theoretic sense of
823 * `rectangle', i.e. a subset of rows crossed with a subset of
824 * columns) whose width and height add up to n.
831 * We have a candidate set. If its size is <=1 or >=n-1
832 * then we move on immediately.
834 if (count
> 1 && count
< n
-1) {
836 * The number of rows we need is n-count. See if we can
837 * find that many rows which each have a zero in all
838 * the positions listed in `set'.
841 for (i
= 0; i
< n
; i
++) {
843 for (j
= 0; j
< n
; j
++)
844 if (set
[j
] && grid
[i
*cr
+j
]) {
853 * We expect never to be able to get _more_ than
854 * n-count suitable rows: this would imply that (for
855 * example) there are four numbers which between them
856 * have at most three possible positions, and hence it
857 * indicates a faulty deduction before this point or
860 if (rows
> n
- count
) {
861 #ifdef STANDALONE_SOLVER
862 if (solver_show_working
) {
864 printf("%*s", solver_recurse_depth
*4,
869 printf(":\n%*s contradiction reached\n",
870 solver_recurse_depth
*4, "");
876 if (rows
>= n
- count
) {
877 int progress
= FALSE
;
880 * We've got one! Now, for each row which _doesn't_
881 * satisfy the criterion, eliminate all its set
882 * bits in the positions _not_ listed in `set'.
883 * Return +1 (meaning progress has been made) if we
884 * successfully eliminated anything at all.
886 * This involves referring back through
887 * rowidx/colidx in order to work out which actual
888 * positions in the cube to meddle with.
890 for (i
= 0; i
< n
; i
++) {
892 for (j
= 0; j
< n
; j
++)
893 if (set
[j
] && grid
[i
*cr
+j
]) {
898 for (j
= 0; j
< n
; j
++)
899 if (!set
[j
] && grid
[i
*cr
+j
]) {
900 int fpos
= indices
[rowidx
[i
]*cr
+colidx
[j
]];
901 #ifdef STANDALONE_SOLVER
902 if (solver_show_working
) {
907 printf("%*s", solver_recurse_depth
*4,
920 printf("%*s ruling out %d at (%d,%d)\n",
921 solver_recurse_depth
*4, "",
926 usage
->cube
[fpos
] = FALSE
;
938 * Binary increment: change the rightmost 0 to a 1, and
939 * change all 1s to the right of it to 0s.
942 while (i
> 0 && set
[i
-1])
943 set
[--i
] = 0, count
--;
945 set
[--i
] = 1, count
++;
954 * Look for forcing chains. A forcing chain is a path of
955 * pairwise-exclusive squares (i.e. each pair of adjacent squares
956 * in the path are in the same row, column or block) with the
957 * following properties:
959 * (a) Each square on the path has precisely two possible numbers.
961 * (b) Each pair of squares which are adjacent on the path share
962 * at least one possible number in common.
964 * (c) Each square in the middle of the path shares _both_ of its
965 * numbers with at least one of its neighbours (not the same
966 * one with both neighbours).
968 * These together imply that at least one of the possible number
969 * choices at one end of the path forces _all_ the rest of the
970 * numbers along the path. In order to make real use of this, we
971 * need further properties:
973 * (c) Ruling out some number N from the square at one end of the
974 * path forces the square at the other end to take the same
977 * (d) The two end squares are both in line with some third
980 * (e) That third square currently has N as a possibility.
982 * If we can find all of that lot, we can deduce that at least one
983 * of the two ends of the forcing chain has number N, and that
984 * therefore the mutually adjacent third square does not.
986 * To find forcing chains, we're going to start a bfs at each
987 * suitable square, once for each of its two possible numbers.
989 static int solver_forcing(struct solver_usage
*usage
,
990 struct solver_scratch
*scratch
)
993 int *bfsqueue
= scratch
->bfsqueue
;
994 #ifdef STANDALONE_SOLVER
995 int *bfsprev
= scratch
->bfsprev
;
997 unsigned char *number
= scratch
->grid
;
998 int *neighbours
= scratch
->neighbours
;
1001 for (y
= 0; y
< cr
; y
++)
1002 for (x
= 0; x
< cr
; x
++) {
1006 * If this square doesn't have exactly two candidate
1007 * numbers, don't try it.
1009 * In this loop we also sum the candidate numbers,
1010 * which is a nasty hack to allow us to quickly find
1011 * `the other one' (since we will shortly know there
1014 for (count
= t
= 0, n
= 1; n
<= cr
; n
++)
1021 * Now attempt a bfs for each candidate.
1023 for (n
= 1; n
<= cr
; n
++)
1024 if (cube(x
, y
, n
)) {
1025 int orign
, currn
, head
, tail
;
1032 memset(number
, cr
+1, cr
*cr
);
1034 bfsqueue
[tail
++] = y
*cr
+x
;
1035 #ifdef STANDALONE_SOLVER
1036 bfsprev
[y
*cr
+x
] = -1;
1038 number
[y
*cr
+x
] = t
- n
;
1040 while (head
< tail
) {
1041 int xx
, yy
, nneighbours
, xt
, yt
, i
;
1043 xx
= bfsqueue
[head
++];
1047 currn
= number
[yy
*cr
+xx
];
1050 * Find neighbours of yy,xx.
1053 for (yt
= 0; yt
< cr
; yt
++)
1054 neighbours
[nneighbours
++] = yt
*cr
+xx
;
1055 for (xt
= 0; xt
< cr
; xt
++)
1056 neighbours
[nneighbours
++] = yy
*cr
+xt
;
1057 xt
= usage
->blocks
->whichblock
[yy
*cr
+xx
];
1058 for (yt
= 0; yt
< cr
; yt
++)
1059 neighbours
[nneighbours
++] = usage
->blocks
->blocks
[xt
][yt
];
1061 int sqindex
= yy
*cr
+xx
;
1062 if (ondiag0(sqindex
)) {
1063 for (i
= 0; i
< cr
; i
++)
1064 neighbours
[nneighbours
++] = diag0(i
);
1066 if (ondiag1(sqindex
)) {
1067 for (i
= 0; i
< cr
; i
++)
1068 neighbours
[nneighbours
++] = diag1(i
);
1073 * Try visiting each of those neighbours.
1075 for (i
= 0; i
< nneighbours
; i
++) {
1078 xt
= neighbours
[i
] % cr
;
1079 yt
= neighbours
[i
] / cr
;
1082 * We need this square to not be
1083 * already visited, and to include
1084 * currn as a possible number.
1086 if (number
[yt
*cr
+xt
] <= cr
)
1088 if (!cube(xt
, yt
, currn
))
1092 * Don't visit _this_ square a second
1095 if (xt
== xx
&& yt
== yy
)
1099 * To continue with the bfs, we need
1100 * this square to have exactly two
1103 for (cc
= tt
= 0, nn
= 1; nn
<= cr
; nn
++)
1104 if (cube(xt
, yt
, nn
))
1107 bfsqueue
[tail
++] = yt
*cr
+xt
;
1108 #ifdef STANDALONE_SOLVER
1109 bfsprev
[yt
*cr
+xt
] = yy
*cr
+xx
;
1111 number
[yt
*cr
+xt
] = tt
- currn
;
1115 * One other possibility is that this
1116 * might be the square in which we can
1117 * make a real deduction: if it's
1118 * adjacent to x,y, and currn is equal
1119 * to the original number we ruled out.
1121 if (currn
== orign
&&
1122 (xt
== x
|| yt
== y
||
1123 (usage
->blocks
->whichblock
[yt
*cr
+xt
] == usage
->blocks
->whichblock
[y
*cr
+x
]) ||
1124 (usage
->diag
&& ((ondiag0(yt
*cr
+xt
) && ondiag0(y
*cr
+x
)) ||
1125 (ondiag1(yt
*cr
+xt
) && ondiag1(y
*cr
+x
)))))) {
1126 #ifdef STANDALONE_SOLVER
1127 if (solver_show_working
) {
1130 printf("%*sforcing chain, %d at ends of ",
1131 solver_recurse_depth
*4, "", orign
);
1135 printf("%s(%d,%d)", sep
, 1+xl
,
1137 xl
= bfsprev
[yl
*cr
+xl
];
1144 printf("\n%*s ruling out %d at (%d,%d)\n",
1145 solver_recurse_depth
*4, "",
1149 cube(xt
, yt
, orign
) = FALSE
;
1160 static struct solver_scratch
*solver_new_scratch(struct solver_usage
*usage
)
1162 struct solver_scratch
*scratch
= snew(struct solver_scratch
);
1164 scratch
->grid
= snewn(cr
*cr
, unsigned char);
1165 scratch
->rowidx
= snewn(cr
, unsigned char);
1166 scratch
->colidx
= snewn(cr
, unsigned char);
1167 scratch
->set
= snewn(cr
, unsigned char);
1168 scratch
->neighbours
= snewn(5*cr
, int);
1169 scratch
->bfsqueue
= snewn(cr
*cr
, int);
1170 #ifdef STANDALONE_SOLVER
1171 scratch
->bfsprev
= snewn(cr
*cr
, int);
1173 scratch
->indexlist
= snewn(cr
*cr
, int); /* used for set elimination */
1174 scratch
->indexlist2
= snewn(cr
, int); /* only used for intersect() */
1178 static void solver_free_scratch(struct solver_scratch
*scratch
)
1180 #ifdef STANDALONE_SOLVER
1181 sfree(scratch
->bfsprev
);
1183 sfree(scratch
->bfsqueue
);
1184 sfree(scratch
->neighbours
);
1185 sfree(scratch
->set
);
1186 sfree(scratch
->colidx
);
1187 sfree(scratch
->rowidx
);
1188 sfree(scratch
->grid
);
1189 sfree(scratch
->indexlist
);
1190 sfree(scratch
->indexlist2
);
1194 static int solver(int cr
, struct block_structure
*blocks
, int xtype
,
1195 digit
*grid
, int maxdiff
)
1197 struct solver_usage
*usage
;
1198 struct solver_scratch
*scratch
;
1199 int x
, y
, b
, i
, n
, ret
;
1200 int diff
= DIFF_BLOCK
;
1203 * Set up a usage structure as a clean slate (everything
1206 usage
= snew(struct solver_usage
);
1208 usage
->blocks
= blocks
;
1209 usage
->cube
= snewn(cr
*cr
*cr
, unsigned char);
1210 usage
->grid
= grid
; /* write straight back to the input */
1211 memset(usage
->cube
, TRUE
, cr
*cr
*cr
);
1213 usage
->row
= snewn(cr
* cr
, unsigned char);
1214 usage
->col
= snewn(cr
* cr
, unsigned char);
1215 usage
->blk
= snewn(cr
* cr
, unsigned char);
1216 memset(usage
->row
, FALSE
, cr
* cr
);
1217 memset(usage
->col
, FALSE
, cr
* cr
);
1218 memset(usage
->blk
, FALSE
, cr
* cr
);
1221 usage
->diag
= snewn(cr
* 2, unsigned char);
1222 memset(usage
->diag
, FALSE
, cr
* 2);
1226 scratch
= solver_new_scratch(usage
);
1229 * Place all the clue numbers we are given.
1231 for (x
= 0; x
< cr
; x
++)
1232 for (y
= 0; y
< cr
; y
++)
1234 solver_place(usage
, x
, y
, grid
[y
*cr
+x
]);
1237 * Now loop over the grid repeatedly trying all permitted modes
1238 * of reasoning. The loop terminates if we complete an
1239 * iteration without making any progress; we then return
1240 * failure or success depending on whether the grid is full or
1245 * I'd like to write `continue;' inside each of the
1246 * following loops, so that the solver returns here after
1247 * making some progress. However, I can't specify that I
1248 * want to continue an outer loop rather than the innermost
1249 * one, so I'm apologetically resorting to a goto.
1254 * Blockwise positional elimination.
1256 for (b
= 0; b
< cr
; b
++)
1257 for (n
= 1; n
<= cr
; n
++)
1258 if (!usage
->blk
[b
*cr
+n
-1]) {
1259 for (i
= 0; i
< cr
; i
++)
1260 scratch
->indexlist
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
],n
);
1261 ret
= solver_elim(usage
, scratch
->indexlist
1262 #ifdef STANDALONE_SOLVER
1263 , "positional elimination,"
1264 " %d in block %s", n
,
1265 usage
->blocks
->blocknames
[b
]
1269 diff
= DIFF_IMPOSSIBLE
;
1271 } else if (ret
> 0) {
1272 diff
= max(diff
, DIFF_BLOCK
);
1277 if (maxdiff
<= DIFF_BLOCK
)
1281 * Row-wise positional elimination.
1283 for (y
= 0; y
< cr
; y
++)
1284 for (n
= 1; n
<= cr
; n
++)
1285 if (!usage
->row
[y
*cr
+n
-1]) {
1286 for (x
= 0; x
< cr
; x
++)
1287 scratch
->indexlist
[x
] = cubepos(x
, y
, n
);
1288 ret
= solver_elim(usage
, scratch
->indexlist
1289 #ifdef STANDALONE_SOLVER
1290 , "positional elimination,"
1291 " %d in row %d", n
, 1+y
1295 diff
= DIFF_IMPOSSIBLE
;
1297 } else if (ret
> 0) {
1298 diff
= max(diff
, DIFF_SIMPLE
);
1303 * Column-wise positional elimination.
1305 for (x
= 0; x
< cr
; x
++)
1306 for (n
= 1; n
<= cr
; n
++)
1307 if (!usage
->col
[x
*cr
+n
-1]) {
1308 for (y
= 0; y
< cr
; y
++)
1309 scratch
->indexlist
[y
] = cubepos(x
, y
, n
);
1310 ret
= solver_elim(usage
, scratch
->indexlist
1311 #ifdef STANDALONE_SOLVER
1312 , "positional elimination,"
1313 " %d in column %d", n
, 1+x
1317 diff
= DIFF_IMPOSSIBLE
;
1319 } else if (ret
> 0) {
1320 diff
= max(diff
, DIFF_SIMPLE
);
1326 * X-diagonal positional elimination.
1329 for (n
= 1; n
<= cr
; n
++)
1330 if (!usage
->diag
[n
-1]) {
1331 for (i
= 0; i
< cr
; i
++)
1332 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
1333 ret
= solver_elim(usage
, scratch
->indexlist
1334 #ifdef STANDALONE_SOLVER
1335 , "positional elimination,"
1336 " %d in \\-diagonal", n
1340 diff
= DIFF_IMPOSSIBLE
;
1342 } else if (ret
> 0) {
1343 diff
= max(diff
, DIFF_SIMPLE
);
1347 for (n
= 1; n
<= cr
; n
++)
1348 if (!usage
->diag
[cr
+n
-1]) {
1349 for (i
= 0; i
< cr
; i
++)
1350 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
1351 ret
= solver_elim(usage
, scratch
->indexlist
1352 #ifdef STANDALONE_SOLVER
1353 , "positional elimination,"
1354 " %d in /-diagonal", n
1358 diff
= DIFF_IMPOSSIBLE
;
1360 } else if (ret
> 0) {
1361 diff
= max(diff
, DIFF_SIMPLE
);
1368 * Numeric elimination.
1370 for (x
= 0; x
< cr
; x
++)
1371 for (y
= 0; y
< cr
; y
++)
1372 if (!usage
->grid
[y
*cr
+x
]) {
1373 for (n
= 1; n
<= cr
; n
++)
1374 scratch
->indexlist
[n
-1] = cubepos(x
, y
, n
);
1375 ret
= solver_elim(usage
, scratch
->indexlist
1376 #ifdef STANDALONE_SOLVER
1377 , "numeric elimination at (%d,%d)",
1382 diff
= DIFF_IMPOSSIBLE
;
1384 } else if (ret
> 0) {
1385 diff
= max(diff
, DIFF_SIMPLE
);
1390 if (maxdiff
<= DIFF_SIMPLE
)
1394 * Intersectional analysis, rows vs blocks.
1396 for (y
= 0; y
< cr
; y
++)
1397 for (b
= 0; b
< cr
; b
++)
1398 for (n
= 1; n
<= cr
; n
++) {
1399 if (usage
->row
[y
*cr
+n
-1] ||
1400 usage
->blk
[b
*cr
+n
-1])
1402 for (i
= 0; i
< cr
; i
++) {
1403 scratch
->indexlist
[i
] = cubepos(i
, y
, n
);
1404 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1407 * solver_intersect() never returns -1.
1409 if (solver_intersect(usage
, scratch
->indexlist
,
1411 #ifdef STANDALONE_SOLVER
1412 , "intersectional analysis,"
1413 " %d in row %d vs block %s",
1414 n
, 1+y
, usage
->blocks
->blocknames
[b
]
1417 solver_intersect(usage
, scratch
->indexlist2
,
1419 #ifdef STANDALONE_SOLVER
1420 , "intersectional analysis,"
1421 " %d in block %s vs row %d",
1422 n
, usage
->blocks
->blocknames
[b
], 1+y
1425 diff
= max(diff
, DIFF_INTERSECT
);
1431 * Intersectional analysis, columns vs blocks.
1433 for (x
= 0; x
< cr
; x
++)
1434 for (b
= 0; b
< cr
; b
++)
1435 for (n
= 1; n
<= cr
; n
++) {
1436 if (usage
->col
[x
*cr
+n
-1] ||
1437 usage
->blk
[b
*cr
+n
-1])
1439 for (i
= 0; i
< cr
; i
++) {
1440 scratch
->indexlist
[i
] = cubepos(x
, i
, n
);
1441 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1443 if (solver_intersect(usage
, scratch
->indexlist
,
1445 #ifdef STANDALONE_SOLVER
1446 , "intersectional analysis,"
1447 " %d in column %d vs block %s",
1448 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1451 solver_intersect(usage
, scratch
->indexlist2
,
1453 #ifdef STANDALONE_SOLVER
1454 , "intersectional analysis,"
1455 " %d in block %s vs column %d",
1456 n
, usage
->blocks
->blocknames
[b
], 1+x
1459 diff
= max(diff
, DIFF_INTERSECT
);
1466 * Intersectional analysis, \-diagonal vs blocks.
1468 for (b
= 0; b
< cr
; b
++)
1469 for (n
= 1; n
<= cr
; n
++) {
1470 if (usage
->diag
[n
-1] ||
1471 usage
->blk
[b
*cr
+n
-1])
1473 for (i
= 0; i
< cr
; i
++) {
1474 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
1475 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1477 if (solver_intersect(usage
, scratch
->indexlist
,
1479 #ifdef STANDALONE_SOLVER
1480 , "intersectional analysis,"
1481 " %d in \\-diagonal vs block %s",
1482 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1485 solver_intersect(usage
, scratch
->indexlist2
,
1487 #ifdef STANDALONE_SOLVER
1488 , "intersectional analysis,"
1489 " %d in block %s vs \\-diagonal",
1490 n
, usage
->blocks
->blocknames
[b
], 1+x
1493 diff
= max(diff
, DIFF_INTERSECT
);
1499 * Intersectional analysis, /-diagonal vs blocks.
1501 for (b
= 0; b
< cr
; b
++)
1502 for (n
= 1; n
<= cr
; n
++) {
1503 if (usage
->diag
[cr
+n
-1] ||
1504 usage
->blk
[b
*cr
+n
-1])
1506 for (i
= 0; i
< cr
; i
++) {
1507 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
1508 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1510 if (solver_intersect(usage
, scratch
->indexlist
,
1512 #ifdef STANDALONE_SOLVER
1513 , "intersectional analysis,"
1514 " %d in /-diagonal vs block %s",
1515 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1518 solver_intersect(usage
, scratch
->indexlist2
,
1520 #ifdef STANDALONE_SOLVER
1521 , "intersectional analysis,"
1522 " %d in block %s vs /-diagonal",
1523 n
, usage
->blocks
->blocknames
[b
], 1+x
1526 diff
= max(diff
, DIFF_INTERSECT
);
1532 if (maxdiff
<= DIFF_INTERSECT
)
1536 * Blockwise set elimination.
1538 for (b
= 0; b
< cr
; b
++) {
1539 for (i
= 0; i
< cr
; i
++)
1540 for (n
= 1; n
<= cr
; n
++)
1541 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1542 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1543 #ifdef STANDALONE_SOLVER
1544 , "set elimination, block %s",
1545 usage
->blocks
->blocknames
[b
]
1549 diff
= DIFF_IMPOSSIBLE
;
1551 } else if (ret
> 0) {
1552 diff
= max(diff
, DIFF_SET
);
1558 * Row-wise set elimination.
1560 for (y
= 0; y
< cr
; y
++) {
1561 for (x
= 0; x
< cr
; x
++)
1562 for (n
= 1; n
<= cr
; n
++)
1563 scratch
->indexlist
[x
*cr
+n
-1] = cubepos(x
, y
, n
);
1564 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1565 #ifdef STANDALONE_SOLVER
1566 , "set elimination, row %d", 1+y
1570 diff
= DIFF_IMPOSSIBLE
;
1572 } else if (ret
> 0) {
1573 diff
= max(diff
, DIFF_SET
);
1579 * Column-wise set elimination.
1581 for (x
= 0; x
< cr
; x
++) {
1582 for (y
= 0; y
< cr
; y
++)
1583 for (n
= 1; n
<= cr
; n
++)
1584 scratch
->indexlist
[y
*cr
+n
-1] = cubepos(x
, y
, n
);
1585 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1586 #ifdef STANDALONE_SOLVER
1587 , "set elimination, column %d", 1+x
1591 diff
= DIFF_IMPOSSIBLE
;
1593 } else if (ret
> 0) {
1594 diff
= max(diff
, DIFF_SET
);
1601 * \-diagonal set elimination.
1603 for (i
= 0; i
< cr
; i
++)
1604 for (n
= 1; n
<= cr
; n
++)
1605 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag0(i
), n
);
1606 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1607 #ifdef STANDALONE_SOLVER
1608 , "set elimination, \\-diagonal"
1612 diff
= DIFF_IMPOSSIBLE
;
1614 } else if (ret
> 0) {
1615 diff
= max(diff
, DIFF_SET
);
1620 * /-diagonal set elimination.
1622 for (i
= 0; i
< cr
; i
++)
1623 for (n
= 1; n
<= cr
; n
++)
1624 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag1(i
), n
);
1625 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1626 #ifdef STANDALONE_SOLVER
1627 , "set elimination, \\-diagonal"
1631 diff
= DIFF_IMPOSSIBLE
;
1633 } else if (ret
> 0) {
1634 diff
= max(diff
, DIFF_SET
);
1639 if (maxdiff
<= DIFF_SET
)
1643 * Row-vs-column set elimination on a single number.
1645 for (n
= 1; n
<= cr
; n
++) {
1646 for (y
= 0; y
< cr
; y
++)
1647 for (x
= 0; x
< cr
; x
++)
1648 scratch
->indexlist
[y
*cr
+x
] = cubepos(x
, y
, n
);
1649 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1650 #ifdef STANDALONE_SOLVER
1651 , "positional set elimination, number %d", n
1655 diff
= DIFF_IMPOSSIBLE
;
1657 } else if (ret
> 0) {
1658 diff
= max(diff
, DIFF_EXTREME
);
1666 if (solver_forcing(usage
, scratch
)) {
1667 diff
= max(diff
, DIFF_EXTREME
);
1672 * If we reach here, we have made no deductions in this
1673 * iteration, so the algorithm terminates.
1679 * Last chance: if we haven't fully solved the puzzle yet, try
1680 * recursing based on guesses for a particular square. We pick
1681 * one of the most constrained empty squares we can find, which
1682 * has the effect of pruning the search tree as much as
1685 if (maxdiff
>= DIFF_RECURSIVE
) {
1686 int best
, bestcount
;
1691 for (y
= 0; y
< cr
; y
++)
1692 for (x
= 0; x
< cr
; x
++)
1693 if (!grid
[y
*cr
+x
]) {
1697 * An unfilled square. Count the number of
1698 * possible digits in it.
1701 for (n
= 1; n
<= cr
; n
++)
1706 * We should have found any impossibilities
1707 * already, so this can safely be an assert.
1711 if (count
< bestcount
) {
1719 digit
*list
, *ingrid
, *outgrid
;
1721 diff
= DIFF_IMPOSSIBLE
; /* no solution found yet */
1724 * Attempt recursion.
1729 list
= snewn(cr
, digit
);
1730 ingrid
= snewn(cr
* cr
, digit
);
1731 outgrid
= snewn(cr
* cr
, digit
);
1732 memcpy(ingrid
, grid
, cr
* cr
);
1734 /* Make a list of the possible digits. */
1735 for (j
= 0, n
= 1; n
<= cr
; n
++)
1739 #ifdef STANDALONE_SOLVER
1740 if (solver_show_working
) {
1742 printf("%*srecursing on (%d,%d) [",
1743 solver_recurse_depth
*4, "", x
+ 1, y
+ 1);
1744 for (i
= 0; i
< j
; i
++) {
1745 printf("%s%d", sep
, list
[i
]);
1753 * And step along the list, recursing back into the
1754 * main solver at every stage.
1756 for (i
= 0; i
< j
; i
++) {
1759 memcpy(outgrid
, ingrid
, cr
* cr
);
1760 outgrid
[y
*cr
+x
] = list
[i
];
1762 #ifdef STANDALONE_SOLVER
1763 if (solver_show_working
)
1764 printf("%*sguessing %d at (%d,%d)\n",
1765 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
1766 solver_recurse_depth
++;
1769 ret
= solver(cr
, blocks
, xtype
, outgrid
, maxdiff
);
1771 #ifdef STANDALONE_SOLVER
1772 solver_recurse_depth
--;
1773 if (solver_show_working
) {
1774 printf("%*sretracting %d at (%d,%d)\n",
1775 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
1780 * If we have our first solution, copy it into the
1781 * grid we will return.
1783 if (diff
== DIFF_IMPOSSIBLE
&& ret
!= DIFF_IMPOSSIBLE
)
1784 memcpy(grid
, outgrid
, cr
*cr
);
1786 if (ret
== DIFF_AMBIGUOUS
)
1787 diff
= DIFF_AMBIGUOUS
;
1788 else if (ret
== DIFF_IMPOSSIBLE
)
1789 /* do not change our return value */;
1791 /* the recursion turned up exactly one solution */
1792 if (diff
== DIFF_IMPOSSIBLE
)
1793 diff
= DIFF_RECURSIVE
;
1795 diff
= DIFF_AMBIGUOUS
;
1799 * As soon as we've found more than one solution,
1800 * give up immediately.
1802 if (diff
== DIFF_AMBIGUOUS
)
1813 * We're forbidden to use recursion, so we just see whether
1814 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1817 for (y
= 0; y
< cr
; y
++)
1818 for (x
= 0; x
< cr
; x
++)
1820 diff
= DIFF_IMPOSSIBLE
;
1825 #ifdef STANDALONE_SOLVER
1826 if (solver_show_working
)
1827 printf("%*s%s found\n",
1828 solver_recurse_depth
*4, "",
1829 diff
== DIFF_IMPOSSIBLE ?
"no solution" :
1830 diff
== DIFF_AMBIGUOUS ?
"multiple solutions" :
1840 solver_free_scratch(scratch
);
1845 /* ----------------------------------------------------------------------
1846 * End of solver code.
1849 /* ----------------------------------------------------------------------
1850 * Solo filled-grid generator.
1852 * This grid generator works by essentially trying to solve a grid
1853 * starting from no clues, and not worrying that there's more than
1854 * one possible solution. Unfortunately, it isn't computationally
1855 * feasible to do this by calling the above solver with an empty
1856 * grid, because that one needs to allocate a lot of scratch space
1857 * at every recursion level. Instead, I have a much simpler
1858 * algorithm which I shamelessly copied from a Python solver
1859 * written by Andrew Wilkinson (which is GPLed, but I've reused
1860 * only ideas and no code). It mostly just does the obvious
1861 * recursive thing: pick an empty square, put one of the possible
1862 * digits in it, recurse until all squares are filled, backtrack
1863 * and change some choices if necessary.
1865 * The clever bit is that every time it chooses which square to
1866 * fill in next, it does so by counting the number of _possible_
1867 * numbers that can go in each square, and it prioritises so that
1868 * it picks a square with the _lowest_ number of possibilities. The
1869 * idea is that filling in lots of the obvious bits (particularly
1870 * any squares with only one possibility) will cut down on the list
1871 * of possibilities for other squares and hence reduce the enormous
1872 * search space as much as possible as early as possible.
1876 * Internal data structure used in gridgen to keep track of
1879 struct gridgen_coord
{ int x
, y
, r
; };
1880 struct gridgen_usage
{
1882 struct block_structure
*blocks
;
1883 /* grid is a copy of the input grid, modified as we go along */
1885 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1887 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1889 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1891 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
1892 unsigned char *diag
;
1893 /* This lists all the empty spaces remaining in the grid. */
1894 struct gridgen_coord
*spaces
;
1896 /* If we need randomisation in the solve, this is our random state. */
1901 * The real recursive step in the generating function.
1903 * Return values: 1 means solution found, 0 means no solution
1904 * found on this branch.
1906 static int gridgen_real(struct gridgen_usage
*usage
, digit
*grid
)
1909 int i
, j
, n
, sx
, sy
, bestm
, bestr
, ret
;
1913 * Firstly, check for completion! If there are no spaces left
1914 * in the grid, we have a solution.
1916 if (usage
->nspaces
== 0) {
1917 memcpy(grid
, usage
->grid
, cr
* cr
);
1922 * Otherwise, there must be at least one space. Find the most
1923 * constrained space, using the `r' field as a tie-breaker.
1925 bestm
= cr
+1; /* so that any space will beat it */
1928 for (j
= 0; j
< usage
->nspaces
; j
++) {
1929 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
1933 * Find the number of digits that could go in this space.
1936 for (n
= 0; n
< cr
; n
++)
1937 if (!usage
->row
[y
*cr
+n
] && !usage
->col
[x
*cr
+n
] &&
1938 !usage
->blk
[usage
->blocks
->whichblock
[y
*cr
+x
]*cr
+n
] &&
1939 (!usage
->diag
|| ((!ondiag0(y
*cr
+x
) || !usage
->diag
[n
]) &&
1940 (!ondiag1(y
*cr
+x
) || !usage
->diag
[cr
+n
]))))
1943 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
1945 bestr
= usage
->spaces
[j
].r
;
1953 * Swap that square into the final place in the spaces array,
1954 * so that decrementing nspaces will remove it from the list.
1956 if (i
!= usage
->nspaces
-1) {
1957 struct gridgen_coord t
;
1958 t
= usage
->spaces
[usage
->nspaces
-1];
1959 usage
->spaces
[usage
->nspaces
-1] = usage
->spaces
[i
];
1960 usage
->spaces
[i
] = t
;
1964 * Now we've decided which square to start our recursion at,
1965 * simply go through all possible values, shuffling them
1966 * randomly first if necessary.
1968 digits
= snewn(bestm
, int);
1970 for (n
= 0; n
< cr
; n
++)
1971 if (!usage
->row
[sy
*cr
+n
] && !usage
->col
[sx
*cr
+n
] &&
1972 !usage
->blk
[usage
->blocks
->whichblock
[sy
*cr
+sx
]*cr
+n
] &&
1973 (!usage
->diag
|| ((!ondiag0(sy
*cr
+sx
) || !usage
->diag
[n
]) &&
1974 (!ondiag1(sy
*cr
+sx
) || !usage
->diag
[cr
+n
])))) {
1979 shuffle(digits
, j
, sizeof(*digits
), usage
->rs
);
1981 /* And finally, go through the digit list and actually recurse. */
1983 for (i
= 0; i
< j
; i
++) {
1986 /* Update the usage structure to reflect the placing of this digit. */
1987 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
1988 usage
->blk
[usage
->blocks
->whichblock
[sy
*cr
+sx
]*cr
+n
-1] = TRUE
;
1990 if (ondiag0(sy
*cr
+sx
))
1991 usage
->diag
[n
-1] = TRUE
;
1992 if (ondiag1(sy
*cr
+sx
))
1993 usage
->diag
[cr
+n
-1] = TRUE
;
1995 usage
->grid
[sy
*cr
+sx
] = n
;
1998 /* Call the solver recursively. Stop when we find a solution. */
1999 if (gridgen_real(usage
, grid
))
2002 /* Revert the usage structure. */
2003 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
2004 usage
->blk
[usage
->blocks
->whichblock
[sy
*cr
+sx
]*cr
+n
-1] = FALSE
;
2006 if (ondiag0(sy
*cr
+sx
))
2007 usage
->diag
[n
-1] = FALSE
;
2008 if (ondiag1(sy
*cr
+sx
))
2009 usage
->diag
[cr
+n
-1] = FALSE
;
2011 usage
->grid
[sy
*cr
+sx
] = 0;
2023 * Entry point to generator. You give it parameters and a starting
2024 * grid, which is simply an array of cr*cr digits.
2026 static int gridgen(int cr
, struct block_structure
*blocks
, int xtype
,
2027 digit
*grid
, random_state
*rs
)
2029 struct gridgen_usage
*usage
;
2033 * Clear the grid to start with.
2035 memset(grid
, 0, cr
*cr
);
2038 * Create a gridgen_usage structure.
2040 usage
= snew(struct gridgen_usage
);
2043 usage
->blocks
= blocks
;
2045 usage
->grid
= snewn(cr
* cr
, digit
);
2046 memcpy(usage
->grid
, grid
, cr
* cr
);
2048 usage
->row
= snewn(cr
* cr
, unsigned char);
2049 usage
->col
= snewn(cr
* cr
, unsigned char);
2050 usage
->blk
= snewn(cr
* cr
, unsigned char);
2051 memset(usage
->row
, FALSE
, cr
* cr
);
2052 memset(usage
->col
, FALSE
, cr
* cr
);
2053 memset(usage
->blk
, FALSE
, cr
* cr
);
2056 usage
->diag
= snewn(2 * cr
, unsigned char);
2057 memset(usage
->diag
, FALSE
, 2 * cr
);
2062 usage
->spaces
= snewn(cr
* cr
, struct gridgen_coord
);
2068 * Initialise the list of grid spaces.
2070 for (y
= 0; y
< cr
; y
++) {
2071 for (x
= 0; x
< cr
; x
++) {
2072 usage
->spaces
[usage
->nspaces
].x
= x
;
2073 usage
->spaces
[usage
->nspaces
].y
= y
;
2074 usage
->spaces
[usage
->nspaces
].r
= random_bits(rs
, 31);
2080 * Run the real generator function.
2082 ret
= gridgen_real(usage
, grid
);
2085 * Clean up the usage structure now we have our answer.
2087 sfree(usage
->spaces
);
2097 /* ----------------------------------------------------------------------
2098 * End of grid generator code.
2102 * Check whether a grid contains a valid complete puzzle.
2104 static int check_valid(int cr
, struct block_structure
*blocks
, int xtype
,
2107 unsigned char *used
;
2110 used
= snewn(cr
, unsigned char);
2113 * Check that each row contains precisely one of everything.
2115 for (y
= 0; y
< cr
; y
++) {
2116 memset(used
, FALSE
, cr
);
2117 for (x
= 0; x
< cr
; x
++)
2118 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2119 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2120 for (n
= 0; n
< cr
; n
++)
2128 * Check that each column contains precisely one of everything.
2130 for (x
= 0; x
< cr
; x
++) {
2131 memset(used
, FALSE
, cr
);
2132 for (y
= 0; y
< cr
; y
++)
2133 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2134 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2135 for (n
= 0; n
< cr
; n
++)
2143 * Check that each block contains precisely one of everything.
2145 for (i
= 0; i
< cr
; i
++) {
2146 memset(used
, FALSE
, cr
);
2147 for (j
= 0; j
< cr
; j
++)
2148 if (grid
[blocks
->blocks
[i
][j
]] > 0 &&
2149 grid
[blocks
->blocks
[i
][j
]] <= cr
)
2150 used
[grid
[blocks
->blocks
[i
][j
]]-1] = TRUE
;
2151 for (n
= 0; n
< cr
; n
++)
2159 * Check that each diagonal contains precisely one of everything.
2162 memset(used
, FALSE
, cr
);
2163 for (i
= 0; i
< cr
; i
++)
2164 if (grid
[diag0(i
)] > 0 && grid
[diag0(i
)] <= cr
)
2165 used
[grid
[diag0(i
)]-1] = TRUE
;
2166 for (n
= 0; n
< cr
; n
++)
2171 for (i
= 0; i
< cr
; i
++)
2172 if (grid
[diag1(i
)] > 0 && grid
[diag1(i
)] <= cr
)
2173 used
[grid
[diag1(i
)]-1] = TRUE
;
2174 for (n
= 0; n
< cr
; n
++)
2185 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
2187 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2190 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2196 break; /* just x,y is all we need */
2198 ADD(cr
- 1 - x
, cr
- 1 - y
);
2203 ADD(cr
- 1 - x
, cr
- 1 - y
);
2214 ADD(cr
- 1 - x
, cr
- 1 - y
);
2218 ADD(cr
- 1 - x
, cr
- 1 - y
);
2219 ADD(cr
- 1 - y
, cr
- 1 - x
);
2224 ADD(cr
- 1 - x
, cr
- 1 - y
);
2228 ADD(cr
- 1 - y
, cr
- 1 - x
);
2237 static char *encode_solve_move(int cr
, digit
*grid
)
2240 char *ret
, *p
, *sep
;
2243 * It's surprisingly easy to work out _exactly_ how long this
2244 * string needs to be. To decimal-encode all the numbers from 1
2247 * - every number has a units digit; total is n.
2248 * - all numbers above 9 have a tens digit; total is max(n-9,0).
2249 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2253 for (i
= 1; i
<= cr
; i
*= 10)
2254 len
+= max(cr
- i
+ 1, 0);
2255 len
+= cr
; /* don't forget the commas */
2256 len
*= cr
; /* there are cr rows of these */
2259 * Now len is one bigger than the total size of the
2260 * comma-separated numbers (because we counted an
2261 * additional leading comma). We need to have a leading S
2262 * and a trailing NUL, so we're off by one in total.
2266 ret
= snewn(len
, char);
2270 for (i
= 0; i
< cr
*cr
; i
++) {
2271 p
+= sprintf(p
, "%s%d", sep
, grid
[i
]);
2275 assert(p
- ret
== len
);
2280 static char *new_game_desc(game_params
*params
, random_state
*rs
,
2281 char **aux
, int interactive
)
2283 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2285 struct block_structure
*blocks
;
2286 digit
*grid
, *grid2
;
2287 struct xy
{ int x
, y
; } *locs
;
2290 int coords
[16], ncoords
;
2295 * Adjust the maximum difficulty level to be consistent with
2296 * the puzzle size: all 2x2 puzzles appear to be Trivial
2297 * (DIFF_BLOCK) so we cannot hold out for even a Basic
2298 * (DIFF_SIMPLE) one.
2300 maxdiff
= params
->diff
;
2301 if (c
== 2 && r
== 2)
2302 maxdiff
= DIFF_BLOCK
;
2304 grid
= snewn(area
, digit
);
2305 locs
= snewn(area
, struct xy
);
2306 grid2
= snewn(area
, digit
);
2308 blocks
= snew(struct block_structure
);
2309 blocks
->c
= params
->c
; blocks
->r
= params
->r
;
2310 blocks
->whichblock
= snewn(area
*2, int);
2311 blocks
->blocks
= snewn(cr
, int *);
2312 for (i
= 0; i
< cr
; i
++)
2313 blocks
->blocks
[i
] = blocks
->whichblock
+ area
+ i
*cr
;
2314 #ifdef STANDALONE_SOLVER
2315 assert(!"This should never happen, so we don't need to create blocknames");
2319 * Loop until we get a grid of the required difficulty. This is
2320 * nasty, but it seems to be unpleasantly hard to generate
2321 * difficult grids otherwise.
2325 * Generate a random solved state, starting by
2326 * constructing the block structure.
2328 if (r
== 1) { /* jigsaw mode */
2329 int *dsf
= divvy_rectangle(cr
, cr
, cr
, rs
);
2332 for (i
= 0; i
< area
; i
++)
2333 blocks
->whichblock
[i
] = -1;
2334 for (i
= 0; i
< area
; i
++) {
2335 int j
= dsf_canonify(dsf
, i
);
2336 if (blocks
->whichblock
[j
] < 0)
2337 blocks
->whichblock
[j
] = nb
++;
2338 blocks
->whichblock
[i
] = blocks
->whichblock
[j
];
2343 } else { /* basic Sudoku mode */
2344 for (y
= 0; y
< cr
; y
++)
2345 for (x
= 0; x
< cr
; x
++)
2346 blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
2348 for (i
= 0; i
< cr
; i
++)
2349 blocks
->blocks
[i
][cr
-1] = 0;
2350 for (i
= 0; i
< area
; i
++) {
2351 int b
= blocks
->whichblock
[i
];
2352 j
= blocks
->blocks
[b
][cr
-1]++;
2354 blocks
->blocks
[b
][j
] = i
;
2357 if (!gridgen(cr
, blocks
, params
->xtype
, grid
, rs
))
2358 continue; /* this might happen if the jigsaw is unsuitable */
2359 assert(check_valid(cr
, blocks
, params
->xtype
, grid
));
2362 * Save the solved grid in aux.
2366 * We might already have written *aux the last time we
2367 * went round this loop, in which case we should free
2368 * the old aux before overwriting it with the new one.
2374 *aux
= encode_solve_move(cr
, grid
);
2378 * Now we have a solved grid, start removing things from it
2379 * while preserving solubility.
2383 * Find the set of equivalence classes of squares permitted
2384 * by the selected symmetry. We do this by enumerating all
2385 * the grid squares which have no symmetric companion
2386 * sorting lower than themselves.
2389 for (y
= 0; y
< cr
; y
++)
2390 for (x
= 0; x
< cr
; x
++) {
2394 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
2395 for (j
= 0; j
< ncoords
; j
++)
2396 if (coords
[2*j
+1]*cr
+coords
[2*j
] < i
)
2406 * Now shuffle that list.
2408 shuffle(locs
, nlocs
, sizeof(*locs
), rs
);
2411 * Now loop over the shuffled list and, for each element,
2412 * see whether removing that element (and its reflections)
2413 * from the grid will still leave the grid soluble.
2415 for (i
= 0; i
< nlocs
; i
++) {
2421 memcpy(grid2
, grid
, area
);
2422 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
2423 for (j
= 0; j
< ncoords
; j
++)
2424 grid2
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
2426 ret
= solver(cr
, blocks
, params
->xtype
, grid2
, maxdiff
);
2427 if (ret
<= maxdiff
) {
2428 for (j
= 0; j
< ncoords
; j
++)
2429 grid
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
2433 memcpy(grid2
, grid
, area
);
2435 if (solver(cr
, blocks
, params
->xtype
, grid2
, maxdiff
) == maxdiff
)
2436 break; /* found one! */
2443 * Now we have the grid as it will be presented to the user.
2444 * Encode it in a game desc.
2450 desc
= snewn(7 * area
, char);
2453 for (i
= 0; i
<= area
; i
++) {
2454 int n
= (i
< area ? grid
[i
] : -1);
2461 int c
= 'a' - 1 + run
;
2465 run
-= c
- ('a' - 1);
2469 * If there's a number in the very top left or
2470 * bottom right, there's no point putting an
2471 * unnecessary _ before or after it.
2473 if (p
> desc
&& n
> 0)
2477 p
+= sprintf(p
, "%d", n
);
2488 * Encode the block structure. We do this by encoding
2489 * the pattern of dividing lines: first we iterate
2490 * over the cr*(cr-1) internal vertical grid lines in
2491 * ordinary reading order, then over the cr*(cr-1)
2492 * internal horizontal ones in transposed reading
2495 * We encode the number of non-lines between the
2496 * lines; _ means zero (two adjacent divisions), a
2497 * means 1, ..., y means 25, and z means 25 non-lines
2498 * _and no following line_ (so that za means 26, zb 27
2501 for (i
= 0; i
<= 2*cr
*(cr
-1); i
++) {
2504 if (i
== 2*cr
*(cr
-1)) {
2505 edge
= TRUE
; /* terminating virtual edge */
2507 if (i
< cr
*(cr
-1)) {
2518 edge
= (blocks
->whichblock
[p0
] != blocks
->whichblock
[p1
]);
2522 while (currrun
> 25)
2523 *p
++ = 'z', currrun
-= 25;
2525 *p
++ = 'a'-1 + currrun
;
2534 assert(p
- desc
< 7 * area
);
2536 desc
= sresize(desc
, p
- desc
, char);
2544 static char *validate_desc(game_params
*params
, char *desc
)
2546 int cr
= params
->c
* params
->r
, area
= cr
*cr
;
2550 while (*desc
&& *desc
!= ',') {
2552 if (n
>= 'a' && n
<= 'z') {
2553 squares
+= n
- 'a' + 1;
2554 } else if (n
== '_') {
2556 } else if (n
> '0' && n
<= '9') {
2557 int val
= atoi(desc
-1);
2558 if (val
< 1 || val
> params
->c
* params
->r
)
2559 return "Out-of-range number in game description";
2561 while (*desc
>= '0' && *desc
<= '9')
2564 return "Invalid character in game description";
2568 return "Not enough data to fill grid";
2571 return "Too much data to fit in grid";
2573 if (params
->r
== 1) {
2575 * Now we expect a suffix giving the jigsaw block
2576 * structure. Parse it and validate that it divides the
2577 * grid into the right number of regions which are the
2581 return "Expected jigsaw block structure in game description";
2584 dsf
= snew_dsf(area
);
2592 else if (*desc
>= 'a' && *desc
<= 'z')
2593 c
= *desc
- 'a' + 1;
2596 return "Invalid character in game description";
2600 adv
= (c
!= 25); /* 'z' is a special case */
2606 * Non-edge; merge the two dsf classes on either
2609 if (pos
>= 2*cr
*(cr
-1)) {
2611 return "Too much data in block structure specification";
2612 } else if (pos
< cr
*(cr
-1)) {
2618 int x
= pos
/(cr
-1) - cr
;
2623 dsf_merge(dsf
, p0
, p1
);
2632 * When desc is exhausted, we expect to have gone exactly
2633 * one space _past_ the end of the grid, due to the dummy
2636 if (pos
!= 2*cr
*(cr
-1)+1) {
2638 return "Not enough data in block structure specification";
2642 * Now we've got our dsf. Verify that it matches
2646 int *canons
, *counts
;
2647 int i
, j
, c
, ncanons
= 0;
2649 canons
= snewn(cr
, int);
2650 counts
= snewn(cr
, int);
2652 for (i
= 0; i
< area
; i
++) {
2653 j
= dsf_canonify(dsf
, i
);
2655 for (c
= 0; c
< ncanons
; c
++)
2656 if (canons
[c
] == j
) {
2658 if (counts
[c
] > cr
) {
2662 return "A jigsaw block is too big";
2668 if (ncanons
>= cr
) {
2672 return "Too many distinct jigsaw blocks";
2674 canons
[ncanons
] = j
;
2675 counts
[ncanons
] = 1;
2681 * If we've managed to get through that loop without
2682 * tripping either of the error conditions, then we
2683 * must have partitioned the entire grid into at most
2684 * cr blocks of at most cr squares each; therefore we
2685 * must have _exactly_ cr blocks of _exactly_ cr
2686 * squares each. I'll verify that by assertion just in
2687 * case something has gone horribly wrong, but it
2688 * shouldn't have been able to happen by duff input,
2689 * only by a bug in the above code.
2691 assert(ncanons
== cr
);
2692 for (c
= 0; c
< ncanons
; c
++)
2693 assert(counts
[c
] == cr
);
2702 return "Unexpected jigsaw block structure in game description";
2708 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
2710 game_state
*state
= snew(game_state
);
2711 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
2715 state
->xtype
= params
->xtype
;
2717 state
->grid
= snewn(area
, digit
);
2718 state
->pencil
= snewn(area
* cr
, unsigned char);
2719 memset(state
->pencil
, 0, area
* cr
);
2720 state
->immutable
= snewn(area
, unsigned char);
2721 memset(state
->immutable
, FALSE
, area
);
2723 state
->blocks
= snew(struct block_structure
);
2724 state
->blocks
->c
= c
; state
->blocks
->r
= r
;
2725 state
->blocks
->refcount
= 1;
2726 state
->blocks
->whichblock
= snewn(area
*2, int);
2727 state
->blocks
->blocks
= snewn(cr
, int *);
2728 for (i
= 0; i
< cr
; i
++)
2729 state
->blocks
->blocks
[i
] = state
->blocks
->whichblock
+ area
+ i
*cr
;
2730 #ifdef STANDALONE_SOLVER
2731 state
->blocks
->blocknames
= (char **)smalloc(cr
*(sizeof(char *)+80));
2734 state
->completed
= state
->cheated
= FALSE
;
2737 while (*desc
&& *desc
!= ',') {
2739 if (n
>= 'a' && n
<= 'z') {
2740 int run
= n
- 'a' + 1;
2741 assert(i
+ run
<= area
);
2743 state
->grid
[i
++] = 0;
2744 } else if (n
== '_') {
2746 } else if (n
> '0' && n
<= '9') {
2748 state
->immutable
[i
] = TRUE
;
2749 state
->grid
[i
++] = atoi(desc
-1);
2750 while (*desc
>= '0' && *desc
<= '9')
2753 assert(!"We can't get here");
2763 assert(*desc
== ',');
2765 dsf
= snew_dsf(area
);
2773 else if (*desc
>= 'a' && *desc
<= 'z')
2774 c
= *desc
- 'a' + 1;
2776 assert(!"Shouldn't get here");
2779 adv
= (c
!= 25); /* 'z' is a special case */
2785 * Non-edge; merge the two dsf classes on either
2788 assert(pos
< 2*cr
*(cr
-1));
2789 if (pos
< cr
*(cr
-1)) {
2795 int x
= pos
/(cr
-1) - cr
;
2800 dsf_merge(dsf
, p0
, p1
);
2809 * When desc is exhausted, we expect to have gone exactly
2810 * one space _past_ the end of the grid, due to the dummy
2813 assert(pos
== 2*cr
*(cr
-1)+1);
2816 * Now we've got our dsf. Translate it into a block
2820 for (i
= 0; i
< area
; i
++)
2821 state
->blocks
->whichblock
[i
] = -1;
2822 for (i
= 0; i
< area
; i
++) {
2823 int j
= dsf_canonify(dsf
, i
);
2824 if (state
->blocks
->whichblock
[j
] < 0)
2825 state
->blocks
->whichblock
[j
] = nb
++;
2826 state
->blocks
->whichblock
[i
] = state
->blocks
->whichblock
[j
];
2836 for (y
= 0; y
< cr
; y
++)
2837 for (x
= 0; x
< cr
; x
++)
2838 state
->blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
2842 * Having sorted out whichblock[], set up the block index arrays.
2844 for (i
= 0; i
< cr
; i
++)
2845 state
->blocks
->blocks
[i
][cr
-1] = 0;
2846 for (i
= 0; i
< area
; i
++) {
2847 int b
= state
->blocks
->whichblock
[i
];
2848 int j
= state
->blocks
->blocks
[b
][cr
-1]++;
2850 state
->blocks
->blocks
[b
][j
] = i
;
2853 #ifdef STANDALONE_SOLVER
2855 * Set up the block names for solver diagnostic output.
2858 char *p
= (char *)(state
->blocks
->blocknames
+ cr
);
2861 for (i
= 0; i
< cr
; i
++)
2862 state
->blocks
->blocknames
[i
] = NULL
;
2864 for (i
= 0; i
< area
; i
++) {
2865 int j
= state
->blocks
->whichblock
[i
];
2866 if (!state
->blocks
->blocknames
[j
]) {
2867 state
->blocks
->blocknames
[j
] = p
;
2868 p
+= 1 + sprintf(p
, "starting at (%d,%d)",
2869 1 + i
%cr
, 1 + i
/cr
);
2874 for (by
= 0; by
< r
; by
++)
2875 for (bx
= 0; bx
< c
; bx
++) {
2876 state
->blocks
->blocknames
[by
*c
+bx
] = p
;
2877 p
+= 1 + sprintf(p
, "(%d,%d)", bx
+1, by
+1);
2880 assert(p
- (char *)state
->blocks
->blocknames
< cr
*(sizeof(char *)+80));
2881 for (i
= 0; i
< cr
; i
++)
2882 assert(state
->blocks
->blocknames
[i
]);
2889 static game_state
*dup_game(game_state
*state
)
2891 game_state
*ret
= snew(game_state
);
2892 int cr
= state
->cr
, area
= cr
* cr
;
2894 ret
->cr
= state
->cr
;
2895 ret
->xtype
= state
->xtype
;
2897 ret
->blocks
= state
->blocks
;
2898 ret
->blocks
->refcount
++;
2900 ret
->grid
= snewn(area
, digit
);
2901 memcpy(ret
->grid
, state
->grid
, area
);
2903 ret
->pencil
= snewn(area
* cr
, unsigned char);
2904 memcpy(ret
->pencil
, state
->pencil
, area
* cr
);
2906 ret
->immutable
= snewn(area
, unsigned char);
2907 memcpy(ret
->immutable
, state
->immutable
, area
);
2909 ret
->completed
= state
->completed
;
2910 ret
->cheated
= state
->cheated
;
2915 static void free_game(game_state
*state
)
2917 if (--state
->blocks
->refcount
== 0) {
2918 sfree(state
->blocks
->whichblock
);
2919 sfree(state
->blocks
->blocks
);
2920 #ifdef STANDALONE_SOLVER
2921 sfree(state
->blocks
->blocknames
);
2923 sfree(state
->blocks
);
2925 sfree(state
->immutable
);
2926 sfree(state
->pencil
);
2931 static char *solve_game(game_state
*state
, game_state
*currstate
,
2932 char *ai
, char **error
)
2940 * If we already have the solution in ai, save ourselves some
2946 grid
= snewn(cr
*cr
, digit
);
2947 memcpy(grid
, state
->grid
, cr
*cr
);
2948 solve_ret
= solver(cr
, state
->blocks
, state
->xtype
, grid
, DIFF_RECURSIVE
);
2952 if (solve_ret
== DIFF_IMPOSSIBLE
)
2953 *error
= "No solution exists for this puzzle";
2954 else if (solve_ret
== DIFF_AMBIGUOUS
)
2955 *error
= "Multiple solutions exist for this puzzle";
2962 ret
= encode_solve_move(cr
, grid
);
2969 static char *grid_text_format(int cr
, struct block_structure
*blocks
,
2970 int xtype
, digit
*grid
)
2974 int totallen
, linelen
, nlines
;
2978 * For non-jigsaw Sudoku, we format in the way we always have,
2979 * by having the digits unevenly spaced so that the dividing
2988 * For jigsaw puzzles, however, we must leave space between
2989 * _all_ pairs of digits for an optional dividing line, so we
2990 * have to move to the rather ugly
3000 * We deal with both cases using the same formatting code; we
3001 * simply invent a vmod value such that there's a vertical
3002 * dividing line before column i iff i is divisible by vmod
3003 * (so it's r in the first case and 1 in the second), and hmod
3004 * likewise for horizontal dividing lines.
3007 if (blocks
->r
!= 1) {
3015 * Line length: we have cr digits, each with a space after it,
3016 * and (cr-1)/vmod dividing lines, each with a space after it.
3017 * The final space is replaced by a newline, but that doesn't
3018 * affect the length.
3020 linelen
= 2*(cr
+ (cr
-1)/vmod
);
3023 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3026 nlines
= cr
+ (cr
-1)/hmod
;
3029 * Allocate the space.
3031 totallen
= linelen
* nlines
;
3032 ret
= snewn(totallen
+1, char); /* leave room for terminating NUL */
3038 for (y
= 0; y
< cr
; y
++) {
3042 for (x
= 0; x
< cr
; x
++) {
3046 digit d
= grid
[y
*cr
+x
];
3050 * Empty space: we usually write a dot, but we'll
3051 * highlight spaces on the X-diagonals (in X mode)
3052 * by using underscores instead.
3054 if (xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
)))
3058 } else if (d
<= 9) {
3075 * Optional dividing line.
3077 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[y
*cr
+x
+1])
3084 if (y
== cr
-1 || (y
+1) % hmod
)
3090 for (x
= 0; x
< cr
; x
++) {
3095 * Division between two squares. This varies
3096 * complicatedly in length.
3098 dwid
= 2; /* digit and its following space */
3100 dwid
--; /* no following space at end of line */
3101 if (x
> 0 && x
% vmod
== 0)
3102 dwid
++; /* preceding space after a divider */
3104 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[(y
+1)*cr
+x
])
3121 * Corner square. This is:
3122 * - a space if all four surrounding squares are in
3124 * - a vertical line if the two left ones are in one
3125 * block and the two right in another
3126 * - a horizontal line if the two top ones are in one
3127 * block and the two bottom in another
3128 * - a plus sign in all other cases. (If we had a
3129 * richer character set available we could break
3130 * this case up further by doing fun things with
3131 * line-drawing T-pieces.)
3133 tl
= blocks
->whichblock
[y
*cr
+x
];
3134 tr
= blocks
->whichblock
[y
*cr
+x
+1];
3135 bl
= blocks
->whichblock
[(y
+1)*cr
+x
];
3136 br
= blocks
->whichblock
[(y
+1)*cr
+x
+1];
3138 if (tl
== tr
&& tr
== bl
&& bl
== br
)
3140 else if (tl
== bl
&& tr
== br
)
3142 else if (tl
== tr
&& bl
== br
)
3151 assert(p
- ret
== totallen
);
3156 static char *game_text_format(game_state
*state
)
3158 return grid_text_format(state
->cr
, state
->blocks
, state
->xtype
,
3164 * These are the coordinates of the currently highlighted
3165 * square on the grid, or -1,-1 if there isn't one. When there
3166 * is, pressing a valid number or letter key or Space will
3167 * enter that number or letter in the grid.
3171 * This indicates whether the current highlight is a
3172 * pencil-mark one or a real one.
3177 static game_ui
*new_ui(game_state
*state
)
3179 game_ui
*ui
= snew(game_ui
);
3181 ui
->hx
= ui
->hy
= -1;
3187 static void free_ui(game_ui
*ui
)
3192 static char *encode_ui(game_ui
*ui
)
3197 static void decode_ui(game_ui
*ui
, char *encoding
)
3201 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
3202 game_state
*newstate
)
3204 int cr
= newstate
->cr
;
3206 * We prevent pencil-mode highlighting of a filled square. So
3207 * if the user has just filled in a square which we had a
3208 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3209 * then we cancel the highlight.
3211 if (ui
->hx
>= 0 && ui
->hy
>= 0 && ui
->hpencil
&&
3212 newstate
->grid
[ui
->hy
* cr
+ ui
->hx
] != 0) {
3213 ui
->hx
= ui
->hy
= -1;
3217 struct game_drawstate
{
3222 unsigned char *pencil
;
3224 /* This is scratch space used within a single call to game_redraw. */
3228 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
3229 int x
, int y
, int button
)
3235 button
&= ~MOD_MASK
;
3237 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
3238 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
3240 if (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
) {
3241 if (button
== LEFT_BUTTON
) {
3242 if (state
->immutable
[ty
*cr
+tx
]) {
3243 ui
->hx
= ui
->hy
= -1;
3244 } else if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
== 0) {
3245 ui
->hx
= ui
->hy
= -1;
3251 return ""; /* UI activity occurred */
3253 if (button
== RIGHT_BUTTON
) {
3255 * Pencil-mode highlighting for non filled squares.
3257 if (state
->grid
[ty
*cr
+tx
] == 0) {
3258 if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
) {
3259 ui
->hx
= ui
->hy
= -1;
3266 ui
->hx
= ui
->hy
= -1;
3268 return ""; /* UI activity occurred */
3272 if (ui
->hx
!= -1 && ui
->hy
!= -1 &&
3273 ((button
>= '1' && button
<= '9' && button
- '0' <= cr
) ||
3274 (button
>= 'a' && button
<= 'z' && button
- 'a' + 10 <= cr
) ||
3275 (button
>= 'A' && button
<= 'Z' && button
- 'A' + 10 <= cr
) ||
3276 button
== ' ' || button
== '\010' || button
== '\177')) {
3277 int n
= button
- '0';
3278 if (button
>= 'A' && button
<= 'Z')
3279 n
= button
- 'A' + 10;
3280 if (button
>= 'a' && button
<= 'z')
3281 n
= button
- 'a' + 10;
3282 if (button
== ' ' || button
== '\010' || button
== '\177')
3286 * Can't overwrite this square. In principle this shouldn't
3287 * happen anyway because we should never have even been
3288 * able to highlight the square, but it never hurts to be
3291 if (state
->immutable
[ui
->hy
*cr
+ui
->hx
])
3295 * Can't make pencil marks in a filled square. In principle
3296 * this shouldn't happen anyway because we should never
3297 * have even been able to pencil-highlight the square, but
3298 * it never hurts to be careful.
3300 if (ui
->hpencil
&& state
->grid
[ui
->hy
*cr
+ui
->hx
])
3303 sprintf(buf
, "%c%d,%d,%d",
3304 (char)(ui
->hpencil
&& n
> 0 ?
'P' : 'R'), ui
->hx
, ui
->hy
, n
);
3306 ui
->hx
= ui
->hy
= -1;
3314 static game_state
*execute_move(game_state
*from
, char *move
)
3320 if (move
[0] == 'S') {
3323 ret
= dup_game(from
);
3324 ret
->completed
= ret
->cheated
= TRUE
;
3327 for (n
= 0; n
< cr
*cr
; n
++) {
3328 ret
->grid
[n
] = atoi(p
);
3330 if (!*p
|| ret
->grid
[n
] < 1 || ret
->grid
[n
] > cr
) {
3335 while (*p
&& isdigit((unsigned char)*p
)) p
++;
3340 } else if ((move
[0] == 'P' || move
[0] == 'R') &&
3341 sscanf(move
+1, "%d,%d,%d", &x
, &y
, &n
) == 3 &&
3342 x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&& n
>= 0 && n
<= cr
) {
3344 ret
= dup_game(from
);
3345 if (move
[0] == 'P' && n
> 0) {
3346 int index
= (y
*cr
+x
) * cr
+ (n
-1);
3347 ret
->pencil
[index
] = !ret
->pencil
[index
];
3349 ret
->grid
[y
*cr
+x
] = n
;
3350 memset(ret
->pencil
+ (y
*cr
+x
)*cr
, 0, cr
);
3353 * We've made a real change to the grid. Check to see
3354 * if the game has been completed.
3356 if (!ret
->completed
&& check_valid(cr
, ret
->blocks
, ret
->xtype
,
3358 ret
->completed
= TRUE
;
3363 return NULL
; /* couldn't parse move string */
3366 /* ----------------------------------------------------------------------
3370 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3371 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3373 static void game_compute_size(game_params
*params
, int tilesize
,
3376 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3377 struct { int tilesize
; } ads
, *ds
= &ads
;
3378 ads
.tilesize
= tilesize
;
3380 *x
= SIZE(params
->c
* params
->r
);
3381 *y
= SIZE(params
->c
* params
->r
);
3384 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
3385 game_params
*params
, int tilesize
)
3387 ds
->tilesize
= tilesize
;
3390 static float *game_colours(frontend
*fe
, int *ncolours
)
3392 float *ret
= snewn(3 * NCOLOURS
, float);
3394 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
3396 ret
[COL_XDIAGONALS
* 3 + 0] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 0];
3397 ret
[COL_XDIAGONALS
* 3 + 1] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 1];
3398 ret
[COL_XDIAGONALS
* 3 + 2] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 2];
3400 ret
[COL_GRID
* 3 + 0] = 0.0F
;
3401 ret
[COL_GRID
* 3 + 1] = 0.0F
;
3402 ret
[COL_GRID
* 3 + 2] = 0.0F
;
3404 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
3405 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
3406 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
3408 ret
[COL_USER
* 3 + 0] = 0.0F
;
3409 ret
[COL_USER
* 3 + 1] = 0.6F
* ret
[COL_BACKGROUND
* 3 + 1];
3410 ret
[COL_USER
* 3 + 2] = 0.0F
;
3412 ret
[COL_HIGHLIGHT
* 3 + 0] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 0];
3413 ret
[COL_HIGHLIGHT
* 3 + 1] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 1];
3414 ret
[COL_HIGHLIGHT
* 3 + 2] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 2];
3416 ret
[COL_ERROR
* 3 + 0] = 1.0F
;
3417 ret
[COL_ERROR
* 3 + 1] = 0.0F
;
3418 ret
[COL_ERROR
* 3 + 2] = 0.0F
;
3420 ret
[COL_PENCIL
* 3 + 0] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 0];
3421 ret
[COL_PENCIL
* 3 + 1] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 1];
3422 ret
[COL_PENCIL
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2];
3424 *ncolours
= NCOLOURS
;
3428 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
3430 struct game_drawstate
*ds
= snew(struct game_drawstate
);
3433 ds
->started
= FALSE
;
3435 ds
->xtype
= state
->xtype
;
3436 ds
->grid
= snewn(cr
*cr
, digit
);
3437 memset(ds
->grid
, cr
+2, cr
*cr
);
3438 ds
->pencil
= snewn(cr
*cr
*cr
, digit
);
3439 memset(ds
->pencil
, 0, cr
*cr
*cr
);
3440 ds
->hl
= snewn(cr
*cr
, unsigned char);
3441 memset(ds
->hl
, 0, cr
*cr
);
3442 ds
->entered_items
= snewn(cr
*cr
, int);
3443 ds
->tilesize
= 0; /* not decided yet */
3447 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
3452 sfree(ds
->entered_items
);
3456 static void draw_number(drawing
*dr
, game_drawstate
*ds
, game_state
*state
,
3457 int x
, int y
, int hl
)
3464 if (ds
->grid
[y
*cr
+x
] == state
->grid
[y
*cr
+x
] &&
3465 ds
->hl
[y
*cr
+x
] == hl
&&
3466 !memcmp(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
))
3467 return; /* no change required */
3469 tx
= BORDER
+ x
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3470 ty
= BORDER
+ y
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3474 cw
= TILE_SIZE
-1-2*GRIDEXTRA
;
3475 ch
= TILE_SIZE
-1-2*GRIDEXTRA
;
3477 if (x
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
-1])
3478 cx
-= GRIDEXTRA
, cw
+= GRIDEXTRA
;
3479 if (x
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
+1])
3481 if (y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
-1)*cr
+x
])
3482 cy
-= GRIDEXTRA
, ch
+= GRIDEXTRA
;
3483 if (y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
+1)*cr
+x
])
3486 clip(dr
, cx
, cy
, cw
, ch
);
3488 /* background needs erasing */
3489 draw_rect(dr
, cx
, cy
, cw
, ch
,
3490 ((hl
& 15) == 1 ? COL_HIGHLIGHT
:
3491 (ds
->xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
))) ? COL_XDIAGONALS
:
3495 * Draw the corners of thick lines in corner-adjacent squares,
3496 * which jut into this square by one pixel.
3498 if (x
> 0 && y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
-1])
3499 draw_rect(dr
, tx
-GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3500 if (x
+1 < cr
&& y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
+1])
3501 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3502 if (x
> 0 && y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
-1])
3503 draw_rect(dr
, tx
-GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3504 if (x
+1 < cr
&& y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
+1])
3505 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3507 /* pencil-mode highlight */
3508 if ((hl
& 15) == 2) {
3512 coords
[2] = cx
+cw
/2;
3515 coords
[5] = cy
+ch
/2;
3516 draw_polygon(dr
, coords
, 3, COL_HIGHLIGHT
, COL_HIGHLIGHT
);
3519 /* new number needs drawing? */
3520 if (state
->grid
[y
*cr
+x
]) {
3522 str
[0] = state
->grid
[y
*cr
+x
] + '0';
3524 str
[0] += 'a' - ('9'+1);
3525 draw_text(dr
, tx
+ TILE_SIZE
/2, ty
+ TILE_SIZE
/2,
3526 FONT_VARIABLE
, TILE_SIZE
/2, ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3527 state
->immutable
[y
*cr
+x
] ? COL_CLUE
: (hl
& 16) ? COL_ERROR
: COL_USER
, str
);
3530 int pw
, ph
, pmax
, fontsize
;
3532 /* count the pencil marks required */
3533 for (i
= npencil
= 0; i
< cr
; i
++)
3534 if (state
->pencil
[(y
*cr
+x
)*cr
+i
])
3538 * It's not sensible to arrange pencil marks in the same
3539 * layout as the squares within a block, because this leads
3540 * to the font being too small. Instead, we arrange pencil
3541 * marks in the nearest thing we can to a square layout,
3542 * and we adjust the square layout depending on the number
3543 * of pencil marks in the square.
3545 for (pw
= 1; pw
* pw
< npencil
; pw
++);
3546 if (pw
< 3) pw
= 3; /* otherwise it just looks _silly_ */
3547 ph
= (npencil
+ pw
- 1) / pw
;
3548 if (ph
< 2) ph
= 2; /* likewise */
3550 fontsize
= TILE_SIZE
/(pmax
*(11-pmax
)/8);
3552 for (i
= j
= 0; i
< cr
; i
++)
3553 if (state
->pencil
[(y
*cr
+x
)*cr
+i
]) {
3554 int dx
= j
% pw
, dy
= j
/ pw
;
3559 str
[0] += 'a' - ('9'+1);
3560 draw_text(dr
, tx
+ (4*dx
+3) * TILE_SIZE
/ (4*pw
+2),
3561 ty
+ (4*dy
+3) * TILE_SIZE
/ (4*ph
+2),
3562 FONT_VARIABLE
, fontsize
,
3563 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_PENCIL
, str
);
3570 draw_update(dr
, cx
, cy
, cw
, ch
);
3572 ds
->grid
[y
*cr
+x
] = state
->grid
[y
*cr
+x
];
3573 memcpy(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
);
3574 ds
->hl
[y
*cr
+x
] = hl
;
3577 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3578 game_state
*state
, int dir
, game_ui
*ui
,
3579 float animtime
, float flashtime
)
3586 * The initial contents of the window are not guaranteed
3587 * and can vary with front ends. To be on the safe side,
3588 * all games should start by drawing a big
3589 * background-colour rectangle covering the whole window.
3591 draw_rect(dr
, 0, 0, SIZE(cr
), SIZE(cr
), COL_BACKGROUND
);
3594 * Draw the grid. We draw it as a big thick rectangle of
3595 * COL_GRID initially; individual calls to draw_number()
3596 * will poke the right-shaped holes in it.
3598 draw_rect(dr
, BORDER
-GRIDEXTRA
, BORDER
-GRIDEXTRA
,
3599 cr
*TILE_SIZE
+1+2*GRIDEXTRA
, cr
*TILE_SIZE
+1+2*GRIDEXTRA
,
3604 * This array is used to keep track of rows, columns and boxes
3605 * which contain a number more than once.
3607 for (x
= 0; x
< cr
* cr
; x
++)
3608 ds
->entered_items
[x
] = 0;
3609 for (x
= 0; x
< cr
; x
++)
3610 for (y
= 0; y
< cr
; y
++) {
3611 digit d
= state
->grid
[y
*cr
+x
];
3613 int box
= state
->blocks
->whichblock
[y
*cr
+x
];
3614 ds
->entered_items
[x
*cr
+d
-1] |= ((ds
->entered_items
[x
*cr
+d
-1] & 1) << 1) | 1;
3615 ds
->entered_items
[y
*cr
+d
-1] |= ((ds
->entered_items
[y
*cr
+d
-1] & 4) << 1) | 4;
3616 ds
->entered_items
[box
*cr
+d
-1] |= ((ds
->entered_items
[box
*cr
+d
-1] & 16) << 1) | 16;
3618 if (ondiag0(y
*cr
+x
))
3619 ds
->entered_items
[d
-1] |= ((ds
->entered_items
[d
-1] & 64) << 1) | 64;
3620 if (ondiag1(y
*cr
+x
))
3621 ds
->entered_items
[cr
+d
-1] |= ((ds
->entered_items
[cr
+d
-1] & 64) << 1) | 64;
3627 * Draw any numbers which need redrawing.
3629 for (x
= 0; x
< cr
; x
++) {
3630 for (y
= 0; y
< cr
; y
++) {
3632 digit d
= state
->grid
[y
*cr
+x
];
3634 if (flashtime
> 0 &&
3635 (flashtime
<= FLASH_TIME
/3 ||
3636 flashtime
>= FLASH_TIME
*2/3))
3639 /* Highlight active input areas. */
3640 if (x
== ui
->hx
&& y
== ui
->hy
)
3641 highlight
= ui
->hpencil ?
2 : 1;
3643 /* Mark obvious errors (ie, numbers which occur more than once
3644 * in a single row, column, or box). */
3645 if (d
&& ((ds
->entered_items
[x
*cr
+d
-1] & 2) ||
3646 (ds
->entered_items
[y
*cr
+d
-1] & 8) ||
3647 (ds
->entered_items
[state
->blocks
->whichblock
[y
*cr
+x
]*cr
+d
-1] & 32) ||
3648 (ds
->xtype
&& ((ondiag0(y
*cr
+x
) && (ds
->entered_items
[d
-1] & 128)) ||
3649 (ondiag1(y
*cr
+x
) && (ds
->entered_items
[cr
+d
-1] & 128))))))
3652 draw_number(dr
, ds
, state
, x
, y
, highlight
);
3657 * Update the _entire_ grid if necessary.
3660 draw_update(dr
, 0, 0, SIZE(cr
), SIZE(cr
));
3665 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
3666 int dir
, game_ui
*ui
)
3671 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3672 int dir
, game_ui
*ui
)
3674 if (!oldstate
->completed
&& newstate
->completed
&&
3675 !oldstate
->cheated
&& !newstate
->cheated
)
3680 static int game_timing_state(game_state
*state
, game_ui
*ui
)
3685 static void game_print_size(game_params
*params
, float *x
, float *y
)
3690 * I'll use 9mm squares by default. They should be quite big
3691 * for this game, because players will want to jot down no end
3692 * of pencil marks in the squares.
3694 game_compute_size(params
, 900, &pw
, &ph
);
3699 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3702 int ink
= print_mono_colour(dr
, 0);
3705 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3706 game_drawstate ads
, *ds
= &ads
;
3707 game_set_size(dr
, ds
, NULL
, tilesize
);
3712 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
3713 draw_rect_outline(dr
, BORDER
, BORDER
, cr
*TILE_SIZE
, cr
*TILE_SIZE
, ink
);
3716 * Highlight X-diagonal squares.
3720 int xhighlight
= print_grey_colour(dr
, HATCH_SLASH
, 0.90F
);
3722 for (i
= 0; i
< cr
; i
++)
3723 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
, BORDER
+ i
*TILE_SIZE
,
3724 TILE_SIZE
, TILE_SIZE
, xhighlight
);
3725 for (i
= 0; i
< cr
; i
++)
3726 if (i
*2 != cr
-1) /* avoid redoing centre square, just for fun */
3727 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
,
3728 BORDER
+ (cr
-1-i
)*TILE_SIZE
,
3729 TILE_SIZE
, TILE_SIZE
, xhighlight
);
3735 for (x
= 1; x
< cr
; x
++) {
3736 print_line_width(dr
, TILE_SIZE
/ 40);
3737 draw_line(dr
, BORDER
+x
*TILE_SIZE
, BORDER
,
3738 BORDER
+x
*TILE_SIZE
, BORDER
+cr
*TILE_SIZE
, ink
);
3740 for (y
= 1; y
< cr
; y
++) {
3741 print_line_width(dr
, TILE_SIZE
/ 40);
3742 draw_line(dr
, BORDER
, BORDER
+y
*TILE_SIZE
,
3743 BORDER
+cr
*TILE_SIZE
, BORDER
+y
*TILE_SIZE
, ink
);
3747 * Thick lines between cells. In order to do this using the
3748 * line-drawing rather than rectangle-drawing API (so as to
3749 * get line thicknesses to scale correctly) and yet have
3750 * correctly mitred joins between lines, we must do this by
3751 * tracing the boundary of each sub-block and drawing it in
3752 * one go as a single polygon.
3757 int x
, y
, dx
, dy
, sx
, sy
, sdx
, sdy
;
3759 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
3762 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3763 * with k unconnected squares, with total perimeter 4k.
3764 * Now repeatedly join two disconnected components
3765 * together into a larger one; every time you do so you
3766 * remove at least two unit edges, and you require k-1 of
3767 * these operations to create a single connected piece, so
3768 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3771 coords
= snewn(4*cr
+4, int); /* 2k+2 points, 2 coords per point */
3774 * Iterate over all the blocks.
3776 for (bi
= 0; bi
< cr
; bi
++) {
3779 * For each block, find a starting square within it
3780 * which has a boundary at the left.
3782 for (i
= 0; i
< cr
; i
++) {
3783 int j
= state
->blocks
->blocks
[bi
][i
];
3784 if (j
% cr
== 0 || state
->blocks
->whichblock
[j
-1] != bi
)
3787 assert(i
< cr
); /* every block must have _some_ leftmost square */
3788 x
= state
->blocks
->blocks
[bi
][i
] % cr
;
3789 y
= state
->blocks
->blocks
[bi
][i
] / cr
;
3794 * Now begin tracing round the perimeter. At all
3795 * times, (x,y) describes some square within the
3796 * block, and (x+dx,y+dy) is some adjacent square
3797 * outside it; so the edge between those two squares
3798 * is always an edge of the block.
3800 sx
= x
, sy
= y
, sdx
= dx
, sdy
= dy
; /* save starting position */
3803 int cx
, cy
, tx
, ty
, nin
;
3806 * To begin with, record the point at one end of
3807 * the edge. To do this, we translate (x,y) down
3808 * and right by half a unit (so they're describing
3809 * a point in the _centre_ of the square) and then
3810 * translate back again in a manner rotated by dy
3814 cx
= ((2*x
+1) + dy
+ dx
) / 2;
3815 cy
= ((2*y
+1) - dx
+ dy
) / 2;
3816 coords
[2*n
+0] = BORDER
+ cx
* TILE_SIZE
;
3817 coords
[2*n
+1] = BORDER
+ cy
* TILE_SIZE
;
3821 * Now advance to the next edge, by looking at the
3822 * two squares beyond it. If they're both outside
3823 * the block, we turn right (by leaving x,y the
3824 * same and rotating dx,dy clockwise); if they're
3825 * both inside, we turn left (by rotating dx,dy
3826 * anticlockwise and contriving to leave x+dx,y+dy
3827 * unchanged); if one of each, we go straight on
3828 * (and may enforce by assertion that they're one
3829 * of each the _right_ way round).
3834 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3835 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3838 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3839 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3848 } else if (nin
== 2) {
3872 * Now enforce by assertion that we ended up
3873 * somewhere sensible.
3875 assert(x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&&
3876 state
->blocks
->whichblock
[y
*cr
+x
] == bi
);
3877 assert(x
+dx
< 0 || x
+dx
>= cr
|| y
+dy
< 0 || y
+dy
>= cr
||
3878 state
->blocks
->whichblock
[(y
+dy
)*cr
+(x
+dx
)] != bi
);
3880 } while (x
!= sx
|| y
!= sy
|| dx
!= sdx
|| dy
!= sdy
);
3883 * That's our polygon; now draw it.
3885 draw_polygon(dr
, coords
, n
, -1, ink
);
3894 for (y
= 0; y
< cr
; y
++)
3895 for (x
= 0; x
< cr
; x
++)
3896 if (state
->grid
[y
*cr
+x
]) {
3899 str
[0] = state
->grid
[y
*cr
+x
] + '0';
3901 str
[0] += 'a' - ('9'+1);
3902 draw_text(dr
, BORDER
+ x
*TILE_SIZE
+ TILE_SIZE
/2,
3903 BORDER
+ y
*TILE_SIZE
+ TILE_SIZE
/2,
3904 FONT_VARIABLE
, TILE_SIZE
/2,
3905 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, str
);
3910 #define thegame solo
3913 const struct game thegame
= {
3914 "Solo", "games.solo", "solo",
3921 TRUE
, game_configure
, custom_params
,
3929 TRUE
, game_text_format
,
3937 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3940 game_free_drawstate
,
3944 TRUE
, FALSE
, game_print_size
, game_print
,
3945 FALSE
, /* wants_statusbar */
3946 FALSE
, game_timing_state
,
3947 REQUIRE_RBUTTON
| REQUIRE_NUMPAD
, /* flags */
3950 #ifdef STANDALONE_SOLVER
3952 int main(int argc
, char **argv
)
3956 char *id
= NULL
, *desc
, *err
;
3960 while (--argc
> 0) {
3962 if (!strcmp(p
, "-v")) {
3963 solver_show_working
= TRUE
;
3964 } else if (!strcmp(p
, "-g")) {
3966 } else if (*p
== '-') {
3967 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
3975 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
3979 desc
= strchr(id
, ':');
3981 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
3986 p
= default_params();
3987 decode_params(p
, id
);
3988 err
= validate_desc(p
, desc
);
3990 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
3993 s
= new_game(NULL
, p
, desc
);
3995 ret
= solver(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
, DIFF_RECURSIVE
);
3997 printf("Difficulty rating: %s\n",
3998 ret
==DIFF_BLOCK ?
"Trivial (blockwise positional elimination only)":
3999 ret
==DIFF_SIMPLE ?
"Basic (row/column/number elimination required)":
4000 ret
==DIFF_INTERSECT ?
"Intermediate (intersectional analysis required)":
4001 ret
==DIFF_SET ?
"Advanced (set elimination required)":
4002 ret
==DIFF_EXTREME ?
"Extreme (complex non-recursive techniques required)":
4003 ret
==DIFF_RECURSIVE ?
"Unreasonable (guesswork and backtracking required)":
4004 ret
==DIFF_AMBIGUOUS ?
"Ambiguous (multiple solutions exist)":
4005 ret
==DIFF_IMPOSSIBLE ?
"Impossible (no solution exists)":
4006 "INTERNAL ERROR: unrecognised difficulty code");
4008 printf("%s\n", grid_text_format(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
));