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
;
99 #define max(x,y) ((x)>(y)?(x):(y))
102 * To save space, I store digits internally as unsigned char. This
103 * imposes a hard limit of 255 on the order of the puzzle. Since
104 * even a 5x5 takes unacceptably long to generate, I don't see this
105 * as a serious limitation unless something _really_ impressive
106 * happens in computing technology; but here's a typedef anyway for
107 * general good practice.
109 typedef unsigned char digit
;
110 #define ORDER_MAX 255
115 #define FLASH_TIME 0.4F
117 enum { SYMM_NONE
, SYMM_ROT2
, SYMM_ROT4
, SYMM_REF4
};
119 enum { DIFF_BLOCK
, DIFF_SIMPLE
, DIFF_INTERSECT
,
120 DIFF_SET
, DIFF_RECURSIVE
, DIFF_AMBIGUOUS
, DIFF_IMPOSSIBLE
};
133 int c
, r
, symm
, diff
;
139 unsigned char *pencil
; /* c*r*c*r elements */
140 unsigned char *immutable
; /* marks which digits are clues */
141 int completed
, cheated
;
144 static game_params
*default_params(void)
146 game_params
*ret
= snew(game_params
);
149 ret
->symm
= SYMM_ROT2
; /* a plausible default */
150 ret
->diff
= DIFF_BLOCK
; /* so is this */
155 static void free_params(game_params
*params
)
160 static game_params
*dup_params(game_params
*params
)
162 game_params
*ret
= snew(game_params
);
163 *ret
= *params
; /* structure copy */
167 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
173 { "2x2 Trivial", { 2, 2, SYMM_ROT2
, DIFF_BLOCK
} },
174 { "2x3 Basic", { 2, 3, SYMM_ROT2
, DIFF_SIMPLE
} },
175 { "3x3 Trivial", { 3, 3, SYMM_ROT2
, DIFF_BLOCK
} },
176 { "3x3 Basic", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
} },
177 { "3x3 Intermediate", { 3, 3, SYMM_ROT2
, DIFF_INTERSECT
} },
178 { "3x3 Advanced", { 3, 3, SYMM_ROT2
, DIFF_SET
} },
179 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2
, DIFF_RECURSIVE
} },
180 { "3x4 Basic", { 3, 4, SYMM_ROT2
, DIFF_SIMPLE
} },
181 { "4x4 Basic", { 4, 4, SYMM_ROT2
, DIFF_SIMPLE
} },
184 if (i
< 0 || i
>= lenof(presets
))
187 *name
= dupstr(presets
[i
].title
);
188 *params
= dup_params(&presets
[i
].params
);
193 static void decode_params(game_params
*ret
, char const *string
)
195 ret
->c
= ret
->r
= atoi(string
);
196 while (*string
&& isdigit((unsigned char)*string
)) string
++;
197 if (*string
== 'x') {
199 ret
->r
= atoi(string
);
200 while (*string
&& isdigit((unsigned char)*string
)) string
++;
203 if (*string
== 'r' || *string
== 'm' || *string
== 'a') {
207 while (*string
&& isdigit((unsigned char)*string
)) string
++;
208 if (sc
== 'm' && sn
== 4)
209 ret
->symm
= SYMM_REF4
;
210 if (sc
== 'r' && sn
== 4)
211 ret
->symm
= SYMM_ROT4
;
212 if (sc
== 'r' && sn
== 2)
213 ret
->symm
= SYMM_ROT2
;
215 ret
->symm
= SYMM_NONE
;
216 } else if (*string
== 'd') {
218 if (*string
== 't') /* trivial */
219 string
++, ret
->diff
= DIFF_BLOCK
;
220 else if (*string
== 'b') /* basic */
221 string
++, ret
->diff
= DIFF_SIMPLE
;
222 else if (*string
== 'i') /* intermediate */
223 string
++, ret
->diff
= DIFF_INTERSECT
;
224 else if (*string
== 'a') /* advanced */
225 string
++, ret
->diff
= DIFF_SET
;
226 else if (*string
== 'u') /* unreasonable */
227 string
++, ret
->diff
= DIFF_RECURSIVE
;
229 string
++; /* eat unknown character */
233 static char *encode_params(game_params
*params
, int full
)
237 sprintf(str
, "%dx%d", params
->c
, params
->r
);
239 switch (params
->symm
) {
240 case SYMM_REF4
: strcat(str
, "m4"); break;
241 case SYMM_ROT4
: strcat(str
, "r4"); break;
242 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
243 case SYMM_NONE
: strcat(str
, "a"); break;
245 switch (params
->diff
) {
246 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
247 case DIFF_SIMPLE
: strcat(str
, "db"); break;
248 case DIFF_INTERSECT
: strcat(str
, "di"); break;
249 case DIFF_SET
: strcat(str
, "da"); break;
250 case DIFF_RECURSIVE
: strcat(str
, "du"); break;
256 static config_item
*game_configure(game_params
*params
)
261 ret
= snewn(5, config_item
);
263 ret
[0].name
= "Columns of sub-blocks";
264 ret
[0].type
= C_STRING
;
265 sprintf(buf
, "%d", params
->c
);
266 ret
[0].sval
= dupstr(buf
);
269 ret
[1].name
= "Rows of sub-blocks";
270 ret
[1].type
= C_STRING
;
271 sprintf(buf
, "%d", params
->r
);
272 ret
[1].sval
= dupstr(buf
);
275 ret
[2].name
= "Symmetry";
276 ret
[2].type
= C_CHOICES
;
277 ret
[2].sval
= ":None:2-way rotation:4-way rotation:4-way mirror";
278 ret
[2].ival
= params
->symm
;
280 ret
[3].name
= "Difficulty";
281 ret
[3].type
= C_CHOICES
;
282 ret
[3].sval
= ":Trivial:Basic:Intermediate:Advanced:Unreasonable";
283 ret
[3].ival
= params
->diff
;
293 static game_params
*custom_params(config_item
*cfg
)
295 game_params
*ret
= snew(game_params
);
297 ret
->c
= atoi(cfg
[0].sval
);
298 ret
->r
= atoi(cfg
[1].sval
);
299 ret
->symm
= cfg
[2].ival
;
300 ret
->diff
= cfg
[3].ival
;
305 static char *validate_params(game_params
*params
)
307 if (params
->c
< 2 || params
->r
< 2)
308 return "Both dimensions must be at least 2";
309 if (params
->c
> ORDER_MAX
|| params
->r
> ORDER_MAX
)
310 return "Dimensions greater than "STR(ORDER_MAX
)" are not supported";
314 /* ----------------------------------------------------------------------
315 * Full recursive Solo solver.
317 * The algorithm for this solver is shamelessly copied from a
318 * Python solver written by Andrew Wilkinson (which is GPLed, but
319 * I've reused only ideas and no code). It mostly just does the
320 * obvious recursive thing: pick an empty square, put one of the
321 * possible digits in it, recurse until all squares are filled,
322 * backtrack and change some choices if necessary.
324 * The clever bit is that every time it chooses which square to
325 * fill in next, it does so by counting the number of _possible_
326 * numbers that can go in each square, and it prioritises so that
327 * it picks a square with the _lowest_ number of possibilities. The
328 * idea is that filling in lots of the obvious bits (particularly
329 * any squares with only one possibility) will cut down on the list
330 * of possibilities for other squares and hence reduce the enormous
331 * search space as much as possible as early as possible.
333 * In practice the algorithm appeared to work very well; run on
334 * sample problems from the Times it completed in well under a
335 * second on my G5 even when written in Python, and given an empty
336 * grid (so that in principle it would enumerate _all_ solved
337 * grids!) it found the first valid solution just as quickly. So
338 * with a bit more randomisation I see no reason not to use this as
343 * Internal data structure used in solver to keep track of
346 struct rsolve_coord
{ int x
, y
, r
; };
347 struct rsolve_usage
{
348 int c
, r
, cr
; /* cr == c*r */
349 /* grid is a copy of the input grid, modified as we go along */
351 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
353 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
355 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
357 /* This lists all the empty spaces remaining in the grid. */
358 struct rsolve_coord
*spaces
;
360 /* If we need randomisation in the solve, this is our random state. */
362 /* Number of solutions so far found, and maximum number we care about. */
367 * The real recursive step in the solving function.
369 static void rsolve_real(struct rsolve_usage
*usage
, digit
*grid
)
371 int c
= usage
->c
, r
= usage
->r
, cr
= usage
->cr
;
372 int i
, j
, n
, sx
, sy
, bestm
, bestr
;
376 * Firstly, check for completion! If there are no spaces left
377 * in the grid, we have a solution.
379 if (usage
->nspaces
== 0) {
382 * This is our first solution, so fill in the output grid.
384 memcpy(grid
, usage
->grid
, cr
* cr
);
391 * Otherwise, there must be at least one space. Find the most
392 * constrained space, using the `r' field as a tie-breaker.
394 bestm
= cr
+1; /* so that any space will beat it */
397 for (j
= 0; j
< usage
->nspaces
; j
++) {
398 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
402 * Find the number of digits that could go in this space.
405 for (n
= 0; n
< cr
; n
++)
406 if (!usage
->row
[y
*cr
+n
] && !usage
->col
[x
*cr
+n
] &&
407 !usage
->blk
[((y
/c
)*c
+(x
/r
))*cr
+n
])
410 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
412 bestr
= usage
->spaces
[j
].r
;
420 * Swap that square into the final place in the spaces array,
421 * so that decrementing nspaces will remove it from the list.
423 if (i
!= usage
->nspaces
-1) {
424 struct rsolve_coord t
;
425 t
= usage
->spaces
[usage
->nspaces
-1];
426 usage
->spaces
[usage
->nspaces
-1] = usage
->spaces
[i
];
427 usage
->spaces
[i
] = t
;
431 * Now we've decided which square to start our recursion at,
432 * simply go through all possible values, shuffling them
433 * randomly first if necessary.
435 digits
= snewn(bestm
, int);
437 for (n
= 0; n
< cr
; n
++)
438 if (!usage
->row
[sy
*cr
+n
] && !usage
->col
[sx
*cr
+n
] &&
439 !usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
]) {
445 for (i
= j
; i
> 1; i
--) {
446 int p
= random_upto(usage
->rs
, i
);
449 digits
[p
] = digits
[i
-1];
455 /* And finally, go through the digit list and actually recurse. */
456 for (i
= 0; i
< j
; i
++) {
459 /* Update the usage structure to reflect the placing of this digit. */
460 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
461 usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
-1] = TRUE
;
462 usage
->grid
[sy
*cr
+sx
] = n
;
465 /* Call the solver recursively. */
466 rsolve_real(usage
, grid
);
469 * If we have seen as many solutions as we need, terminate
470 * all processing immediately.
472 if (usage
->solns
>= usage
->maxsolns
)
475 /* Revert the usage structure. */
476 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
477 usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
-1] = FALSE
;
478 usage
->grid
[sy
*cr
+sx
] = 0;
486 * Entry point to solver. You give it dimensions and a starting
487 * grid, which is simply an array of N^4 digits. In that array, 0
488 * means an empty square, and 1..N mean a clue square.
490 * Return value is the number of solutions found; searching will
491 * stop after the provided `max'. (Thus, you can pass max==1 to
492 * indicate that you only care about finding _one_ solution, or
493 * max==2 to indicate that you want to know the difference between
494 * a unique and non-unique solution.) The input parameter `grid' is
495 * also filled in with the _first_ (or only) solution found by the
498 static int rsolve(int c
, int r
, digit
*grid
, random_state
*rs
, int max
)
500 struct rsolve_usage
*usage
;
505 * Create an rsolve_usage structure.
507 usage
= snew(struct rsolve_usage
);
513 usage
->grid
= snewn(cr
* cr
, digit
);
514 memcpy(usage
->grid
, grid
, cr
* cr
);
516 usage
->row
= snewn(cr
* cr
, unsigned char);
517 usage
->col
= snewn(cr
* cr
, unsigned char);
518 usage
->blk
= snewn(cr
* cr
, unsigned char);
519 memset(usage
->row
, FALSE
, cr
* cr
);
520 memset(usage
->col
, FALSE
, cr
* cr
);
521 memset(usage
->blk
, FALSE
, cr
* cr
);
523 usage
->spaces
= snewn(cr
* cr
, struct rsolve_coord
);
527 usage
->maxsolns
= max
;
532 * Now fill it in with data from the input grid.
534 for (y
= 0; y
< cr
; y
++) {
535 for (x
= 0; x
< cr
; x
++) {
536 int v
= grid
[y
*cr
+x
];
538 usage
->spaces
[usage
->nspaces
].x
= x
;
539 usage
->spaces
[usage
->nspaces
].y
= y
;
541 usage
->spaces
[usage
->nspaces
].r
= random_bits(rs
, 31);
543 usage
->spaces
[usage
->nspaces
].r
= usage
->nspaces
;
546 usage
->row
[y
*cr
+v
-1] = TRUE
;
547 usage
->col
[x
*cr
+v
-1] = TRUE
;
548 usage
->blk
[((y
/c
)*c
+(x
/r
))*cr
+v
-1] = TRUE
;
554 * Run the real recursive solving function.
556 rsolve_real(usage
, grid
);
560 * Clean up the usage structure now we have our answer.
562 sfree(usage
->spaces
);
575 /* ----------------------------------------------------------------------
576 * End of recursive solver code.
579 /* ----------------------------------------------------------------------
580 * Less capable non-recursive solver. This one is used to check
581 * solubility of a grid as we gradually remove numbers from it: by
582 * verifying a grid using this solver we can ensure it isn't _too_
583 * hard (e.g. does not actually require guessing and backtracking).
585 * It supports a variety of specific modes of reasoning. By
586 * enabling or disabling subsets of these modes we can arrange a
587 * range of difficulty levels.
591 * Modes of reasoning currently supported:
593 * - Positional elimination: a number must go in a particular
594 * square because all the other empty squares in a given
595 * row/col/blk are ruled out.
597 * - Numeric elimination: a square must have a particular number
598 * in because all the other numbers that could go in it are
601 * - Intersectional analysis: given two domains which overlap
602 * (hence one must be a block, and the other can be a row or
603 * col), if the possible locations for a particular number in
604 * one of the domains can be narrowed down to the overlap, then
605 * that number can be ruled out everywhere but the overlap in
606 * the other domain too.
608 * - Set elimination: if there is a subset of the empty squares
609 * within a domain such that the union of the possible numbers
610 * in that subset has the same size as the subset itself, then
611 * those numbers can be ruled out everywhere else in the domain.
612 * (For example, if there are five empty squares and the
613 * possible numbers in each are 12, 23, 13, 134 and 1345, then
614 * the first three empty squares form such a subset: the numbers
615 * 1, 2 and 3 _must_ be in those three squares in some
616 * permutation, and hence we can deduce none of them can be in
617 * the fourth or fifth squares.)
618 * + You can also see this the other way round, concentrating
619 * on numbers rather than squares: if there is a subset of
620 * the unplaced numbers within a domain such that the union
621 * of all their possible positions has the same size as the
622 * subset itself, then all other numbers can be ruled out for
623 * those positions. However, it turns out that this is
624 * exactly equivalent to the first formulation at all times:
625 * there is a 1-1 correspondence between suitable subsets of
626 * the unplaced numbers and suitable subsets of the unfilled
627 * places, found by taking the _complement_ of the union of
628 * the numbers' possible positions (or the spaces' possible
633 * Within this solver, I'm going to transform all y-coordinates by
634 * inverting the significance of the block number and the position
635 * within the block. That is, we will start with the top row of
636 * each block in order, then the second row of each block in order,
639 * This transformation has the enormous advantage that it means
640 * every row, column _and_ block is described by an arithmetic
641 * progression of coordinates within the cubic array, so that I can
642 * use the same very simple function to do blockwise, row-wise and
643 * column-wise elimination.
645 #define YTRANS(y) (((y)%c)*r+(y)/c)
646 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
648 struct nsolve_usage
{
651 * We set up a cubic array, indexed by x, y and digit; each
652 * element of this array is TRUE or FALSE according to whether
653 * or not that digit _could_ in principle go in that position.
655 * The way to index this array is cube[(x*cr+y)*cr+n-1].
656 * y-coordinates in here are transformed.
660 * This is the grid in which we write down our final
661 * deductions. y-coordinates in here are _not_ transformed.
665 * Now we keep track, at a slightly higher level, of what we
666 * have yet to work out, to prevent doing the same deduction
669 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
671 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
673 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
676 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
677 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
680 * Function called when we are certain that a particular square has
681 * a particular number in it. The y-coordinate passed in here is
684 static void nsolve_place(struct nsolve_usage
*usage
, int x
, int y
, int n
)
686 int c
= usage
->c
, r
= usage
->r
, cr
= usage
->cr
;
692 * Rule out all other numbers in this square.
694 for (i
= 1; i
<= cr
; i
++)
699 * Rule out this number in all other positions in the row.
701 for (i
= 0; i
< cr
; i
++)
706 * Rule out this number in all other positions in the column.
708 for (i
= 0; i
< cr
; i
++)
713 * Rule out this number in all other positions in the block.
717 for (i
= 0; i
< r
; i
++)
718 for (j
= 0; j
< c
; j
++)
719 if (bx
+i
!= x
|| by
+j
*r
!= y
)
720 cube(bx
+i
,by
+j
*r
,n
) = FALSE
;
723 * Enter the number in the result grid.
725 usage
->grid
[YUNTRANS(y
)*cr
+x
] = n
;
728 * Cross out this number from the list of numbers left to place
729 * in its row, its column and its block.
731 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
732 usage
->blk
[((y
%r
)*c
+(x
/r
))*cr
+n
-1] = TRUE
;
735 static int nsolve_elim(struct nsolve_usage
*usage
, int start
, int step
736 #ifdef STANDALONE_SOLVER
741 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
745 * Count the number of set bits within this section of the
750 for (i
= 0; i
< cr
; i
++)
751 if (usage
->cube
[start
+i
*step
]) {
765 if (!usage
->grid
[YUNTRANS(y
)*cr
+x
]) {
766 #ifdef STANDALONE_SOLVER
767 if (solver_show_working
) {
772 printf(":\n placing %d at (%d,%d)\n",
773 n
, 1+x
, 1+YUNTRANS(y
));
776 nsolve_place(usage
, x
, y
, n
);
784 static int nsolve_intersect(struct nsolve_usage
*usage
,
785 int start1
, int step1
, int start2
, int step2
786 #ifdef STANDALONE_SOLVER
791 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
795 * Loop over the first domain and see if there's any set bit
796 * not also in the second.
798 for (i
= 0; i
< cr
; i
++) {
799 int p
= start1
+i
*step1
;
800 if (usage
->cube
[p
] &&
801 !(p
>= start2
&& p
< start2
+cr
*step2
&&
802 (p
- start2
) % step2
== 0))
803 return FALSE
; /* there is, so we can't deduce */
807 * We have determined that all set bits in the first domain are
808 * within its overlap with the second. So loop over the second
809 * domain and remove all set bits that aren't also in that
810 * overlap; return TRUE iff we actually _did_ anything.
813 for (i
= 0; i
< cr
; i
++) {
814 int p
= start2
+i
*step2
;
815 if (usage
->cube
[p
] &&
816 !(p
>= start1
&& p
< start1
+cr
*step1
&& (p
- start1
) % step1
== 0))
818 #ifdef STANDALONE_SOLVER
819 if (solver_show_working
) {
835 printf(" ruling out %d at (%d,%d)\n",
836 pn
, 1+px
, 1+YUNTRANS(py
));
839 ret
= TRUE
; /* we did something */
847 static int nsolve_set(struct nsolve_usage
*usage
,
848 int start
, int step1
, int step2
849 #ifdef STANDALONE_SOLVER
854 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
856 unsigned char *grid
= snewn(cr
*cr
, unsigned char);
857 unsigned char *rowidx
= snewn(cr
, unsigned char);
858 unsigned char *colidx
= snewn(cr
, unsigned char);
859 unsigned char *set
= snewn(cr
, unsigned char);
862 * We are passed a cr-by-cr matrix of booleans. Our first job
863 * is to winnow it by finding any definite placements - i.e.
864 * any row with a solitary 1 - and discarding that row and the
865 * column containing the 1.
867 memset(rowidx
, TRUE
, cr
);
868 memset(colidx
, TRUE
, cr
);
869 for (i
= 0; i
< cr
; i
++) {
870 int count
= 0, first
= -1;
871 for (j
= 0; j
< cr
; j
++)
872 if (usage
->cube
[start
+i
*step1
+j
*step2
])
876 * This condition actually marks a completely insoluble
877 * (i.e. internally inconsistent) puzzle. We return and
878 * report no progress made.
883 rowidx
[i
] = colidx
[first
] = FALSE
;
887 * Convert each of rowidx/colidx from a list of 0s and 1s to a
888 * list of the indices of the 1s.
890 for (i
= j
= 0; i
< cr
; i
++)
894 for (i
= j
= 0; i
< cr
; i
++)
900 * And create the smaller matrix.
902 for (i
= 0; i
< n
; i
++)
903 for (j
= 0; j
< n
; j
++)
904 grid
[i
*cr
+j
] = usage
->cube
[start
+rowidx
[i
]*step1
+colidx
[j
]*step2
];
907 * Having done that, we now have a matrix in which every row
908 * has at least two 1s in. Now we search to see if we can find
909 * a rectangle of zeroes (in the set-theoretic sense of
910 * `rectangle', i.e. a subset of rows crossed with a subset of
911 * columns) whose width and height add up to n.
918 * We have a candidate set. If its size is <=1 or >=n-1
919 * then we move on immediately.
921 if (count
> 1 && count
< n
-1) {
923 * The number of rows we need is n-count. See if we can
924 * find that many rows which each have a zero in all
925 * the positions listed in `set'.
928 for (i
= 0; i
< n
; i
++) {
930 for (j
= 0; j
< n
; j
++)
931 if (set
[j
] && grid
[i
*cr
+j
]) {
940 * We expect never to be able to get _more_ than
941 * n-count suitable rows: this would imply that (for
942 * example) there are four numbers which between them
943 * have at most three possible positions, and hence it
944 * indicates a faulty deduction before this point or
947 assert(rows
<= n
- count
);
948 if (rows
>= n
- count
) {
949 int progress
= FALSE
;
952 * We've got one! Now, for each row which _doesn't_
953 * satisfy the criterion, eliminate all its set
954 * bits in the positions _not_ listed in `set'.
955 * Return TRUE (meaning progress has been made) if
956 * we successfully eliminated anything at all.
958 * This involves referring back through
959 * rowidx/colidx in order to work out which actual
960 * positions in the cube to meddle with.
962 for (i
= 0; i
< n
; i
++) {
964 for (j
= 0; j
< n
; j
++)
965 if (set
[j
] && grid
[i
*cr
+j
]) {
970 for (j
= 0; j
< n
; j
++)
971 if (!set
[j
] && grid
[i
*cr
+j
]) {
972 int fpos
= (start
+rowidx
[i
]*step1
+
974 #ifdef STANDALONE_SOLVER
975 if (solver_show_working
) {
991 printf(" ruling out %d at (%d,%d)\n",
992 pn
, 1+px
, 1+YUNTRANS(py
));
996 usage
->cube
[fpos
] = FALSE
;
1012 * Binary increment: change the rightmost 0 to a 1, and
1013 * change all 1s to the right of it to 0s.
1016 while (i
> 0 && set
[i
-1])
1017 set
[--i
] = 0, count
--;
1019 set
[--i
] = 1, count
++;
1032 static int nsolve(int c
, int r
, digit
*grid
)
1034 struct nsolve_usage
*usage
;
1037 int diff
= DIFF_BLOCK
;
1040 * Set up a usage structure as a clean slate (everything
1043 usage
= snew(struct nsolve_usage
);
1047 usage
->cube
= snewn(cr
*cr
*cr
, unsigned char);
1048 usage
->grid
= grid
; /* write straight back to the input */
1049 memset(usage
->cube
, TRUE
, cr
*cr
*cr
);
1051 usage
->row
= snewn(cr
* cr
, unsigned char);
1052 usage
->col
= snewn(cr
* cr
, unsigned char);
1053 usage
->blk
= snewn(cr
* cr
, unsigned char);
1054 memset(usage
->row
, FALSE
, cr
* cr
);
1055 memset(usage
->col
, FALSE
, cr
* cr
);
1056 memset(usage
->blk
, FALSE
, cr
* cr
);
1059 * Place all the clue numbers we are given.
1061 for (x
= 0; x
< cr
; x
++)
1062 for (y
= 0; y
< cr
; y
++)
1064 nsolve_place(usage
, x
, YTRANS(y
), grid
[y
*cr
+x
]);
1067 * Now loop over the grid repeatedly trying all permitted modes
1068 * of reasoning. The loop terminates if we complete an
1069 * iteration without making any progress; we then return
1070 * failure or success depending on whether the grid is full or
1075 * I'd like to write `continue;' inside each of the
1076 * following loops, so that the solver returns here after
1077 * making some progress. However, I can't specify that I
1078 * want to continue an outer loop rather than the innermost
1079 * one, so I'm apologetically resorting to a goto.
1084 * Blockwise positional elimination.
1086 for (x
= 0; x
< cr
; x
+= r
)
1087 for (y
= 0; y
< r
; y
++)
1088 for (n
= 1; n
<= cr
; n
++)
1089 if (!usage
->blk
[(y
*c
+(x
/r
))*cr
+n
-1] &&
1090 nsolve_elim(usage
, cubepos(x
,y
,n
), r
*cr
1091 #ifdef STANDALONE_SOLVER
1092 , "positional elimination,"
1093 " block (%d,%d)", 1+x
/r
, 1+y
1096 diff
= max(diff
, DIFF_BLOCK
);
1101 * Row-wise positional elimination.
1103 for (y
= 0; y
< cr
; y
++)
1104 for (n
= 1; n
<= cr
; n
++)
1105 if (!usage
->row
[y
*cr
+n
-1] &&
1106 nsolve_elim(usage
, cubepos(0,y
,n
), cr
*cr
1107 #ifdef STANDALONE_SOLVER
1108 , "positional elimination,"
1109 " row %d", 1+YUNTRANS(y
)
1112 diff
= max(diff
, DIFF_SIMPLE
);
1116 * Column-wise positional elimination.
1118 for (x
= 0; x
< cr
; x
++)
1119 for (n
= 1; n
<= cr
; n
++)
1120 if (!usage
->col
[x
*cr
+n
-1] &&
1121 nsolve_elim(usage
, cubepos(x
,0,n
), cr
1122 #ifdef STANDALONE_SOLVER
1123 , "positional elimination," " column %d", 1+x
1126 diff
= max(diff
, DIFF_SIMPLE
);
1131 * Numeric elimination.
1133 for (x
= 0; x
< cr
; x
++)
1134 for (y
= 0; y
< cr
; y
++)
1135 if (!usage
->grid
[YUNTRANS(y
)*cr
+x
] &&
1136 nsolve_elim(usage
, cubepos(x
,y
,1), 1
1137 #ifdef STANDALONE_SOLVER
1138 , "numeric elimination at (%d,%d)", 1+x
,
1142 diff
= max(diff
, DIFF_SIMPLE
);
1147 * Intersectional analysis, rows vs blocks.
1149 for (y
= 0; y
< cr
; y
++)
1150 for (x
= 0; x
< cr
; x
+= r
)
1151 for (n
= 1; n
<= cr
; n
++)
1152 if (!usage
->row
[y
*cr
+n
-1] &&
1153 !usage
->blk
[((y
%r
)*c
+(x
/r
))*cr
+n
-1] &&
1154 (nsolve_intersect(usage
, cubepos(0,y
,n
), cr
*cr
,
1155 cubepos(x
,y
%r
,n
), r
*cr
1156 #ifdef STANDALONE_SOLVER
1157 , "intersectional analysis,"
1158 " row %d vs block (%d,%d)",
1159 1+YUNTRANS(y
), 1+x
/r
, 1+y
%r
1162 nsolve_intersect(usage
, cubepos(x
,y
%r
,n
), r
*cr
,
1163 cubepos(0,y
,n
), cr
*cr
1164 #ifdef STANDALONE_SOLVER
1165 , "intersectional analysis,"
1166 " block (%d,%d) vs row %d",
1167 1+x
/r
, 1+y
%r
, 1+YUNTRANS(y
)
1170 diff
= max(diff
, DIFF_INTERSECT
);
1175 * Intersectional analysis, columns vs blocks.
1177 for (x
= 0; x
< cr
; x
++)
1178 for (y
= 0; y
< r
; y
++)
1179 for (n
= 1; n
<= cr
; n
++)
1180 if (!usage
->col
[x
*cr
+n
-1] &&
1181 !usage
->blk
[(y
*c
+(x
/r
))*cr
+n
-1] &&
1182 (nsolve_intersect(usage
, cubepos(x
,0,n
), cr
,
1183 cubepos((x
/r
)*r
,y
,n
), r
*cr
1184 #ifdef STANDALONE_SOLVER
1185 , "intersectional analysis,"
1186 " column %d vs block (%d,%d)",
1190 nsolve_intersect(usage
, cubepos((x
/r
)*r
,y
,n
), r
*cr
,
1192 #ifdef STANDALONE_SOLVER
1193 , "intersectional analysis,"
1194 " block (%d,%d) vs column %d",
1198 diff
= max(diff
, DIFF_INTERSECT
);
1203 * Blockwise set elimination.
1205 for (x
= 0; x
< cr
; x
+= r
)
1206 for (y
= 0; y
< r
; y
++)
1207 if (nsolve_set(usage
, cubepos(x
,y
,1), r
*cr
, 1
1208 #ifdef STANDALONE_SOLVER
1209 , "set elimination, block (%d,%d)", 1+x
/r
, 1+y
1212 diff
= max(diff
, DIFF_SET
);
1217 * Row-wise set elimination.
1219 for (y
= 0; y
< cr
; y
++)
1220 if (nsolve_set(usage
, cubepos(0,y
,1), cr
*cr
, 1
1221 #ifdef STANDALONE_SOLVER
1222 , "set elimination, row %d", 1+YUNTRANS(y
)
1225 diff
= max(diff
, DIFF_SET
);
1230 * Column-wise set elimination.
1232 for (x
= 0; x
< cr
; x
++)
1233 if (nsolve_set(usage
, cubepos(x
,0,1), cr
, 1
1234 #ifdef STANDALONE_SOLVER
1235 , "set elimination, column %d", 1+x
1238 diff
= max(diff
, DIFF_SET
);
1243 * If we reach here, we have made no deductions in this
1244 * iteration, so the algorithm terminates.
1255 for (x
= 0; x
< cr
; x
++)
1256 for (y
= 0; y
< cr
; y
++)
1258 return DIFF_IMPOSSIBLE
;
1262 /* ----------------------------------------------------------------------
1263 * End of non-recursive solver code.
1267 * Check whether a grid contains a valid complete puzzle.
1269 static int check_valid(int c
, int r
, digit
*grid
)
1272 unsigned char *used
;
1275 used
= snewn(cr
, unsigned char);
1278 * Check that each row contains precisely one of everything.
1280 for (y
= 0; y
< cr
; y
++) {
1281 memset(used
, FALSE
, cr
);
1282 for (x
= 0; x
< cr
; x
++)
1283 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
1284 used
[grid
[y
*cr
+x
]-1] = TRUE
;
1285 for (n
= 0; n
< cr
; n
++)
1293 * Check that each column contains precisely one of everything.
1295 for (x
= 0; x
< cr
; x
++) {
1296 memset(used
, FALSE
, cr
);
1297 for (y
= 0; y
< cr
; y
++)
1298 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
1299 used
[grid
[y
*cr
+x
]-1] = TRUE
;
1300 for (n
= 0; n
< cr
; n
++)
1308 * Check that each block contains precisely one of everything.
1310 for (x
= 0; x
< cr
; x
+= r
) {
1311 for (y
= 0; y
< cr
; y
+= c
) {
1313 memset(used
, FALSE
, cr
);
1314 for (xx
= x
; xx
< x
+r
; xx
++)
1315 for (yy
= 0; yy
< y
+c
; yy
++)
1316 if (grid
[yy
*cr
+xx
] > 0 && grid
[yy
*cr
+xx
] <= cr
)
1317 used
[grid
[yy
*cr
+xx
]-1] = TRUE
;
1318 for (n
= 0; n
< cr
; n
++)
1330 static void symmetry_limit(game_params
*params
, int *xlim
, int *ylim
, int s
)
1332 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1344 *xlim
= *ylim
= (cr
+1) / 2;
1349 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
1351 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1360 break; /* just x,y is all we need */
1365 *output
++ = cr
- 1 - x
;
1370 *output
++ = cr
- 1 - y
;
1374 *output
++ = cr
- 1 - y
;
1379 *output
++ = cr
- 1 - x
;
1385 *output
++ = cr
- 1 - x
;
1386 *output
++ = cr
- 1 - y
;
1394 struct game_aux_info
{
1399 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1400 game_aux_info
**aux
, int interactive
)
1402 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1404 digit
*grid
, *grid2
;
1405 struct xy
{ int x
, y
; } *locs
;
1409 int coords
[16], ncoords
;
1411 int maxdiff
, recursing
;
1414 * Adjust the maximum difficulty level to be consistent with
1415 * the puzzle size: all 2x2 puzzles appear to be Trivial
1416 * (DIFF_BLOCK) so we cannot hold out for even a Basic
1417 * (DIFF_SIMPLE) one.
1419 maxdiff
= params
->diff
;
1420 if (c
== 2 && r
== 2)
1421 maxdiff
= DIFF_BLOCK
;
1423 grid
= snewn(area
, digit
);
1424 locs
= snewn(area
, struct xy
);
1425 grid2
= snewn(area
, digit
);
1428 * Loop until we get a grid of the required difficulty. This is
1429 * nasty, but it seems to be unpleasantly hard to generate
1430 * difficult grids otherwise.
1434 * Start the recursive solver with an empty grid to generate a
1435 * random solved state.
1437 memset(grid
, 0, area
);
1438 ret
= rsolve(c
, r
, grid
, rs
, 1);
1440 assert(check_valid(c
, r
, grid
));
1443 * Save the solved grid in the aux_info.
1446 game_aux_info
*ai
= snew(game_aux_info
);
1449 ai
->grid
= snewn(cr
* cr
, digit
);
1450 memcpy(ai
->grid
, grid
, cr
* cr
* sizeof(digit
));
1455 * Now we have a solved grid, start removing things from it
1456 * while preserving solubility.
1458 symmetry_limit(params
, &xlim
, &ylim
, params
->symm
);
1464 * Iterate over the grid and enumerate all the filled
1465 * squares we could empty.
1469 for (x
= 0; x
< xlim
; x
++)
1470 for (y
= 0; y
< ylim
; y
++)
1478 * Now shuffle that list.
1480 for (i
= nlocs
; i
> 1; i
--) {
1481 int p
= random_upto(rs
, i
);
1483 struct xy t
= locs
[p
];
1484 locs
[p
] = locs
[i
-1];
1490 * Now loop over the shuffled list and, for each element,
1491 * see whether removing that element (and its reflections)
1492 * from the grid will still leave the grid soluble by
1495 for (i
= 0; i
< nlocs
; i
++) {
1501 memcpy(grid2
, grid
, area
);
1502 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
1503 for (j
= 0; j
< ncoords
; j
++)
1504 grid2
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
1507 ret
= (rsolve(c
, r
, grid2
, NULL
, 2) == 1);
1509 ret
= (nsolve(c
, r
, grid2
) <= maxdiff
);
1512 for (j
= 0; j
< ncoords
; j
++)
1513 grid
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
1520 * There was nothing we could remove without
1521 * destroying solvability. If we're trying to
1522 * generate a recursion-only grid and haven't
1523 * switched over to rsolve yet, we now do;
1524 * otherwise we give up.
1526 if (maxdiff
== DIFF_RECURSIVE
&& !recursing
) {
1534 memcpy(grid2
, grid
, area
);
1535 } while (nsolve(c
, r
, grid2
) < maxdiff
);
1541 * Now we have the grid as it will be presented to the user.
1542 * Encode it in a game desc.
1548 desc
= snewn(5 * area
, char);
1551 for (i
= 0; i
<= area
; i
++) {
1552 int n
= (i
< area ? grid
[i
] : -1);
1559 int c
= 'a' - 1 + run
;
1563 run
-= c
- ('a' - 1);
1567 * If there's a number in the very top left or
1568 * bottom right, there's no point putting an
1569 * unnecessary _ before or after it.
1571 if (p
> desc
&& n
> 0)
1575 p
+= sprintf(p
, "%d", n
);
1579 assert(p
- desc
< 5 * area
);
1581 desc
= sresize(desc
, p
- desc
, char);
1589 static void game_free_aux_info(game_aux_info
*aux
)
1595 static char *validate_desc(game_params
*params
, char *desc
)
1597 int area
= params
->r
* params
->r
* params
->c
* params
->c
;
1602 if (n
>= 'a' && n
<= 'z') {
1603 squares
+= n
- 'a' + 1;
1604 } else if (n
== '_') {
1606 } else if (n
> '0' && n
<= '9') {
1608 while (*desc
>= '0' && *desc
<= '9')
1611 return "Invalid character in game description";
1615 return "Not enough data to fill grid";
1618 return "Too much data to fit in grid";
1623 static game_state
*new_game(midend_data
*me
, game_params
*params
, char *desc
)
1625 game_state
*state
= snew(game_state
);
1626 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
1629 state
->c
= params
->c
;
1630 state
->r
= params
->r
;
1632 state
->grid
= snewn(area
, digit
);
1633 state
->pencil
= snewn(area
* cr
, unsigned char);
1634 memset(state
->pencil
, 0, area
* cr
);
1635 state
->immutable
= snewn(area
, unsigned char);
1636 memset(state
->immutable
, FALSE
, area
);
1638 state
->completed
= state
->cheated
= FALSE
;
1643 if (n
>= 'a' && n
<= 'z') {
1644 int run
= n
- 'a' + 1;
1645 assert(i
+ run
<= area
);
1647 state
->grid
[i
++] = 0;
1648 } else if (n
== '_') {
1650 } else if (n
> '0' && n
<= '9') {
1652 state
->immutable
[i
] = TRUE
;
1653 state
->grid
[i
++] = atoi(desc
-1);
1654 while (*desc
>= '0' && *desc
<= '9')
1657 assert(!"We can't get here");
1665 static game_state
*dup_game(game_state
*state
)
1667 game_state
*ret
= snew(game_state
);
1668 int c
= state
->c
, r
= state
->r
, cr
= c
*r
, area
= cr
* cr
;
1673 ret
->grid
= snewn(area
, digit
);
1674 memcpy(ret
->grid
, state
->grid
, area
);
1676 ret
->pencil
= snewn(area
* cr
, unsigned char);
1677 memcpy(ret
->pencil
, state
->pencil
, area
* cr
);
1679 ret
->immutable
= snewn(area
, unsigned char);
1680 memcpy(ret
->immutable
, state
->immutable
, area
);
1682 ret
->completed
= state
->completed
;
1683 ret
->cheated
= state
->cheated
;
1688 static void free_game(game_state
*state
)
1690 sfree(state
->immutable
);
1691 sfree(state
->pencil
);
1696 static game_state
*solve_game(game_state
*state
, game_aux_info
*ai
,
1700 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1703 ret
= dup_game(state
);
1704 ret
->completed
= ret
->cheated
= TRUE
;
1707 * If we already have the solution in the aux_info, save
1708 * ourselves some time.
1714 memcpy(ret
->grid
, ai
->grid
, cr
* cr
* sizeof(digit
));
1717 rsolve_ret
= rsolve(c
, r
, ret
->grid
, NULL
, 2);
1719 if (rsolve_ret
!= 1) {
1721 if (rsolve_ret
== 0)
1722 *error
= "No solution exists for this puzzle";
1724 *error
= "Multiple solutions exist for this puzzle";
1732 static char *grid_text_format(int c
, int r
, digit
*grid
)
1740 * There are cr lines of digits, plus r-1 lines of block
1741 * separators. Each line contains cr digits, cr-1 separating
1742 * spaces, and c-1 two-character block separators. Thus, the
1743 * total length of a line is 2*cr+2*c-3 (not counting the
1744 * newline), and there are cr+r-1 of them.
1746 maxlen
= (cr
+r
-1) * (2*cr
+2*c
-2);
1747 ret
= snewn(maxlen
+1, char);
1750 for (y
= 0; y
< cr
; y
++) {
1751 for (x
= 0; x
< cr
; x
++) {
1752 int ch
= grid
[y
* cr
+ x
];
1762 if ((x
+1) % r
== 0) {
1769 if (y
+1 < cr
&& (y
+1) % c
== 0) {
1770 for (x
= 0; x
< cr
; x
++) {
1774 if ((x
+1) % r
== 0) {
1784 assert(p
- ret
== maxlen
);
1789 static char *game_text_format(game_state
*state
)
1791 return grid_text_format(state
->c
, state
->r
, state
->grid
);
1796 * These are the coordinates of the currently highlighted
1797 * square on the grid, or -1,-1 if there isn't one. When there
1798 * is, pressing a valid number or letter key or Space will
1799 * enter that number or letter in the grid.
1803 * This indicates whether the current highlight is a
1804 * pencil-mark one or a real one.
1809 static game_ui
*new_ui(game_state
*state
)
1811 game_ui
*ui
= snew(game_ui
);
1813 ui
->hx
= ui
->hy
= -1;
1819 static void free_ui(game_ui
*ui
)
1824 static game_state
*make_move(game_state
*from
, game_ui
*ui
, game_drawstate
*ds
,
1825 int x
, int y
, int button
)
1827 int c
= from
->c
, r
= from
->r
, cr
= c
*r
;
1831 button
&= ~MOD_MASK
;
1833 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
1834 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
1836 if (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
) {
1837 if (button
== LEFT_BUTTON
) {
1838 if (from
->immutable
[ty
*cr
+tx
]) {
1839 ui
->hx
= ui
->hy
= -1;
1840 } else if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
== 0) {
1841 ui
->hx
= ui
->hy
= -1;
1847 return from
; /* UI activity occurred */
1849 if (button
== RIGHT_BUTTON
) {
1851 * Pencil-mode highlighting for non filled squares.
1853 if (from
->grid
[ty
*cr
+tx
] == 0) {
1854 if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
) {
1855 ui
->hx
= ui
->hy
= -1;
1862 ui
->hx
= ui
->hy
= -1;
1864 return from
; /* UI activity occurred */
1868 if (ui
->hx
!= -1 && ui
->hy
!= -1 &&
1869 ((button
>= '1' && button
<= '9' && button
- '0' <= cr
) ||
1870 (button
>= 'a' && button
<= 'z' && button
- 'a' + 10 <= cr
) ||
1871 (button
>= 'A' && button
<= 'Z' && button
- 'A' + 10 <= cr
) ||
1873 int n
= button
- '0';
1874 if (button
>= 'A' && button
<= 'Z')
1875 n
= button
- 'A' + 10;
1876 if (button
>= 'a' && button
<= 'z')
1877 n
= button
- 'a' + 10;
1882 * Can't overwrite this square. In principle this shouldn't
1883 * happen anyway because we should never have even been
1884 * able to highlight the square, but it never hurts to be
1887 if (from
->immutable
[ui
->hy
*cr
+ui
->hx
])
1891 * Can't make pencil marks in a filled square. In principle
1892 * this shouldn't happen anyway because we should never
1893 * have even been able to pencil-highlight the square, but
1894 * it never hurts to be careful.
1896 if (ui
->hpencil
&& from
->grid
[ui
->hy
*cr
+ui
->hx
])
1899 ret
= dup_game(from
);
1900 if (ui
->hpencil
&& n
> 0) {
1901 int index
= (ui
->hy
*cr
+ui
->hx
) * cr
+ (n
-1);
1902 ret
->pencil
[index
] = !ret
->pencil
[index
];
1904 ret
->grid
[ui
->hy
*cr
+ui
->hx
] = n
;
1905 memset(ret
->pencil
+ (ui
->hy
*cr
+ui
->hx
)*cr
, 0, cr
);
1908 * We've made a real change to the grid. Check to see
1909 * if the game has been completed.
1911 if (!ret
->completed
&& check_valid(c
, r
, ret
->grid
)) {
1912 ret
->completed
= TRUE
;
1915 ui
->hx
= ui
->hy
= -1;
1917 return ret
; /* made a valid move */
1923 /* ----------------------------------------------------------------------
1927 struct game_drawstate
{
1931 unsigned char *pencil
;
1935 #define XSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1936 #define YSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1938 static void game_size(game_params
*params
, int *x
, int *y
)
1940 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1946 static float *game_colours(frontend
*fe
, game_state
*state
, int *ncolours
)
1948 float *ret
= snewn(3 * NCOLOURS
, float);
1950 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
1952 ret
[COL_GRID
* 3 + 0] = 0.0F
;
1953 ret
[COL_GRID
* 3 + 1] = 0.0F
;
1954 ret
[COL_GRID
* 3 + 2] = 0.0F
;
1956 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
1957 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
1958 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
1960 ret
[COL_USER
* 3 + 0] = 0.0F
;
1961 ret
[COL_USER
* 3 + 1] = 0.6F
* ret
[COL_BACKGROUND
* 3 + 1];
1962 ret
[COL_USER
* 3 + 2] = 0.0F
;
1964 ret
[COL_HIGHLIGHT
* 3 + 0] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 0];
1965 ret
[COL_HIGHLIGHT
* 3 + 1] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 1];
1966 ret
[COL_HIGHLIGHT
* 3 + 2] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 2];
1968 ret
[COL_PENCIL
* 3 + 0] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 0];
1969 ret
[COL_PENCIL
* 3 + 1] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 1];
1970 ret
[COL_PENCIL
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2];
1972 *ncolours
= NCOLOURS
;
1976 static game_drawstate
*game_new_drawstate(game_state
*state
)
1978 struct game_drawstate
*ds
= snew(struct game_drawstate
);
1979 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1981 ds
->started
= FALSE
;
1985 ds
->grid
= snewn(cr
*cr
, digit
);
1986 memset(ds
->grid
, 0, cr
*cr
);
1987 ds
->pencil
= snewn(cr
*cr
*cr
, digit
);
1988 memset(ds
->pencil
, 0, cr
*cr
*cr
);
1989 ds
->hl
= snewn(cr
*cr
, unsigned char);
1990 memset(ds
->hl
, 0, cr
*cr
);
1995 static void game_free_drawstate(game_drawstate
*ds
)
2003 static void draw_number(frontend
*fe
, game_drawstate
*ds
, game_state
*state
,
2004 int x
, int y
, int hl
)
2006 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
2011 if (ds
->grid
[y
*cr
+x
] == state
->grid
[y
*cr
+x
] &&
2012 ds
->hl
[y
*cr
+x
] == hl
&&
2013 !memcmp(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
))
2014 return; /* no change required */
2016 tx
= BORDER
+ x
* TILE_SIZE
+ 2;
2017 ty
= BORDER
+ y
* TILE_SIZE
+ 2;
2033 clip(fe
, cx
, cy
, cw
, ch
);
2035 /* background needs erasing */
2036 draw_rect(fe
, cx
, cy
, cw
, ch
, hl
== 1 ? COL_HIGHLIGHT
: COL_BACKGROUND
);
2038 /* pencil-mode highlight */
2043 coords
[2] = cx
+cw
/2;
2046 coords
[5] = cy
+ch
/2;
2047 draw_polygon(fe
, coords
, 3, TRUE
, COL_HIGHLIGHT
);
2050 /* new number needs drawing? */
2051 if (state
->grid
[y
*cr
+x
]) {
2053 str
[0] = state
->grid
[y
*cr
+x
] + '0';
2055 str
[0] += 'a' - ('9'+1);
2056 draw_text(fe
, tx
+ TILE_SIZE
/2, ty
+ TILE_SIZE
/2,
2057 FONT_VARIABLE
, TILE_SIZE
/2, ALIGN_VCENTRE
| ALIGN_HCENTRE
,
2058 state
->immutable
[y
*cr
+x
] ? COL_CLUE
: COL_USER
, str
);
2060 /* pencil marks required? */
2063 for (i
= j
= 0; i
< cr
; i
++)
2064 if (state
->pencil
[(y
*cr
+x
)*cr
+i
]) {
2065 int dx
= j
% r
, dy
= j
/ r
, crm
= max(c
, r
);
2069 str
[0] += 'a' - ('9'+1);
2070 draw_text(fe
, tx
+ (4*dx
+3) * TILE_SIZE
/ (4*r
+2),
2071 ty
+ (4*dy
+3) * TILE_SIZE
/ (4*c
+2),
2072 FONT_VARIABLE
, TILE_SIZE
/(crm
*5/4),
2073 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_PENCIL
, str
);
2080 draw_update(fe
, cx
, cy
, cw
, ch
);
2082 ds
->grid
[y
*cr
+x
] = state
->grid
[y
*cr
+x
];
2083 memcpy(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
);
2084 ds
->hl
[y
*cr
+x
] = hl
;
2087 static void game_redraw(frontend
*fe
, game_drawstate
*ds
, game_state
*oldstate
,
2088 game_state
*state
, int dir
, game_ui
*ui
,
2089 float animtime
, float flashtime
)
2091 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
2096 * The initial contents of the window are not guaranteed
2097 * and can vary with front ends. To be on the safe side,
2098 * all games should start by drawing a big
2099 * background-colour rectangle covering the whole window.
2101 draw_rect(fe
, 0, 0, XSIZE(cr
), YSIZE(cr
), COL_BACKGROUND
);
2106 for (x
= 0; x
<= cr
; x
++) {
2107 int thick
= (x
% r ?
0 : 1);
2108 draw_rect(fe
, BORDER
+ x
*TILE_SIZE
- thick
, BORDER
-1,
2109 1+2*thick
, cr
*TILE_SIZE
+3, COL_GRID
);
2111 for (y
= 0; y
<= cr
; y
++) {
2112 int thick
= (y
% c ?
0 : 1);
2113 draw_rect(fe
, BORDER
-1, BORDER
+ y
*TILE_SIZE
- thick
,
2114 cr
*TILE_SIZE
+3, 1+2*thick
, COL_GRID
);
2119 * Draw any numbers which need redrawing.
2121 for (x
= 0; x
< cr
; x
++) {
2122 for (y
= 0; y
< cr
; y
++) {
2124 if (flashtime
> 0 &&
2125 (flashtime
<= FLASH_TIME
/3 ||
2126 flashtime
>= FLASH_TIME
*2/3))
2128 if (x
== ui
->hx
&& y
== ui
->hy
)
2129 highlight
= ui
->hpencil ?
2 : 1;
2130 draw_number(fe
, ds
, state
, x
, y
, highlight
);
2135 * Update the _entire_ grid if necessary.
2138 draw_update(fe
, 0, 0, XSIZE(cr
), YSIZE(cr
));
2143 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
2144 int dir
, game_ui
*ui
)
2149 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
2150 int dir
, game_ui
*ui
)
2152 if (!oldstate
->completed
&& newstate
->completed
&&
2153 !oldstate
->cheated
&& !newstate
->cheated
)
2158 static int game_wants_statusbar(void)
2163 static int game_timing_state(game_state
*state
)
2169 #define thegame solo
2172 const struct game thegame
= {
2173 "Solo", "games.solo",
2180 TRUE
, game_configure
, custom_params
,
2189 TRUE
, game_text_format
,
2196 game_free_drawstate
,
2200 game_wants_statusbar
,
2201 FALSE
, game_timing_state
,
2202 0, /* mouse_priorities */
2205 #ifdef STANDALONE_SOLVER
2208 * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2211 void frontend_default_colour(frontend
*fe
, float *output
) {}
2212 void draw_text(frontend
*fe
, int x
, int y
, int fonttype
, int fontsize
,
2213 int align
, int colour
, char *text
) {}
2214 void draw_rect(frontend
*fe
, int x
, int y
, int w
, int h
, int colour
) {}
2215 void draw_line(frontend
*fe
, int x1
, int y1
, int x2
, int y2
, int colour
) {}
2216 void draw_polygon(frontend
*fe
, int *coords
, int npoints
,
2217 int fill
, int colour
) {}
2218 void clip(frontend
*fe
, int x
, int y
, int w
, int h
) {}
2219 void unclip(frontend
*fe
) {}
2220 void start_draw(frontend
*fe
) {}
2221 void draw_update(frontend
*fe
, int x
, int y
, int w
, int h
) {}
2222 void end_draw(frontend
*fe
) {}
2223 unsigned long random_bits(random_state
*state
, int bits
)
2224 { assert(!"Shouldn't get randomness"); return 0; }
2225 unsigned long random_upto(random_state
*state
, unsigned long limit
)
2226 { assert(!"Shouldn't get randomness"); return 0; }
2228 void fatal(char *fmt
, ...)
2232 fprintf(stderr
, "fatal error: ");
2235 vfprintf(stderr
, fmt
, ap
);
2238 fprintf(stderr
, "\n");
2242 int main(int argc
, char **argv
)
2247 char *id
= NULL
, *desc
, *err
;
2251 while (--argc
> 0) {
2253 if (!strcmp(p
, "-r")) {
2255 } else if (!strcmp(p
, "-n")) {
2257 } else if (!strcmp(p
, "-v")) {
2258 solver_show_working
= TRUE
;
2260 } else if (!strcmp(p
, "-g")) {
2263 } else if (*p
== '-') {
2264 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0]);
2272 fprintf(stderr
, "usage: %s [-n | -r | -g | -v] <game_id>\n", argv
[0]);
2276 desc
= strchr(id
, ':');
2278 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
2283 p
= default_params();
2284 decode_params(p
, id
);
2285 err
= validate_desc(p
, desc
);
2287 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
2290 s
= new_game(NULL
, p
, desc
);
2293 int ret
= rsolve(p
->c
, p
->r
, s
->grid
, NULL
, 2);
2295 fprintf(stderr
, "%s: rsolve: multiple solutions detected\n",
2299 int ret
= nsolve(p
->c
, p
->r
, s
->grid
);
2301 if (ret
== DIFF_IMPOSSIBLE
) {
2303 * Now resort to rsolve to determine whether it's
2306 ret
= rsolve(p
->c
, p
->r
, s
->grid
, NULL
, 2);
2308 ret
= DIFF_IMPOSSIBLE
;
2310 ret
= DIFF_RECURSIVE
;
2312 ret
= DIFF_AMBIGUOUS
;
2314 printf("Difficulty rating: %s\n",
2315 ret
==DIFF_BLOCK ?
"Trivial (blockwise positional elimination only)":
2316 ret
==DIFF_SIMPLE ?
"Basic (row/column/number elimination required)":
2317 ret
==DIFF_INTERSECT ?
"Intermediate (intersectional analysis required)":
2318 ret
==DIFF_SET ?
"Advanced (set elimination required)":
2319 ret
==DIFF_RECURSIVE ?
"Unreasonable (guesswork and backtracking required)":
2320 ret
==DIFF_AMBIGUOUS ?
"Ambiguous (multiple solutions exist)":
2321 ret
==DIFF_IMPOSSIBLE ?
"Impossible (no solution exists)":
2322 "INTERNAL ERROR: unrecognised difficulty code");
2326 printf("%s\n", grid_text_format(p
->c
, p
->r
, s
->grid
));