2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - it might still be nice to do some prioritisation on the
7 * removal of numbers from the grid
8 * + one possibility is to try to minimise the maximum number
9 * of filled squares in any block, which in particular ought
10 * to enforce never leaving a completely filled block in the
11 * puzzle as presented.
13 * - alternative interface modes
14 * + sudoku.com's Windows program has a palette of possible
15 * entries; you select a palette entry first and then click
16 * on the square you want it to go in, thus enabling
17 * mouse-only play. Useful for PDAs! I don't think it's
18 * actually incompatible with the current highlight-then-type
19 * approach: you _either_ highlight a palette entry and then
20 * click, _or_ you highlight a square and then type. At most
21 * one thing is ever highlighted at a time, so there's no way
23 * + `pencil marks' might be useful for more subtle forms of
24 * deduction, now we can create puzzles that require them.
28 * Solo puzzles need to be square overall (since each row and each
29 * column must contain one of every digit), but they need not be
30 * subdivided the same way internally. I am going to adopt a
31 * convention whereby I _always_ refer to `r' as the number of rows
32 * of _big_ divisions, and `c' as the number of columns of _big_
33 * divisions. Thus, a 2c by 3r puzzle looks something like this:
37 * ------+------ (Of course, you can't subdivide it the other way
38 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
39 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
40 * ------+------ box down on the left-hand side.)
44 * The need for a strong naming convention should now be clear:
45 * each small box is two rows of digits by three columns, while the
46 * overall puzzle has three rows of small boxes by two columns. So
47 * I will (hopefully) consistently use `r' to denote the number of
48 * rows _of small boxes_ (here 3), which is also the number of
49 * columns of digits in each small box; and `c' vice versa (here
52 * I'm also going to choose arbitrarily to list c first wherever
53 * possible: the above is a 2x3 puzzle, not a 3x2 one.
63 #ifdef STANDALONE_SOLVER
65 int solver_show_working
;
70 #define max(x,y) ((x)>(y)?(x):(y))
73 * To save space, I store digits internally as unsigned char. This
74 * imposes a hard limit of 255 on the order of the puzzle. Since
75 * even a 5x5 takes unacceptably long to generate, I don't see this
76 * as a serious limitation unless something _really_ impressive
77 * happens in computing technology; but here's a typedef anyway for
78 * general good practice.
80 typedef unsigned char digit
;
86 #define FLASH_TIME 0.4F
88 enum { SYMM_NONE
, SYMM_ROT2
, SYMM_ROT4
, SYMM_REF4
};
90 enum { DIFF_BLOCK
, DIFF_SIMPLE
, DIFF_INTERSECT
,
91 DIFF_SET
, DIFF_RECURSIVE
, DIFF_AMBIGUOUS
, DIFF_IMPOSSIBLE
};
103 int c
, r
, symm
, diff
;
109 unsigned char *immutable
; /* marks which digits are clues */
110 int completed
, cheated
;
113 static game_params
*default_params(void)
115 game_params
*ret
= snew(game_params
);
118 ret
->symm
= SYMM_ROT2
; /* a plausible default */
119 ret
->diff
= DIFF_BLOCK
; /* so is this */
124 static void free_params(game_params
*params
)
129 static game_params
*dup_params(game_params
*params
)
131 game_params
*ret
= snew(game_params
);
132 *ret
= *params
; /* structure copy */
136 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
142 { "2x2 Trivial", { 2, 2, SYMM_ROT2
, DIFF_BLOCK
} },
143 { "2x3 Basic", { 2, 3, SYMM_ROT2
, DIFF_SIMPLE
} },
144 { "3x3 Trivial", { 3, 3, SYMM_ROT2
, DIFF_BLOCK
} },
145 { "3x3 Basic", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
} },
146 { "3x3 Intermediate", { 3, 3, SYMM_ROT2
, DIFF_INTERSECT
} },
147 { "3x3 Advanced", { 3, 3, SYMM_ROT2
, DIFF_SET
} },
148 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2
, DIFF_RECURSIVE
} },
149 { "3x4 Basic", { 3, 4, SYMM_ROT2
, DIFF_SIMPLE
} },
150 { "4x4 Basic", { 4, 4, SYMM_ROT2
, DIFF_SIMPLE
} },
153 if (i
< 0 || i
>= lenof(presets
))
156 *name
= dupstr(presets
[i
].title
);
157 *params
= dup_params(&presets
[i
].params
);
162 static game_params
*decode_params(char const *string
)
164 game_params
*ret
= default_params();
166 ret
->c
= ret
->r
= atoi(string
);
167 ret
->symm
= SYMM_ROT2
;
168 ret
->diff
= DIFF_BLOCK
;
169 while (*string
&& isdigit((unsigned char)*string
)) string
++;
170 if (*string
== 'x') {
172 ret
->r
= atoi(string
);
173 while (*string
&& isdigit((unsigned char)*string
)) string
++;
176 if (*string
== 'r' || *string
== 'm' || *string
== 'a') {
180 while (*string
&& isdigit((unsigned char)*string
)) string
++;
181 if (sc
== 'm' && sn
== 4)
182 ret
->symm
= SYMM_REF4
;
183 if (sc
== 'r' && sn
== 4)
184 ret
->symm
= SYMM_ROT4
;
185 if (sc
== 'r' && sn
== 2)
186 ret
->symm
= SYMM_ROT2
;
188 ret
->symm
= SYMM_NONE
;
189 } else if (*string
== 'd') {
191 if (*string
== 't') /* trivial */
192 string
++, ret
->diff
= DIFF_BLOCK
;
193 else if (*string
== 'b') /* basic */
194 string
++, ret
->diff
= DIFF_SIMPLE
;
195 else if (*string
== 'i') /* intermediate */
196 string
++, ret
->diff
= DIFF_INTERSECT
;
197 else if (*string
== 'a') /* advanced */
198 string
++, ret
->diff
= DIFF_SET
;
199 else if (*string
== 'u') /* unreasonable */
200 string
++, ret
->diff
= DIFF_RECURSIVE
;
202 string
++; /* eat unknown character */
208 static char *encode_params(game_params
*params
)
213 * Symmetry is a game generation preference and hence is left
214 * out of the encoding. Users can add it back in as they see
217 sprintf(str
, "%dx%d", params
->c
, params
->r
);
221 static config_item
*game_configure(game_params
*params
)
226 ret
= snewn(5, config_item
);
228 ret
[0].name
= "Columns of sub-blocks";
229 ret
[0].type
= C_STRING
;
230 sprintf(buf
, "%d", params
->c
);
231 ret
[0].sval
= dupstr(buf
);
234 ret
[1].name
= "Rows of sub-blocks";
235 ret
[1].type
= C_STRING
;
236 sprintf(buf
, "%d", params
->r
);
237 ret
[1].sval
= dupstr(buf
);
240 ret
[2].name
= "Symmetry";
241 ret
[2].type
= C_CHOICES
;
242 ret
[2].sval
= ":None:2-way rotation:4-way rotation:4-way mirror";
243 ret
[2].ival
= params
->symm
;
245 ret
[3].name
= "Difficulty";
246 ret
[3].type
= C_CHOICES
;
247 ret
[3].sval
= ":Trivial:Basic:Intermediate:Advanced:Unreasonable";
248 ret
[3].ival
= params
->diff
;
258 static game_params
*custom_params(config_item
*cfg
)
260 game_params
*ret
= snew(game_params
);
262 ret
->c
= atoi(cfg
[0].sval
);
263 ret
->r
= atoi(cfg
[1].sval
);
264 ret
->symm
= cfg
[2].ival
;
265 ret
->diff
= cfg
[3].ival
;
270 static char *validate_params(game_params
*params
)
272 if (params
->c
< 2 || params
->r
< 2)
273 return "Both dimensions must be at least 2";
274 if (params
->c
> ORDER_MAX
|| params
->r
> ORDER_MAX
)
275 return "Dimensions greater than "STR(ORDER_MAX
)" are not supported";
279 /* ----------------------------------------------------------------------
280 * Full recursive Solo solver.
282 * The algorithm for this solver is shamelessly copied from a
283 * Python solver written by Andrew Wilkinson (which is GPLed, but
284 * I've reused only ideas and no code). It mostly just does the
285 * obvious recursive thing: pick an empty square, put one of the
286 * possible digits in it, recurse until all squares are filled,
287 * backtrack and change some choices if necessary.
289 * The clever bit is that every time it chooses which square to
290 * fill in next, it does so by counting the number of _possible_
291 * numbers that can go in each square, and it prioritises so that
292 * it picks a square with the _lowest_ number of possibilities. The
293 * idea is that filling in lots of the obvious bits (particularly
294 * any squares with only one possibility) will cut down on the list
295 * of possibilities for other squares and hence reduce the enormous
296 * search space as much as possible as early as possible.
298 * In practice the algorithm appeared to work very well; run on
299 * sample problems from the Times it completed in well under a
300 * second on my G5 even when written in Python, and given an empty
301 * grid (so that in principle it would enumerate _all_ solved
302 * grids!) it found the first valid solution just as quickly. So
303 * with a bit more randomisation I see no reason not to use this as
308 * Internal data structure used in solver to keep track of
311 struct rsolve_coord
{ int x
, y
, r
; };
312 struct rsolve_usage
{
313 int c
, r
, cr
; /* cr == c*r */
314 /* grid is a copy of the input grid, modified as we go along */
316 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
318 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
320 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
322 /* This lists all the empty spaces remaining in the grid. */
323 struct rsolve_coord
*spaces
;
325 /* If we need randomisation in the solve, this is our random state. */
327 /* Number of solutions so far found, and maximum number we care about. */
332 * The real recursive step in the solving function.
334 static void rsolve_real(struct rsolve_usage
*usage
, digit
*grid
)
336 int c
= usage
->c
, r
= usage
->r
, cr
= usage
->cr
;
337 int i
, j
, n
, sx
, sy
, bestm
, bestr
;
341 * Firstly, check for completion! If there are no spaces left
342 * in the grid, we have a solution.
344 if (usage
->nspaces
== 0) {
347 * This is our first solution, so fill in the output grid.
349 memcpy(grid
, usage
->grid
, cr
* cr
);
356 * Otherwise, there must be at least one space. Find the most
357 * constrained space, using the `r' field as a tie-breaker.
359 bestm
= cr
+1; /* so that any space will beat it */
362 for (j
= 0; j
< usage
->nspaces
; j
++) {
363 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
367 * Find the number of digits that could go in this space.
370 for (n
= 0; n
< cr
; n
++)
371 if (!usage
->row
[y
*cr
+n
] && !usage
->col
[x
*cr
+n
] &&
372 !usage
->blk
[((y
/c
)*c
+(x
/r
))*cr
+n
])
375 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
377 bestr
= usage
->spaces
[j
].r
;
385 * Swap that square into the final place in the spaces array,
386 * so that decrementing nspaces will remove it from the list.
388 if (i
!= usage
->nspaces
-1) {
389 struct rsolve_coord t
;
390 t
= usage
->spaces
[usage
->nspaces
-1];
391 usage
->spaces
[usage
->nspaces
-1] = usage
->spaces
[i
];
392 usage
->spaces
[i
] = t
;
396 * Now we've decided which square to start our recursion at,
397 * simply go through all possible values, shuffling them
398 * randomly first if necessary.
400 digits
= snewn(bestm
, int);
402 for (n
= 0; n
< cr
; n
++)
403 if (!usage
->row
[sy
*cr
+n
] && !usage
->col
[sx
*cr
+n
] &&
404 !usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
]) {
410 for (i
= j
; i
> 1; i
--) {
411 int p
= random_upto(usage
->rs
, i
);
414 digits
[p
] = digits
[i
-1];
420 /* And finally, go through the digit list and actually recurse. */
421 for (i
= 0; i
< j
; i
++) {
424 /* Update the usage structure to reflect the placing of this digit. */
425 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
426 usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
-1] = TRUE
;
427 usage
->grid
[sy
*cr
+sx
] = n
;
430 /* Call the solver recursively. */
431 rsolve_real(usage
, grid
);
434 * If we have seen as many solutions as we need, terminate
435 * all processing immediately.
437 if (usage
->solns
>= usage
->maxsolns
)
440 /* Revert the usage structure. */
441 usage
->row
[sy
*cr
+n
-1] = usage
->col
[sx
*cr
+n
-1] =
442 usage
->blk
[((sy
/c
)*c
+(sx
/r
))*cr
+n
-1] = FALSE
;
443 usage
->grid
[sy
*cr
+sx
] = 0;
451 * Entry point to solver. You give it dimensions and a starting
452 * grid, which is simply an array of N^4 digits. In that array, 0
453 * means an empty square, and 1..N mean a clue square.
455 * Return value is the number of solutions found; searching will
456 * stop after the provided `max'. (Thus, you can pass max==1 to
457 * indicate that you only care about finding _one_ solution, or
458 * max==2 to indicate that you want to know the difference between
459 * a unique and non-unique solution.) The input parameter `grid' is
460 * also filled in with the _first_ (or only) solution found by the
463 static int rsolve(int c
, int r
, digit
*grid
, random_state
*rs
, int max
)
465 struct rsolve_usage
*usage
;
470 * Create an rsolve_usage structure.
472 usage
= snew(struct rsolve_usage
);
478 usage
->grid
= snewn(cr
* cr
, digit
);
479 memcpy(usage
->grid
, grid
, cr
* cr
);
481 usage
->row
= snewn(cr
* cr
, unsigned char);
482 usage
->col
= snewn(cr
* cr
, unsigned char);
483 usage
->blk
= snewn(cr
* cr
, unsigned char);
484 memset(usage
->row
, FALSE
, cr
* cr
);
485 memset(usage
->col
, FALSE
, cr
* cr
);
486 memset(usage
->blk
, FALSE
, cr
* cr
);
488 usage
->spaces
= snewn(cr
* cr
, struct rsolve_coord
);
492 usage
->maxsolns
= max
;
497 * Now fill it in with data from the input grid.
499 for (y
= 0; y
< cr
; y
++) {
500 for (x
= 0; x
< cr
; x
++) {
501 int v
= grid
[y
*cr
+x
];
503 usage
->spaces
[usage
->nspaces
].x
= x
;
504 usage
->spaces
[usage
->nspaces
].y
= y
;
506 usage
->spaces
[usage
->nspaces
].r
= random_bits(rs
, 31);
508 usage
->spaces
[usage
->nspaces
].r
= usage
->nspaces
;
511 usage
->row
[y
*cr
+v
-1] = TRUE
;
512 usage
->col
[x
*cr
+v
-1] = TRUE
;
513 usage
->blk
[((y
/c
)*c
+(x
/r
))*cr
+v
-1] = TRUE
;
519 * Run the real recursive solving function.
521 rsolve_real(usage
, grid
);
525 * Clean up the usage structure now we have our answer.
527 sfree(usage
->spaces
);
540 /* ----------------------------------------------------------------------
541 * End of recursive solver code.
544 /* ----------------------------------------------------------------------
545 * Less capable non-recursive solver. This one is used to check
546 * solubility of a grid as we gradually remove numbers from it: by
547 * verifying a grid using this solver we can ensure it isn't _too_
548 * hard (e.g. does not actually require guessing and backtracking).
550 * It supports a variety of specific modes of reasoning. By
551 * enabling or disabling subsets of these modes we can arrange a
552 * range of difficulty levels.
556 * Modes of reasoning currently supported:
558 * - Positional elimination: a number must go in a particular
559 * square because all the other empty squares in a given
560 * row/col/blk are ruled out.
562 * - Numeric elimination: a square must have a particular number
563 * in because all the other numbers that could go in it are
566 * - Intersectional analysis: given two domains which overlap
567 * (hence one must be a block, and the other can be a row or
568 * col), if the possible locations for a particular number in
569 * one of the domains can be narrowed down to the overlap, then
570 * that number can be ruled out everywhere but the overlap in
571 * the other domain too.
573 * - Set elimination: if there is a subset of the empty squares
574 * within a domain such that the union of the possible numbers
575 * in that subset has the same size as the subset itself, then
576 * those numbers can be ruled out everywhere else in the domain.
577 * (For example, if there are five empty squares and the
578 * possible numbers in each are 12, 23, 13, 134 and 1345, then
579 * the first three empty squares form such a subset: the numbers
580 * 1, 2 and 3 _must_ be in those three squares in some
581 * permutation, and hence we can deduce none of them can be in
582 * the fourth or fifth squares.)
583 * + You can also see this the other way round, concentrating
584 * on numbers rather than squares: if there is a subset of
585 * the unplaced numbers within a domain such that the union
586 * of all their possible positions has the same size as the
587 * subset itself, then all other numbers can be ruled out for
588 * those positions. However, it turns out that this is
589 * exactly equivalent to the first formulation at all times:
590 * there is a 1-1 correspondence between suitable subsets of
591 * the unplaced numbers and suitable subsets of the unfilled
592 * places, found by taking the _complement_ of the union of
593 * the numbers' possible positions (or the spaces' possible
598 * Within this solver, I'm going to transform all y-coordinates by
599 * inverting the significance of the block number and the position
600 * within the block. That is, we will start with the top row of
601 * each block in order, then the second row of each block in order,
604 * This transformation has the enormous advantage that it means
605 * every row, column _and_ block is described by an arithmetic
606 * progression of coordinates within the cubic array, so that I can
607 * use the same very simple function to do blockwise, row-wise and
608 * column-wise elimination.
610 #define YTRANS(y) (((y)%c)*r+(y)/c)
611 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
613 struct nsolve_usage
{
616 * We set up a cubic array, indexed by x, y and digit; each
617 * element of this array is TRUE or FALSE according to whether
618 * or not that digit _could_ in principle go in that position.
620 * The way to index this array is cube[(x*cr+y)*cr+n-1].
621 * y-coordinates in here are transformed.
625 * This is the grid in which we write down our final
626 * deductions. y-coordinates in here are _not_ transformed.
630 * Now we keep track, at a slightly higher level, of what we
631 * have yet to work out, to prevent doing the same deduction
634 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
636 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
638 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
641 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
642 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
645 * Function called when we are certain that a particular square has
646 * a particular number in it. The y-coordinate passed in here is
649 static void nsolve_place(struct nsolve_usage
*usage
, int x
, int y
, int n
)
651 int c
= usage
->c
, r
= usage
->r
, cr
= usage
->cr
;
657 * Rule out all other numbers in this square.
659 for (i
= 1; i
<= cr
; i
++)
664 * Rule out this number in all other positions in the row.
666 for (i
= 0; i
< cr
; i
++)
671 * Rule out this number in all other positions in the column.
673 for (i
= 0; i
< cr
; i
++)
678 * Rule out this number in all other positions in the block.
682 for (i
= 0; i
< r
; i
++)
683 for (j
= 0; j
< c
; j
++)
684 if (bx
+i
!= x
|| by
+j
*r
!= y
)
685 cube(bx
+i
,by
+j
*r
,n
) = FALSE
;
688 * Enter the number in the result grid.
690 usage
->grid
[YUNTRANS(y
)*cr
+x
] = n
;
693 * Cross out this number from the list of numbers left to place
694 * in its row, its column and its block.
696 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
697 usage
->blk
[((y
%r
)*c
+(x
/r
))*cr
+n
-1] = TRUE
;
700 static int nsolve_elim(struct nsolve_usage
*usage
, int start
, int step
701 #ifdef STANDALONE_SOLVER
706 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
710 * Count the number of set bits within this section of the
715 for (i
= 0; i
< cr
; i
++)
716 if (usage
->cube
[start
+i
*step
]) {
730 if (!usage
->grid
[YUNTRANS(y
)*cr
+x
]) {
731 #ifdef STANDALONE_SOLVER
732 if (solver_show_working
) {
737 printf(":\n placing %d at (%d,%d)\n",
738 n
, 1+x
, 1+YUNTRANS(y
));
741 nsolve_place(usage
, x
, y
, n
);
749 static int nsolve_intersect(struct nsolve_usage
*usage
,
750 int start1
, int step1
, int start2
, int step2
751 #ifdef STANDALONE_SOLVER
756 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
760 * Loop over the first domain and see if there's any set bit
761 * not also in the second.
763 for (i
= 0; i
< cr
; i
++) {
764 int p
= start1
+i
*step1
;
765 if (usage
->cube
[p
] &&
766 !(p
>= start2
&& p
< start2
+cr
*step2
&&
767 (p
- start2
) % step2
== 0))
768 return FALSE
; /* there is, so we can't deduce */
772 * We have determined that all set bits in the first domain are
773 * within its overlap with the second. So loop over the second
774 * domain and remove all set bits that aren't also in that
775 * overlap; return TRUE iff we actually _did_ anything.
778 for (i
= 0; i
< cr
; i
++) {
779 int p
= start2
+i
*step2
;
780 if (usage
->cube
[p
] &&
781 !(p
>= start1
&& p
< start1
+cr
*step1
&& (p
- start1
) % step1
== 0))
783 #ifdef STANDALONE_SOLVER
784 if (solver_show_working
) {
800 printf(" ruling out %d at (%d,%d)\n",
801 pn
, 1+px
, 1+YUNTRANS(py
));
804 ret
= TRUE
; /* we did something */
812 static int nsolve_set(struct nsolve_usage
*usage
,
813 int start
, int step1
, int step2
814 #ifdef STANDALONE_SOLVER
819 int c
= usage
->c
, r
= usage
->r
, cr
= c
*r
;
821 unsigned char *grid
= snewn(cr
*cr
, unsigned char);
822 unsigned char *rowidx
= snewn(cr
, unsigned char);
823 unsigned char *colidx
= snewn(cr
, unsigned char);
824 unsigned char *set
= snewn(cr
, unsigned char);
827 * We are passed a cr-by-cr matrix of booleans. Our first job
828 * is to winnow it by finding any definite placements - i.e.
829 * any row with a solitary 1 - and discarding that row and the
830 * column containing the 1.
832 memset(rowidx
, TRUE
, cr
);
833 memset(colidx
, TRUE
, cr
);
834 for (i
= 0; i
< cr
; i
++) {
835 int count
= 0, first
= -1;
836 for (j
= 0; j
< cr
; j
++)
837 if (usage
->cube
[start
+i
*step1
+j
*step2
])
841 * This condition actually marks a completely insoluble
842 * (i.e. internally inconsistent) puzzle. We return and
843 * report no progress made.
848 rowidx
[i
] = colidx
[first
] = FALSE
;
852 * Convert each of rowidx/colidx from a list of 0s and 1s to a
853 * list of the indices of the 1s.
855 for (i
= j
= 0; i
< cr
; i
++)
859 for (i
= j
= 0; i
< cr
; i
++)
865 * And create the smaller matrix.
867 for (i
= 0; i
< n
; i
++)
868 for (j
= 0; j
< n
; j
++)
869 grid
[i
*cr
+j
] = usage
->cube
[start
+rowidx
[i
]*step1
+colidx
[j
]*step2
];
872 * Having done that, we now have a matrix in which every row
873 * has at least two 1s in. Now we search to see if we can find
874 * a rectangle of zeroes (in the set-theoretic sense of
875 * `rectangle', i.e. a subset of rows crossed with a subset of
876 * columns) whose width and height add up to n.
883 * We have a candidate set. If its size is <=1 or >=n-1
884 * then we move on immediately.
886 if (count
> 1 && count
< n
-1) {
888 * The number of rows we need is n-count. See if we can
889 * find that many rows which each have a zero in all
890 * the positions listed in `set'.
893 for (i
= 0; i
< n
; i
++) {
895 for (j
= 0; j
< n
; j
++)
896 if (set
[j
] && grid
[i
*cr
+j
]) {
905 * We expect never to be able to get _more_ than
906 * n-count suitable rows: this would imply that (for
907 * example) there are four numbers which between them
908 * have at most three possible positions, and hence it
909 * indicates a faulty deduction before this point or
912 assert(rows
<= n
- count
);
913 if (rows
>= n
- count
) {
914 int progress
= FALSE
;
917 * We've got one! Now, for each row which _doesn't_
918 * satisfy the criterion, eliminate all its set
919 * bits in the positions _not_ listed in `set'.
920 * Return TRUE (meaning progress has been made) if
921 * we successfully eliminated anything at all.
923 * This involves referring back through
924 * rowidx/colidx in order to work out which actual
925 * positions in the cube to meddle with.
927 for (i
= 0; i
< n
; i
++) {
929 for (j
= 0; j
< n
; j
++)
930 if (set
[j
] && grid
[i
*cr
+j
]) {
935 for (j
= 0; j
< n
; j
++)
936 if (!set
[j
] && grid
[i
*cr
+j
]) {
937 int fpos
= (start
+rowidx
[i
]*step1
+
939 #ifdef STANDALONE_SOLVER
940 if (solver_show_working
) {
956 printf(" ruling out %d at (%d,%d)\n",
957 pn
, 1+px
, 1+YUNTRANS(py
));
961 usage
->cube
[fpos
] = FALSE
;
977 * Binary increment: change the rightmost 0 to a 1, and
978 * change all 1s to the right of it to 0s.
981 while (i
> 0 && set
[i
-1])
982 set
[--i
] = 0, count
--;
984 set
[--i
] = 1, count
++;
997 static int nsolve(int c
, int r
, digit
*grid
)
999 struct nsolve_usage
*usage
;
1002 int diff
= DIFF_BLOCK
;
1005 * Set up a usage structure as a clean slate (everything
1008 usage
= snew(struct nsolve_usage
);
1012 usage
->cube
= snewn(cr
*cr
*cr
, unsigned char);
1013 usage
->grid
= grid
; /* write straight back to the input */
1014 memset(usage
->cube
, TRUE
, cr
*cr
*cr
);
1016 usage
->row
= snewn(cr
* cr
, unsigned char);
1017 usage
->col
= snewn(cr
* cr
, unsigned char);
1018 usage
->blk
= snewn(cr
* cr
, unsigned char);
1019 memset(usage
->row
, FALSE
, cr
* cr
);
1020 memset(usage
->col
, FALSE
, cr
* cr
);
1021 memset(usage
->blk
, FALSE
, cr
* cr
);
1024 * Place all the clue numbers we are given.
1026 for (x
= 0; x
< cr
; x
++)
1027 for (y
= 0; y
< cr
; y
++)
1029 nsolve_place(usage
, x
, YTRANS(y
), grid
[y
*cr
+x
]);
1032 * Now loop over the grid repeatedly trying all permitted modes
1033 * of reasoning. The loop terminates if we complete an
1034 * iteration without making any progress; we then return
1035 * failure or success depending on whether the grid is full or
1040 * I'd like to write `continue;' inside each of the
1041 * following loops, so that the solver returns here after
1042 * making some progress. However, I can't specify that I
1043 * want to continue an outer loop rather than the innermost
1044 * one, so I'm apologetically resorting to a goto.
1049 * Blockwise positional elimination.
1051 for (x
= 0; x
< cr
; x
+= r
)
1052 for (y
= 0; y
< r
; y
++)
1053 for (n
= 1; n
<= cr
; n
++)
1054 if (!usage
->blk
[(y
*c
+(x
/r
))*cr
+n
-1] &&
1055 nsolve_elim(usage
, cubepos(x
,y
,n
), r
*cr
1056 #ifdef STANDALONE_SOLVER
1057 , "positional elimination,"
1058 " block (%d,%d)", 1+x
/r
, 1+y
1061 diff
= max(diff
, DIFF_BLOCK
);
1066 * Row-wise positional elimination.
1068 for (y
= 0; y
< cr
; y
++)
1069 for (n
= 1; n
<= cr
; n
++)
1070 if (!usage
->row
[y
*cr
+n
-1] &&
1071 nsolve_elim(usage
, cubepos(0,y
,n
), cr
*cr
1072 #ifdef STANDALONE_SOLVER
1073 , "positional elimination,"
1074 " row %d", 1+YUNTRANS(y
)
1077 diff
= max(diff
, DIFF_SIMPLE
);
1081 * Column-wise positional elimination.
1083 for (x
= 0; x
< cr
; x
++)
1084 for (n
= 1; n
<= cr
; n
++)
1085 if (!usage
->col
[x
*cr
+n
-1] &&
1086 nsolve_elim(usage
, cubepos(x
,0,n
), cr
1087 #ifdef STANDALONE_SOLVER
1088 , "positional elimination," " column %d", 1+x
1091 diff
= max(diff
, DIFF_SIMPLE
);
1096 * Numeric elimination.
1098 for (x
= 0; x
< cr
; x
++)
1099 for (y
= 0; y
< cr
; y
++)
1100 if (!usage
->grid
[YUNTRANS(y
)*cr
+x
] &&
1101 nsolve_elim(usage
, cubepos(x
,y
,1), 1
1102 #ifdef STANDALONE_SOLVER
1103 , "numeric elimination at (%d,%d)", 1+x
,
1107 diff
= max(diff
, DIFF_SIMPLE
);
1112 * Intersectional analysis, rows vs blocks.
1114 for (y
= 0; y
< cr
; y
++)
1115 for (x
= 0; x
< cr
; x
+= r
)
1116 for (n
= 1; n
<= cr
; n
++)
1117 if (!usage
->row
[y
*cr
+n
-1] &&
1118 !usage
->blk
[((y
%r
)*c
+(x
/r
))*cr
+n
-1] &&
1119 (nsolve_intersect(usage
, cubepos(0,y
,n
), cr
*cr
,
1120 cubepos(x
,y
%r
,n
), r
*cr
1121 #ifdef STANDALONE_SOLVER
1122 , "intersectional analysis,"
1123 " row %d vs block (%d,%d)",
1124 1+YUNTRANS(y
), 1+x
/r
, 1+y
%r
1127 nsolve_intersect(usage
, cubepos(x
,y
%r
,n
), r
*cr
,
1128 cubepos(0,y
,n
), cr
*cr
1129 #ifdef STANDALONE_SOLVER
1130 , "intersectional analysis,"
1131 " block (%d,%d) vs row %d",
1132 1+x
/r
, 1+y
%r
, 1+YUNTRANS(y
)
1135 diff
= max(diff
, DIFF_INTERSECT
);
1140 * Intersectional analysis, columns vs blocks.
1142 for (x
= 0; x
< cr
; x
++)
1143 for (y
= 0; y
< r
; y
++)
1144 for (n
= 1; n
<= cr
; n
++)
1145 if (!usage
->col
[x
*cr
+n
-1] &&
1146 !usage
->blk
[(y
*c
+(x
/r
))*cr
+n
-1] &&
1147 (nsolve_intersect(usage
, cubepos(x
,0,n
), cr
,
1148 cubepos((x
/r
)*r
,y
,n
), r
*cr
1149 #ifdef STANDALONE_SOLVER
1150 , "intersectional analysis,"
1151 " column %d vs block (%d,%d)",
1155 nsolve_intersect(usage
, cubepos((x
/r
)*r
,y
,n
), r
*cr
,
1157 #ifdef STANDALONE_SOLVER
1158 , "intersectional analysis,"
1159 " block (%d,%d) vs column %d",
1163 diff
= max(diff
, DIFF_INTERSECT
);
1168 * Blockwise set elimination.
1170 for (x
= 0; x
< cr
; x
+= r
)
1171 for (y
= 0; y
< r
; y
++)
1172 if (nsolve_set(usage
, cubepos(x
,y
,1), r
*cr
, 1
1173 #ifdef STANDALONE_SOLVER
1174 , "set elimination, block (%d,%d)", 1+x
/r
, 1+y
1177 diff
= max(diff
, DIFF_SET
);
1182 * Row-wise set elimination.
1184 for (y
= 0; y
< cr
; y
++)
1185 if (nsolve_set(usage
, cubepos(0,y
,1), cr
*cr
, 1
1186 #ifdef STANDALONE_SOLVER
1187 , "set elimination, row %d", 1+YUNTRANS(y
)
1190 diff
= max(diff
, DIFF_SET
);
1195 * Column-wise set elimination.
1197 for (x
= 0; x
< cr
; x
++)
1198 if (nsolve_set(usage
, cubepos(x
,0,1), cr
, 1
1199 #ifdef STANDALONE_SOLVER
1200 , "set elimination, column %d", 1+x
1203 diff
= max(diff
, DIFF_SET
);
1208 * If we reach here, we have made no deductions in this
1209 * iteration, so the algorithm terminates.
1220 for (x
= 0; x
< cr
; x
++)
1221 for (y
= 0; y
< cr
; y
++)
1223 return DIFF_IMPOSSIBLE
;
1227 /* ----------------------------------------------------------------------
1228 * End of non-recursive solver code.
1232 * Check whether a grid contains a valid complete puzzle.
1234 static int check_valid(int c
, int r
, digit
*grid
)
1237 unsigned char *used
;
1240 used
= snewn(cr
, unsigned char);
1243 * Check that each row contains precisely one of everything.
1245 for (y
= 0; y
< cr
; y
++) {
1246 memset(used
, FALSE
, cr
);
1247 for (x
= 0; x
< cr
; x
++)
1248 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
1249 used
[grid
[y
*cr
+x
]-1] = TRUE
;
1250 for (n
= 0; n
< cr
; n
++)
1258 * Check that each column contains precisely one of everything.
1260 for (x
= 0; x
< cr
; x
++) {
1261 memset(used
, FALSE
, cr
);
1262 for (y
= 0; y
< cr
; y
++)
1263 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
1264 used
[grid
[y
*cr
+x
]-1] = TRUE
;
1265 for (n
= 0; n
< cr
; n
++)
1273 * Check that each block contains precisely one of everything.
1275 for (x
= 0; x
< cr
; x
+= r
) {
1276 for (y
= 0; y
< cr
; y
+= c
) {
1278 memset(used
, FALSE
, cr
);
1279 for (xx
= x
; xx
< x
+r
; xx
++)
1280 for (yy
= 0; yy
< y
+c
; yy
++)
1281 if (grid
[yy
*cr
+xx
] > 0 && grid
[yy
*cr
+xx
] <= cr
)
1282 used
[grid
[yy
*cr
+xx
]-1] = TRUE
;
1283 for (n
= 0; n
< cr
; n
++)
1295 static void symmetry_limit(game_params
*params
, int *xlim
, int *ylim
, int s
)
1297 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1309 *xlim
= *ylim
= (cr
+1) / 2;
1314 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
1316 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1325 break; /* just x,y is all we need */
1330 *output
++ = cr
- 1 - x
;
1335 *output
++ = cr
- 1 - y
;
1339 *output
++ = cr
- 1 - y
;
1344 *output
++ = cr
- 1 - x
;
1350 *output
++ = cr
- 1 - x
;
1351 *output
++ = cr
- 1 - y
;
1359 struct game_aux_info
{
1364 static char *new_game_seed(game_params
*params
, random_state
*rs
,
1365 game_aux_info
**aux
)
1367 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1369 digit
*grid
, *grid2
;
1370 struct xy
{ int x
, y
; } *locs
;
1374 int coords
[16], ncoords
;
1376 int maxdiff
, recursing
;
1379 * Adjust the maximum difficulty level to be consistent with
1380 * the puzzle size: all 2x2 puzzles appear to be Trivial
1381 * (DIFF_BLOCK) so we cannot hold out for even a Basic
1382 * (DIFF_SIMPLE) one.
1384 maxdiff
= params
->diff
;
1385 if (c
== 2 && r
== 2)
1386 maxdiff
= DIFF_BLOCK
;
1388 grid
= snewn(area
, digit
);
1389 locs
= snewn(area
, struct xy
);
1390 grid2
= snewn(area
, digit
);
1393 * Loop until we get a grid of the required difficulty. This is
1394 * nasty, but it seems to be unpleasantly hard to generate
1395 * difficult grids otherwise.
1399 * Start the recursive solver with an empty grid to generate a
1400 * random solved state.
1402 memset(grid
, 0, area
);
1403 ret
= rsolve(c
, r
, grid
, rs
, 1);
1405 assert(check_valid(c
, r
, grid
));
1408 * Save the solved grid in the aux_info.
1411 game_aux_info
*ai
= snew(game_aux_info
);
1414 ai
->grid
= snewn(cr
* cr
, digit
);
1415 memcpy(ai
->grid
, grid
, cr
* cr
* sizeof(digit
));
1420 * Now we have a solved grid, start removing things from it
1421 * while preserving solubility.
1423 symmetry_limit(params
, &xlim
, &ylim
, params
->symm
);
1429 * Iterate over the grid and enumerate all the filled
1430 * squares we could empty.
1434 for (x
= 0; x
< xlim
; x
++)
1435 for (y
= 0; y
< ylim
; y
++)
1443 * Now shuffle that list.
1445 for (i
= nlocs
; i
> 1; i
--) {
1446 int p
= random_upto(rs
, i
);
1448 struct xy t
= locs
[p
];
1449 locs
[p
] = locs
[i
-1];
1455 * Now loop over the shuffled list and, for each element,
1456 * see whether removing that element (and its reflections)
1457 * from the grid will still leave the grid soluble by
1460 for (i
= 0; i
< nlocs
; i
++) {
1466 memcpy(grid2
, grid
, area
);
1467 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
1468 for (j
= 0; j
< ncoords
; j
++)
1469 grid2
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
1472 ret
= (rsolve(c
, r
, grid2
, NULL
, 2) == 1);
1474 ret
= (nsolve(c
, r
, grid2
) <= maxdiff
);
1477 for (j
= 0; j
< ncoords
; j
++)
1478 grid
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
1485 * There was nothing we could remove without
1486 * destroying solvability. If we're trying to
1487 * generate a recursion-only grid and haven't
1488 * switched over to rsolve yet, we now do;
1489 * otherwise we give up.
1491 if (maxdiff
== DIFF_RECURSIVE
&& !recursing
) {
1499 memcpy(grid2
, grid
, area
);
1500 } while (nsolve(c
, r
, grid2
) < maxdiff
);
1506 * Now we have the grid as it will be presented to the user.
1507 * Encode it in a game seed.
1513 seed
= snewn(5 * area
, char);
1516 for (i
= 0; i
<= area
; i
++) {
1517 int n
= (i
< area ? grid
[i
] : -1);
1524 int c
= 'a' - 1 + run
;
1528 run
-= c
- ('a' - 1);
1532 * If there's a number in the very top left or
1533 * bottom right, there's no point putting an
1534 * unnecessary _ before or after it.
1536 if (p
> seed
&& n
> 0)
1540 p
+= sprintf(p
, "%d", n
);
1544 assert(p
- seed
< 5 * area
);
1546 seed
= sresize(seed
, p
- seed
, char);
1554 static void game_free_aux_info(game_aux_info
*aux
)
1560 static char *validate_seed(game_params
*params
, char *seed
)
1562 int area
= params
->r
* params
->r
* params
->c
* params
->c
;
1567 if (n
>= 'a' && n
<= 'z') {
1568 squares
+= n
- 'a' + 1;
1569 } else if (n
== '_') {
1571 } else if (n
> '0' && n
<= '9') {
1573 while (*seed
>= '0' && *seed
<= '9')
1576 return "Invalid character in game specification";
1580 return "Not enough data to fill grid";
1583 return "Too much data to fit in grid";
1588 static game_state
*new_game(game_params
*params
, char *seed
)
1590 game_state
*state
= snew(game_state
);
1591 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
1594 state
->c
= params
->c
;
1595 state
->r
= params
->r
;
1597 state
->grid
= snewn(area
, digit
);
1598 state
->immutable
= snewn(area
, unsigned char);
1599 memset(state
->immutable
, FALSE
, area
);
1601 state
->completed
= state
->cheated
= FALSE
;
1606 if (n
>= 'a' && n
<= 'z') {
1607 int run
= n
- 'a' + 1;
1608 assert(i
+ run
<= area
);
1610 state
->grid
[i
++] = 0;
1611 } else if (n
== '_') {
1613 } else if (n
> '0' && n
<= '9') {
1615 state
->immutable
[i
] = TRUE
;
1616 state
->grid
[i
++] = atoi(seed
-1);
1617 while (*seed
>= '0' && *seed
<= '9')
1620 assert(!"We can't get here");
1628 static game_state
*dup_game(game_state
*state
)
1630 game_state
*ret
= snew(game_state
);
1631 int c
= state
->c
, r
= state
->r
, cr
= c
*r
, area
= cr
* cr
;
1636 ret
->grid
= snewn(area
, digit
);
1637 memcpy(ret
->grid
, state
->grid
, area
);
1639 ret
->immutable
= snewn(area
, unsigned char);
1640 memcpy(ret
->immutable
, state
->immutable
, area
);
1642 ret
->completed
= state
->completed
;
1643 ret
->cheated
= state
->cheated
;
1648 static void free_game(game_state
*state
)
1650 sfree(state
->immutable
);
1655 static game_state
*solve_game(game_state
*state
, game_aux_info
*ai
,
1659 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1662 ret
= dup_game(state
);
1663 ret
->completed
= ret
->cheated
= TRUE
;
1666 * If we already have the solution in the aux_info, save
1667 * ourselves some time.
1673 memcpy(ret
->grid
, ai
->grid
, cr
* cr
* sizeof(digit
));
1676 rsolve_ret
= rsolve(c
, r
, ret
->grid
, NULL
, 2);
1678 if (rsolve_ret
!= 1) {
1680 if (rsolve_ret
== 0)
1681 *error
= "No solution exists for this puzzle";
1683 *error
= "Multiple solutions exist for this puzzle";
1691 static char *grid_text_format(int c
, int r
, digit
*grid
)
1699 * There are cr lines of digits, plus r-1 lines of block
1700 * separators. Each line contains cr digits, cr-1 separating
1701 * spaces, and c-1 two-character block separators. Thus, the
1702 * total length of a line is 2*cr+2*c-3 (not counting the
1703 * newline), and there are cr+r-1 of them.
1705 maxlen
= (cr
+r
-1) * (2*cr
+2*c
-2);
1706 ret
= snewn(maxlen
+1, char);
1709 for (y
= 0; y
< cr
; y
++) {
1710 for (x
= 0; x
< cr
; x
++) {
1711 int ch
= grid
[y
* cr
+ x
];
1721 if ((x
+1) % r
== 0) {
1728 if (y
+1 < cr
&& (y
+1) % c
== 0) {
1729 for (x
= 0; x
< cr
; x
++) {
1733 if ((x
+1) % r
== 0) {
1743 assert(p
- ret
== maxlen
);
1748 static char *game_text_format(game_state
*state
)
1750 return grid_text_format(state
->c
, state
->r
, state
->grid
);
1755 * These are the coordinates of the currently highlighted
1756 * square on the grid, or -1,-1 if there isn't one. When there
1757 * is, pressing a valid number or letter key or Space will
1758 * enter that number or letter in the grid.
1763 static game_ui
*new_ui(game_state
*state
)
1765 game_ui
*ui
= snew(game_ui
);
1767 ui
->hx
= ui
->hy
= -1;
1772 static void free_ui(game_ui
*ui
)
1777 static game_state
*make_move(game_state
*from
, game_ui
*ui
, int x
, int y
,
1780 int c
= from
->c
, r
= from
->r
, cr
= c
*r
;
1784 button
&= ~MOD_NUM_KEYPAD
; /* we treat this the same as normal */
1786 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
1787 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
1789 if (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&& button
== LEFT_BUTTON
) {
1790 if (tx
== ui
->hx
&& ty
== ui
->hy
) {
1791 ui
->hx
= ui
->hy
= -1;
1796 return from
; /* UI activity occurred */
1799 if (ui
->hx
!= -1 && ui
->hy
!= -1 &&
1800 ((button
>= '1' && button
<= '9' && button
- '0' <= cr
) ||
1801 (button
>= 'a' && button
<= 'z' && button
- 'a' + 10 <= cr
) ||
1802 (button
>= 'A' && button
<= 'Z' && button
- 'A' + 10 <= cr
) ||
1804 int n
= button
- '0';
1805 if (button
>= 'A' && button
<= 'Z')
1806 n
= button
- 'A' + 10;
1807 if (button
>= 'a' && button
<= 'z')
1808 n
= button
- 'a' + 10;
1812 if (from
->immutable
[ui
->hy
*cr
+ui
->hx
])
1813 return NULL
; /* can't overwrite this square */
1815 ret
= dup_game(from
);
1816 ret
->grid
[ui
->hy
*cr
+ui
->hx
] = n
;
1817 ui
->hx
= ui
->hy
= -1;
1820 * We've made a real change to the grid. Check to see
1821 * if the game has been completed.
1823 if (!ret
->completed
&& check_valid(c
, r
, ret
->grid
)) {
1824 ret
->completed
= TRUE
;
1827 return ret
; /* made a valid move */
1833 /* ----------------------------------------------------------------------
1837 struct game_drawstate
{
1844 #define XSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1845 #define YSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1847 static void game_size(game_params
*params
, int *x
, int *y
)
1849 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
1855 static float *game_colours(frontend
*fe
, game_state
*state
, int *ncolours
)
1857 float *ret
= snewn(3 * NCOLOURS
, float);
1859 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
1861 ret
[COL_GRID
* 3 + 0] = 0.0F
;
1862 ret
[COL_GRID
* 3 + 1] = 0.0F
;
1863 ret
[COL_GRID
* 3 + 2] = 0.0F
;
1865 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
1866 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
1867 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
1869 ret
[COL_USER
* 3 + 0] = 0.0F
;
1870 ret
[COL_USER
* 3 + 1] = 0.6F
* ret
[COL_BACKGROUND
* 3 + 1];
1871 ret
[COL_USER
* 3 + 2] = 0.0F
;
1873 ret
[COL_HIGHLIGHT
* 3 + 0] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 0];
1874 ret
[COL_HIGHLIGHT
* 3 + 1] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 1];
1875 ret
[COL_HIGHLIGHT
* 3 + 2] = 0.85F
* ret
[COL_BACKGROUND
* 3 + 2];
1877 *ncolours
= NCOLOURS
;
1881 static game_drawstate
*game_new_drawstate(game_state
*state
)
1883 struct game_drawstate
*ds
= snew(struct game_drawstate
);
1884 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1886 ds
->started
= FALSE
;
1890 ds
->grid
= snewn(cr
*cr
, digit
);
1891 memset(ds
->grid
, 0, cr
*cr
);
1892 ds
->hl
= snewn(cr
*cr
, unsigned char);
1893 memset(ds
->hl
, 0, cr
*cr
);
1898 static void game_free_drawstate(game_drawstate
*ds
)
1905 static void draw_number(frontend
*fe
, game_drawstate
*ds
, game_state
*state
,
1906 int x
, int y
, int hl
)
1908 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1913 if (ds
->grid
[y
*cr
+x
] == state
->grid
[y
*cr
+x
] && ds
->hl
[y
*cr
+x
] == hl
)
1914 return; /* no change required */
1916 tx
= BORDER
+ x
* TILE_SIZE
+ 2;
1917 ty
= BORDER
+ y
* TILE_SIZE
+ 2;
1933 clip(fe
, cx
, cy
, cw
, ch
);
1935 /* background needs erasing? */
1936 if (ds
->grid
[y
*cr
+x
] || ds
->hl
[y
*cr
+x
] != hl
)
1937 draw_rect(fe
, cx
, cy
, cw
, ch
, hl ? COL_HIGHLIGHT
: COL_BACKGROUND
);
1939 /* new number needs drawing? */
1940 if (state
->grid
[y
*cr
+x
]) {
1942 str
[0] = state
->grid
[y
*cr
+x
] + '0';
1944 str
[0] += 'a' - ('9'+1);
1945 draw_text(fe
, tx
+ TILE_SIZE
/2, ty
+ TILE_SIZE
/2,
1946 FONT_VARIABLE
, TILE_SIZE
/2, ALIGN_VCENTRE
| ALIGN_HCENTRE
,
1947 state
->immutable
[y
*cr
+x
] ? COL_CLUE
: COL_USER
, str
);
1952 draw_update(fe
, cx
, cy
, cw
, ch
);
1954 ds
->grid
[y
*cr
+x
] = state
->grid
[y
*cr
+x
];
1955 ds
->hl
[y
*cr
+x
] = hl
;
1958 static void game_redraw(frontend
*fe
, game_drawstate
*ds
, game_state
*oldstate
,
1959 game_state
*state
, int dir
, game_ui
*ui
,
1960 float animtime
, float flashtime
)
1962 int c
= state
->c
, r
= state
->r
, cr
= c
*r
;
1967 * The initial contents of the window are not guaranteed
1968 * and can vary with front ends. To be on the safe side,
1969 * all games should start by drawing a big
1970 * background-colour rectangle covering the whole window.
1972 draw_rect(fe
, 0, 0, XSIZE(cr
), YSIZE(cr
), COL_BACKGROUND
);
1977 for (x
= 0; x
<= cr
; x
++) {
1978 int thick
= (x
% r ?
0 : 1);
1979 draw_rect(fe
, BORDER
+ x
*TILE_SIZE
- thick
, BORDER
-1,
1980 1+2*thick
, cr
*TILE_SIZE
+3, COL_GRID
);
1982 for (y
= 0; y
<= cr
; y
++) {
1983 int thick
= (y
% c ?
0 : 1);
1984 draw_rect(fe
, BORDER
-1, BORDER
+ y
*TILE_SIZE
- thick
,
1985 cr
*TILE_SIZE
+3, 1+2*thick
, COL_GRID
);
1990 * Draw any numbers which need redrawing.
1992 for (x
= 0; x
< cr
; x
++) {
1993 for (y
= 0; y
< cr
; y
++) {
1994 draw_number(fe
, ds
, state
, x
, y
,
1995 (x
== ui
->hx
&& y
== ui
->hy
) ||
1997 (flashtime
<= FLASH_TIME
/3 ||
1998 flashtime
>= FLASH_TIME
*2/3)));
2003 * Update the _entire_ grid if necessary.
2006 draw_update(fe
, 0, 0, XSIZE(cr
), YSIZE(cr
));
2011 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
2017 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
2020 if (!oldstate
->completed
&& newstate
->completed
&&
2021 !oldstate
->cheated
&& !newstate
->cheated
)
2026 static int game_wants_statusbar(void)
2032 #define thegame solo
2035 const struct game thegame
= {
2036 "Solo", "games.solo",
2043 TRUE
, game_configure
, custom_params
,
2052 TRUE
, game_text_format
,
2059 game_free_drawstate
,
2063 game_wants_statusbar
,
2066 #ifdef STANDALONE_SOLVER
2069 * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2072 void frontend_default_colour(frontend
*fe
, float *output
) {}
2073 void draw_text(frontend
*fe
, int x
, int y
, int fonttype
, int fontsize
,
2074 int align
, int colour
, char *text
) {}
2075 void draw_rect(frontend
*fe
, int x
, int y
, int w
, int h
, int colour
) {}
2076 void draw_line(frontend
*fe
, int x1
, int y1
, int x2
, int y2
, int colour
) {}
2077 void draw_polygon(frontend
*fe
, int *coords
, int npoints
,
2078 int fill
, int colour
) {}
2079 void clip(frontend
*fe
, int x
, int y
, int w
, int h
) {}
2080 void unclip(frontend
*fe
) {}
2081 void start_draw(frontend
*fe
) {}
2082 void draw_update(frontend
*fe
, int x
, int y
, int w
, int h
) {}
2083 void end_draw(frontend
*fe
) {}
2084 unsigned long random_bits(random_state
*state
, int bits
)
2085 { assert(!"Shouldn't get randomness"); return 0; }
2086 unsigned long random_upto(random_state
*state
, unsigned long limit
)
2087 { assert(!"Shouldn't get randomness"); return 0; }
2089 void fatal(char *fmt
, ...)
2093 fprintf(stderr
, "fatal error: ");
2096 vfprintf(stderr
, fmt
, ap
);
2099 fprintf(stderr
, "\n");
2103 int main(int argc
, char **argv
)
2108 char *id
= NULL
, *seed
, *err
;
2112 while (--argc
> 0) {
2114 if (!strcmp(p
, "-r")) {
2116 } else if (!strcmp(p
, "-n")) {
2118 } else if (!strcmp(p
, "-v")) {
2119 solver_show_working
= TRUE
;
2121 } else if (!strcmp(p
, "-g")) {
2124 } else if (*p
== '-') {
2125 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0]);
2133 fprintf(stderr
, "usage: %s [-n | -r | -g | -v] <game_id>\n", argv
[0]);
2137 seed
= strchr(id
, ':');
2139 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
2144 p
= decode_params(id
);
2145 err
= validate_seed(p
, seed
);
2147 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
2150 s
= new_game(p
, seed
);
2153 int ret
= rsolve(p
->c
, p
->r
, s
->grid
, NULL
, 2);
2155 fprintf(stderr
, "%s: rsolve: multiple solutions detected\n",
2159 int ret
= nsolve(p
->c
, p
->r
, s
->grid
);
2161 if (ret
== DIFF_IMPOSSIBLE
) {
2163 * Now resort to rsolve to determine whether it's
2166 ret
= rsolve(p
->c
, p
->r
, s
->grid
, NULL
, 2);
2168 ret
= DIFF_IMPOSSIBLE
;
2170 ret
= DIFF_RECURSIVE
;
2172 ret
= DIFF_AMBIGUOUS
;
2174 printf("Difficulty rating: %s\n",
2175 ret
==DIFF_BLOCK ?
"Trivial (blockwise positional elimination only)":
2176 ret
==DIFF_SIMPLE ?
"Basic (row/column/number elimination required)":
2177 ret
==DIFF_INTERSECT ?
"Intermediate (intersectional analysis required)":
2178 ret
==DIFF_SET ?
"Advanced (set elimination required)":
2179 ret
==DIFF_RECURSIVE ?
"Unreasonable (guesswork and backtracking required)":
2180 ret
==DIFF_AMBIGUOUS ?
"Ambiguous (multiple solutions exist)":
2181 ret
==DIFF_IMPOSSIBLE ?
"Impossible (no solution exists)":
2182 "INTERNAL ERROR: unrecognised difficulty code");
2186 printf("%s\n", grid_text_format(p
->c
, p
->r
, s
->grid
));