2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - reports from users are that `Trivial'-mode puzzles are still
7 * rather hard compared to newspapers' easy ones, so some better
8 * low-end difficulty grading would be nice
9 * + it's possible that really easy puzzles always have
10 * _several_ things you can do, so don't make you hunt too
11 * hard for the one deduction you can currently make
12 * + it's also possible that easy puzzles require fewer
13 * cross-eliminations: perhaps there's a higher incidence of
14 * things you can deduce by looking only at (say) rows,
15 * rather than things you have to check both rows and columns
17 * + but really, what I need to do is find some really easy
18 * puzzles and _play_ them, to see what's actually easy about
20 * + while I'm revamping this area, filling in the _last_
21 * number in a nearly-full row or column should certainly be
22 * permitted even at the lowest difficulty level.
23 * + also Owen noticed that `Basic' grids requiring numeric
24 * elimination are actually very hard, so I wonder if a
25 * difficulty gradation between that and positional-
26 * elimination-only might be in order
27 * + but it's not good to have _too_ many difficulty levels, or
28 * it'll take too long to randomly generate a given level.
30 * - it might still be nice to do some prioritisation on the
31 * removal of numbers from the grid
32 * + one possibility is to try to minimise the maximum number
33 * of filled squares in any block, which in particular ought
34 * to enforce never leaving a completely filled block in the
35 * puzzle as presented.
37 * - alternative interface modes
38 * + sudoku.com's Windows program has a palette of possible
39 * entries; you select a palette entry first and then click
40 * on the square you want it to go in, thus enabling
41 * mouse-only play. Useful for PDAs! I don't think it's
42 * actually incompatible with the current highlight-then-type
43 * approach: you _either_ highlight a palette entry and then
44 * click, _or_ you highlight a square and then type. At most
45 * one thing is ever highlighted at a time, so there's no way
47 * + then again, I don't actually like sudoku.com's interface;
48 * it's too much like a paint package whereas I prefer to
49 * think of Solo as a text editor.
50 * + another PDA-friendly possibility is a drag interface:
51 * _drag_ numbers from the palette into the grid squares.
52 * Thought experiments suggest I'd prefer that to the
53 * sudoku.com approach, but I haven't actually tried it.
57 * Solo puzzles need to be square overall (since each row and each
58 * column must contain one of every digit), but they need not be
59 * subdivided the same way internally. I am going to adopt a
60 * convention whereby I _always_ refer to `r' as the number of rows
61 * of _big_ divisions, and `c' as the number of columns of _big_
62 * divisions. Thus, a 2c by 3r puzzle looks something like this:
66 * ------+------ (Of course, you can't subdivide it the other way
67 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
68 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
69 * ------+------ box down on the left-hand side.)
73 * The need for a strong naming convention should now be clear:
74 * each small box is two rows of digits by three columns, while the
75 * overall puzzle has three rows of small boxes by two columns. So
76 * I will (hopefully) consistently use `r' to denote the number of
77 * rows _of small boxes_ (here 3), which is also the number of
78 * columns of digits in each small box; and `c' vice versa (here
81 * I'm also going to choose arbitrarily to list c first wherever
82 * possible: the above is a 2x3 puzzle, not a 3x2 one.
92 #ifdef STANDALONE_SOLVER
94 int solver_show_working, solver_recurse_depth;
100 * To save space, I store digits internally as unsigned char. This
101 * imposes a hard limit of 255 on the order of the puzzle. Since
102 * even a 5x5 takes unacceptably long to generate, I don't see this
103 * as a serious limitation unless something _really_ impressive
104 * happens in computing technology; but here's a typedef anyway for
105 * general good practice.
107 typedef unsigned char digit;
108 #define ORDER_MAX 255
110 #define PREFERRED_TILE_SIZE 32
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
114 #define FLASH_TIME 0.4F
116 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
117 SYMM_REF4D, SYMM_REF8 };
119 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_NEIGHBOUR,
120 DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
134 int c, r, symm, diff;
140 unsigned char *pencil; /* c*r*c*r elements */
141 unsigned char *immutable; /* marks which digits are clues */
142 int completed, cheated;
145 static game_params *default_params(void)
147 game_params *ret = snew(game_params);
150 ret->symm = SYMM_ROT2; /* a plausible default */
151 ret->diff = DIFF_BLOCK; /* so is this */
156 static void free_params(game_params *params)
161 static game_params *dup_params(game_params *params)
163 game_params *ret = snew(game_params);
164 *ret = *params; /* structure copy */
168 static int game_fetch_preset(int i, char **name, game_params **params)
174 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK } },
175 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE } },
176 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK } },
177 { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE } },
178 { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT } },
179 { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET } },
180 { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_NEIGHBOUR } },
181 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE } },
183 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE } },
184 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE } },
188 if (i < 0 || i >= lenof(presets))
191 *name = dupstr(presets[i].title);
192 *params = dup_params(&presets[i].params);
197 static void decode_params(game_params *ret, char const *string)
199 ret->c = ret->r = atoi(string);
200 while (*string && isdigit((unsigned char)*string)) string++;
201 if (*string == 'x') {
203 ret->r = atoi(string);
204 while (*string && isdigit((unsigned char)*string)) string++;
207 if (*string == 'r' || *string == 'm' || *string == 'a') {
210 if (*string == 'd') {
217 while (*string && isdigit((unsigned char)*string)) string++;
218 if (sc == 'm' && sn == 8)
219 ret->symm = SYMM_REF8;
220 if (sc == 'm' && sn == 4)
221 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
222 if (sc == 'm' && sn == 2)
223 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
224 if (sc == 'r' && sn == 4)
225 ret->symm = SYMM_ROT4;
226 if (sc == 'r' && sn == 2)
227 ret->symm = SYMM_ROT2;
229 ret->symm = SYMM_NONE;
230 } else if (*string == 'd') {
232 if (*string == 't') /* trivial */
233 string++, ret->diff = DIFF_BLOCK;
234 else if (*string == 'b') /* basic */
235 string++, ret->diff = DIFF_SIMPLE;
236 else if (*string == 'i') /* intermediate */
237 string++, ret->diff = DIFF_INTERSECT;
238 else if (*string == 'a') /* advanced */
239 string++, ret->diff = DIFF_SET;
240 else if (*string == 'e') /* extreme */
241 string++, ret->diff = DIFF_NEIGHBOUR;
242 else if (*string == 'u') /* unreasonable */
243 string++, ret->diff = DIFF_RECURSIVE;
245 string++; /* eat unknown character */
249 static char *encode_params(game_params *params, int full)
253 sprintf(str, "%dx%d", params->c, params->r);
255 switch (params->symm) {
256 case SYMM_REF8: strcat(str, "m8"); break;
257 case SYMM_REF4: strcat(str, "m4"); break;
258 case SYMM_REF4D: strcat(str, "md4"); break;
259 case SYMM_REF2: strcat(str, "m2"); break;
260 case SYMM_REF2D: strcat(str, "md2"); break;
261 case SYMM_ROT4: strcat(str, "r4"); break;
262 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
263 case SYMM_NONE: strcat(str, "a"); break;
265 switch (params->diff) {
266 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
267 case DIFF_SIMPLE: strcat(str, "db"); break;
268 case DIFF_INTERSECT: strcat(str, "di"); break;
269 case DIFF_SET: strcat(str, "da"); break;
270 case DIFF_NEIGHBOUR: strcat(str, "de"); break;
271 case DIFF_RECURSIVE: strcat(str, "du"); break;
277 static config_item *game_configure(game_params *params)
282 ret = snewn(5, config_item);
284 ret[0].name = "Columns of sub-blocks";
285 ret[0].type = C_STRING;
286 sprintf(buf, "%d", params->c);
287 ret[0].sval = dupstr(buf);
290 ret[1].name = "Rows of sub-blocks";
291 ret[1].type = C_STRING;
292 sprintf(buf, "%d", params->r);
293 ret[1].sval = dupstr(buf);
296 ret[2].name = "Symmetry";
297 ret[2].type = C_CHOICES;
298 ret[2].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
299 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
301 ret[2].ival = params->symm;
303 ret[3].name = "Difficulty";
304 ret[3].type = C_CHOICES;
305 ret[3].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
306 ret[3].ival = params->diff;
316 static game_params *custom_params(config_item *cfg)
318 game_params *ret = snew(game_params);
320 ret->c = atoi(cfg[0].sval);
321 ret->r = atoi(cfg[1].sval);
322 ret->symm = cfg[2].ival;
323 ret->diff = cfg[3].ival;
328 static char *validate_params(game_params *params, int full)
330 if (params->c < 2 || params->r < 2)
331 return "Both dimensions must be at least 2";
332 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
333 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
334 if ((params->c * params->r) > 36)
335 return "Unable to support more than 36 distinct symbols in a puzzle";
339 /* ----------------------------------------------------------------------
342 * This solver is used for two purposes:
343 * + to check solubility of a grid as we gradually remove numbers
345 * + to solve an externally generated puzzle when the user selects
348 * It supports a variety of specific modes of reasoning. By
349 * enabling or disabling subsets of these modes we can arrange a
350 * range of difficulty levels.
354 * Modes of reasoning currently supported:
356 * - Positional elimination: a number must go in a particular
357 * square because all the other empty squares in a given
358 * row/col/blk are ruled out.
360 * - Numeric elimination: a square must have a particular number
361 * in because all the other numbers that could go in it are
364 * - Intersectional analysis: given two domains which overlap
365 * (hence one must be a block, and the other can be a row or
366 * col), if the possible locations for a particular number in
367 * one of the domains can be narrowed down to the overlap, then
368 * that number can be ruled out everywhere but the overlap in
369 * the other domain too.
371 * - Set elimination: if there is a subset of the empty squares
372 * within a domain such that the union of the possible numbers
373 * in that subset has the same size as the subset itself, then
374 * those numbers can be ruled out everywhere else in the domain.
375 * (For example, if there are five empty squares and the
376 * possible numbers in each are 12, 23, 13, 134 and 1345, then
377 * the first three empty squares form such a subset: the numbers
378 * 1, 2 and 3 _must_ be in those three squares in some
379 * permutation, and hence we can deduce none of them can be in
380 * the fourth or fifth squares.)
381 * + You can also see this the other way round, concentrating
382 * on numbers rather than squares: if there is a subset of
383 * the unplaced numbers within a domain such that the union
384 * of all their possible positions has the same size as the
385 * subset itself, then all other numbers can be ruled out for
386 * those positions. However, it turns out that this is
387 * exactly equivalent to the first formulation at all times:
388 * there is a 1-1 correspondence between suitable subsets of
389 * the unplaced numbers and suitable subsets of the unfilled
390 * places, found by taking the _complement_ of the union of
391 * the numbers' possible positions (or the spaces' possible
394 * - Mutual neighbour elimination: find two squares A,B and a
395 * number N in the possible set of A, such that putting N in A
396 * would rule out enough possibilities from the mutual
397 * neighbours of A and B that there would be no possibilities
398 * left for B. Thereby rule out N in A.
399 * + The simplest case of this is if B has two possibilities
400 * (wlog {1,2}), and there are two mutual neighbours of A and
401 * B which have possibilities {1,3} and {2,3}. Thus, if A
402 * were to be 3, then those neighbours would contain 1 and 2,
403 * and hence there would be nothing left which could go in B.
404 * + There can be more complex cases of it too: if A and B are
405 * in the same column of large blocks, then they can have
406 * more than two mutual neighbours, some of which can also be
407 * neighbours of one another. Suppose, for example, that B
408 * has possibilities {1,2,3}; there's one square P in the
409 * same column as B and the same block as A, with
410 * possibilities {1,4}; and there are _two_ squares Q,R in
411 * the same column as A and the same block as B with
412 * possibilities {2,3,4}. Then if A contained 4, P would
413 * contain 1, and Q and R would have to contain 2 and 3 in
414 * _some_ order; therefore, once again, B would have no
415 * remaining possibilities.
417 * - Recursion. If all else fails, we pick one of the currently
418 * most constrained empty squares and take a random guess at its
419 * contents, then continue solving on that basis and see if we
424 * Within this solver, I'm going to transform all y-coordinates by
425 * inverting the significance of the block number and the position
426 * within the block. That is, we will start with the top row of
427 * each block in order, then the second row of each block in order,
430 * This transformation has the enormous advantage that it means
431 * every row, column _and_ block is described by an arithmetic
432 * progression of coordinates within the cubic array, so that I can
433 * use the same very simple function to do blockwise, row-wise and
434 * column-wise elimination.
436 #define YTRANS(y) (((y)%c)*r+(y)/c)
437 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
439 struct solver_usage {
442 * We set up a cubic array, indexed by x, y and digit; each
443 * element of this array is TRUE or FALSE according to whether
444 * or not that digit _could_ in principle go in that position.
446 * The way to index this array is cube[(x*cr+y)*cr+n-1].
447 * y-coordinates in here are transformed.
451 * This is the grid in which we write down our final
452 * deductions. y-coordinates in here are _not_ transformed.
456 * Now we keep track, at a slightly higher level, of what we
457 * have yet to work out, to prevent doing the same deduction
460 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
462 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
464 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
467 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
468 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
471 * Function called when we are certain that a particular square has
472 * a particular number in it. The y-coordinate passed in here is
475 static void solver_place(struct solver_usage *usage, int x, int y, int n)
477 int c = usage->c, r = usage->r, cr = usage->cr;
483 * Rule out all other numbers in this square.
485 for (i = 1; i <= cr; i++)
490 * Rule out this number in all other positions in the row.
492 for (i = 0; i < cr; i++)
497 * Rule out this number in all other positions in the column.
499 for (i = 0; i < cr; i++)
504 * Rule out this number in all other positions in the block.
508 for (i = 0; i < r; i++)
509 for (j = 0; j < c; j++)
510 if (bx+i != x || by+j*r != y)
511 cube(bx+i,by+j*r,n) = FALSE;
514 * Enter the number in the result grid.
516 usage->grid[YUNTRANS(y)*cr+x] = n;
519 * Cross out this number from the list of numbers left to place
520 * in its row, its column and its block.
522 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
523 usage->blk[((y%r)*c+(x/r))*cr+n-1] = TRUE;
526 static int solver_elim(struct solver_usage *usage, int start, int step
527 #ifdef STANDALONE_SOLVER
532 int c = usage->c, r = usage->r, cr = c*r;
536 * Count the number of set bits within this section of the
541 for (i = 0; i < cr; i++)
542 if (usage->cube[start+i*step]) {
556 if (!usage->grid[YUNTRANS(y)*cr+x]) {
557 #ifdef STANDALONE_SOLVER
558 if (solver_show_working) {
560 printf("%*s", solver_recurse_depth*4, "");
564 printf(":\n%*s placing %d at (%d,%d)\n",
565 solver_recurse_depth*4, "", n, 1+x, 1+YUNTRANS(y));
568 solver_place(usage, x, y, n);
572 #ifdef STANDALONE_SOLVER
573 if (solver_show_working) {
575 printf("%*s", solver_recurse_depth*4, "");
579 printf(":\n%*s no possibilities available\n",
580 solver_recurse_depth*4, "");
589 static int solver_intersect(struct solver_usage *usage,
590 int start1, int step1, int start2, int step2
591 #ifdef STANDALONE_SOLVER
596 int c = usage->c, r = usage->r, cr = c*r;
600 * Loop over the first domain and see if there's any set bit
601 * not also in the second.
603 for (i = 0; i < cr; i++) {
604 int p = start1+i*step1;
605 if (usage->cube[p] &&
606 !(p >= start2 && p < start2+cr*step2 &&
607 (p - start2) % step2 == 0))
608 return 0; /* there is, so we can't deduce */
612 * We have determined that all set bits in the first domain are
613 * within its overlap with the second. So loop over the second
614 * domain and remove all set bits that aren't also in that
615 * overlap; return +1 iff we actually _did_ anything.
618 for (i = 0; i < cr; i++) {
619 int p = start2+i*step2;
620 if (usage->cube[p] &&
621 !(p >= start1 && p < start1+cr*step1 && (p - start1) % step1 == 0))
623 #ifdef STANDALONE_SOLVER
624 if (solver_show_working) {
629 printf("%*s", solver_recurse_depth*4, "");
641 printf("%*s ruling out %d at (%d,%d)\n",
642 solver_recurse_depth*4, "", pn, 1+px, 1+YUNTRANS(py));
645 ret = +1; /* we did something */
653 struct solver_scratch {
654 unsigned char *grid, *rowidx, *colidx, *set;
658 static int solver_set(struct solver_usage *usage,
659 struct solver_scratch *scratch,
660 int start, int step1, int step2
661 #ifdef STANDALONE_SOLVER
666 int c = usage->c, r = usage->r, cr = c*r;
668 unsigned char *grid = scratch->grid;
669 unsigned char *rowidx = scratch->rowidx;
670 unsigned char *colidx = scratch->colidx;
671 unsigned char *set = scratch->set;
674 * We are passed a cr-by-cr matrix of booleans. Our first job
675 * is to winnow it by finding any definite placements - i.e.
676 * any row with a solitary 1 - and discarding that row and the
677 * column containing the 1.
679 memset(rowidx, TRUE, cr);
680 memset(colidx, TRUE, cr);
681 for (i = 0; i < cr; i++) {
682 int count = 0, first = -1;
683 for (j = 0; j < cr; j++)
684 if (usage->cube[start+i*step1+j*step2])
688 * If count == 0, then there's a row with no 1s at all and
689 * the puzzle is internally inconsistent. However, we ought
690 * to have caught this already during the simpler reasoning
691 * methods, so we can safely fail an assertion if we reach
696 rowidx[i] = colidx[first] = FALSE;
700 * Convert each of rowidx/colidx from a list of 0s and 1s to a
701 * list of the indices of the 1s.
703 for (i = j = 0; i < cr; i++)
707 for (i = j = 0; i < cr; i++)
713 * And create the smaller matrix.
715 for (i = 0; i < n; i++)
716 for (j = 0; j < n; j++)
717 grid[i*cr+j] = usage->cube[start+rowidx[i]*step1+colidx[j]*step2];
720 * Having done that, we now have a matrix in which every row
721 * has at least two 1s in. Now we search to see if we can find
722 * a rectangle of zeroes (in the set-theoretic sense of
723 * `rectangle', i.e. a subset of rows crossed with a subset of
724 * columns) whose width and height add up to n.
731 * We have a candidate set. If its size is <=1 or >=n-1
732 * then we move on immediately.
734 if (count > 1 && count < n-1) {
736 * The number of rows we need is n-count. See if we can
737 * find that many rows which each have a zero in all
738 * the positions listed in `set'.
741 for (i = 0; i < n; i++) {
743 for (j = 0; j < n; j++)
744 if (set[j] && grid[i*cr+j]) {
753 * We expect never to be able to get _more_ than
754 * n-count suitable rows: this would imply that (for
755 * example) there are four numbers which between them
756 * have at most three possible positions, and hence it
757 * indicates a faulty deduction before this point or
760 if (rows > n - count) {
761 #ifdef STANDALONE_SOLVER
762 if (solver_show_working) {
764 printf("%*s", solver_recurse_depth*4,
769 printf(":\n%*s contradiction reached\n",
770 solver_recurse_depth*4, "");
776 if (rows >= n - count) {
777 int progress = FALSE;
780 * We've got one! Now, for each row which _doesn't_
781 * satisfy the criterion, eliminate all its set
782 * bits in the positions _not_ listed in `set'.
783 * Return +1 (meaning progress has been made) if we
784 * successfully eliminated anything at all.
786 * This involves referring back through
787 * rowidx/colidx in order to work out which actual
788 * positions in the cube to meddle with.
790 for (i = 0; i < n; i++) {
792 for (j = 0; j < n; j++)
793 if (set[j] && grid[i*cr+j]) {
798 for (j = 0; j < n; j++)
799 if (!set[j] && grid[i*cr+j]) {
800 int fpos = (start+rowidx[i]*step1+
802 #ifdef STANDALONE_SOLVER
803 if (solver_show_working) {
808 printf("%*s", solver_recurse_depth*4,
821 printf("%*s ruling out %d at (%d,%d)\n",
822 solver_recurse_depth*4, "",
823 pn, 1+px, 1+YUNTRANS(py));
827 usage->cube[fpos] = FALSE;
839 * Binary increment: change the rightmost 0 to a 1, and
840 * change all 1s to the right of it to 0s.
843 while (i > 0 && set[i-1])
844 set[--i] = 0, count--;
846 set[--i] = 1, count++;
855 * Try to find a number in the possible set of (x1,y1) which can be
856 * ruled out because it would leave no possibilities for (x2,y2).
858 static int solver_mne(struct solver_usage *usage,
859 struct solver_scratch *scratch,
860 int x1, int y1, int x2, int y2)
862 int c = usage->c, r = usage->r, cr = c*r;
864 unsigned char *set = scratch->set;
865 unsigned char *numbers = scratch->rowidx;
866 unsigned char *numbersleft = scratch->colidx;
870 nb[0] = scratch->mne;
871 nb[1] = scratch->mne + cr;
874 * First, work out the mutual neighbour squares of the two. We
875 * can assert that they're not actually in the same block,
876 * which leaves two possibilities: they're in different block
877 * rows _and_ different block columns (thus their mutual
878 * neighbours are precisely the other two corners of the
879 * rectangle), or they're in the same row (WLOG) and different
880 * columns, in which case their mutual neighbours are the
881 * column of each block aligned with the other square.
883 * We divide the mutual neighbours into two separate subsets
884 * nb[0] and nb[1]; squares in the same subset are not only
885 * adjacent to both our key squares, but are also always
886 * adjacent to one another.
888 if (x1 / r != x2 / r && y1 % r != y2 % r) {
889 /* Corners of the rectangle. */
891 nb[0][0] = cubepos(x2, y1, 1);
892 nb[1][0] = cubepos(x1, y2, 1);
893 } else if (x1 / r != x2 / r) {
894 /* Same row of blocks; different blocks within that row. */
895 int x1b = x1 - (x1 % r);
896 int x2b = x2 - (x2 % r);
899 for (i = 0; i < r; i++) {
900 nb[0][i] = cubepos(x2b+i, y1, 1);
901 nb[1][i] = cubepos(x1b+i, y2, 1);
904 /* Same column of blocks; different blocks within that column. */
908 assert(y1 % r != y2 % r);
911 for (i = 0; i < c; i++) {
912 nb[0][i] = cubepos(x2, y1b+i*r, 1);
913 nb[1][i] = cubepos(x1, y2b+i*r, 1);
918 * Right. Now loop over each possible number.
920 for (n = 1; n <= cr; n++) {
921 if (!cube(x1, y1, n))
923 for (j = 0; j < cr; j++)
924 numbersleft[j] = cube(x2, y2, j+1);
927 * Go over every possible subset of each neighbour list,
928 * and see if its union of possible numbers minus n has the
929 * same size as the subset. If so, add the numbers in that
930 * subset to the set of things which would be ruled out
931 * from (x2,y2) if n were placed at (x1,y1).
937 * Binary increment: change the rightmost 0 to a 1, and
938 * change all 1s to the right of it to 0s.
941 while (i > 0 && set[i-1])
942 set[--i] = 0, count--;
944 set[--i] = 1, count++;
949 * Examine this subset of each neighbour set.
951 for (nbi = 0; nbi < 2; nbi++) {
954 memset(numbers, 0, cr);
956 for (i = 0; i < nnb; i++)
958 for (j = 0; j < cr; j++)
959 if (j != n-1 && usage->cube[nbs[i] + j])
962 for (i = j = 0; j < cr; j++)
967 * Got one. This subset of nbs, in the absence
968 * of n, would definitely contain all the
969 * numbers listed in `numbers'. Rule them out
972 for (j = 0; j < cr; j++)
980 * If we've got nothing left in `numbersleft', we have a
981 * successful mutual neighbour elimination.
983 for (j = 0; j < cr; j++)
988 #ifdef STANDALONE_SOLVER
989 if (solver_show_working) {
990 printf("%*smutual neighbour elimination, (%d,%d) vs (%d,%d):\n",
991 solver_recurse_depth*4, "",
992 1+x1, 1+YUNTRANS(y1), 1+x2, 1+YUNTRANS(y2));
993 printf("%*s ruling out %d at (%d,%d)\n",
994 solver_recurse_depth*4, "",
995 n, 1+x1, 1+YUNTRANS(y1));
998 cube(x1, y1, n) = FALSE;
1003 return 0; /* nothing found */
1006 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1008 struct solver_scratch *scratch = snew(struct solver_scratch);
1010 scratch->grid = snewn(cr*cr, unsigned char);
1011 scratch->rowidx = snewn(cr, unsigned char);
1012 scratch->colidx = snewn(cr, unsigned char);
1013 scratch->set = snewn(cr, unsigned char);
1014 scratch->mne = snewn(2*cr, int);
1018 static void solver_free_scratch(struct solver_scratch *scratch)
1020 sfree(scratch->mne);
1021 sfree(scratch->set);
1022 sfree(scratch->colidx);
1023 sfree(scratch->rowidx);
1024 sfree(scratch->grid);
1028 static int solver(int c, int r, digit *grid, int maxdiff)
1030 struct solver_usage *usage;
1031 struct solver_scratch *scratch;
1033 int x, y, x2, y2, n, ret;
1034 int diff = DIFF_BLOCK;
1037 * Set up a usage structure as a clean slate (everything
1040 usage = snew(struct solver_usage);
1044 usage->cube = snewn(cr*cr*cr, unsigned char);
1045 usage->grid = grid; /* write straight back to the input */
1046 memset(usage->cube, TRUE, cr*cr*cr);
1048 usage->row = snewn(cr * cr, unsigned char);
1049 usage->col = snewn(cr * cr, unsigned char);
1050 usage->blk = snewn(cr * cr, unsigned char);
1051 memset(usage->row, FALSE, cr * cr);
1052 memset(usage->col, FALSE, cr * cr);
1053 memset(usage->blk, FALSE, cr * cr);
1055 scratch = solver_new_scratch(usage);
1058 * Place all the clue numbers we are given.
1060 for (x = 0; x < cr; x++)
1061 for (y = 0; y < cr; y++)
1063 solver_place(usage, x, YTRANS(y), grid[y*cr+x]);
1066 * Now loop over the grid repeatedly trying all permitted modes
1067 * of reasoning. The loop terminates if we complete an
1068 * iteration without making any progress; we then return
1069 * failure or success depending on whether the grid is full or
1074 * I'd like to write `continue;' inside each of the
1075 * following loops, so that the solver returns here after
1076 * making some progress. However, I can't specify that I
1077 * want to continue an outer loop rather than the innermost
1078 * one, so I'm apologetically resorting to a goto.
1083 * Blockwise positional elimination.
1085 for (x = 0; x < cr; x += r)
1086 for (y = 0; y < r; y++)
1087 for (n = 1; n <= cr; n++)
1088 if (!usage->blk[(y*c+(x/r))*cr+n-1]) {
1089 ret = solver_elim(usage, cubepos(x,y,n), r*cr
1090 #ifdef STANDALONE_SOLVER
1091 , "positional elimination,"
1092 " %d in block (%d,%d)", n, 1+x/r, 1+y
1096 diff = DIFF_IMPOSSIBLE;
1098 } else if (ret > 0) {
1099 diff = max(diff, DIFF_BLOCK);
1104 if (maxdiff <= DIFF_BLOCK)
1108 * Row-wise positional elimination.
1110 for (y = 0; y < cr; y++)
1111 for (n = 1; n <= cr; n++)
1112 if (!usage->row[y*cr+n-1]) {
1113 ret = solver_elim(usage, cubepos(0,y,n), cr*cr
1114 #ifdef STANDALONE_SOLVER
1115 , "positional elimination,"
1116 " %d in row %d", n, 1+YUNTRANS(y)
1120 diff = DIFF_IMPOSSIBLE;
1122 } else if (ret > 0) {
1123 diff = max(diff, DIFF_SIMPLE);
1128 * Column-wise positional elimination.
1130 for (x = 0; x < cr; x++)
1131 for (n = 1; n <= cr; n++)
1132 if (!usage->col[x*cr+n-1]) {
1133 ret = solver_elim(usage, cubepos(x,0,n), cr
1134 #ifdef STANDALONE_SOLVER
1135 , "positional elimination,"
1136 " %d in column %d", n, 1+x
1140 diff = DIFF_IMPOSSIBLE;
1142 } else if (ret > 0) {
1143 diff = max(diff, DIFF_SIMPLE);
1149 * Numeric elimination.
1151 for (x = 0; x < cr; x++)
1152 for (y = 0; y < cr; y++)
1153 if (!usage->grid[YUNTRANS(y)*cr+x]) {
1154 ret = solver_elim(usage, cubepos(x,y,1), 1
1155 #ifdef STANDALONE_SOLVER
1156 , "numeric elimination at (%d,%d)", 1+x,
1161 diff = DIFF_IMPOSSIBLE;
1163 } else if (ret > 0) {
1164 diff = max(diff, DIFF_SIMPLE);
1169 if (maxdiff <= DIFF_SIMPLE)
1173 * Intersectional analysis, rows vs blocks.
1175 for (y = 0; y < cr; y++)
1176 for (x = 0; x < cr; x += r)
1177 for (n = 1; n <= cr; n++)
1179 * solver_intersect() never returns -1.
1181 if (!usage->row[y*cr+n-1] &&
1182 !usage->blk[((y%r)*c+(x/r))*cr+n-1] &&
1183 (solver_intersect(usage, cubepos(0,y,n), cr*cr,
1184 cubepos(x,y%r,n), r*cr
1185 #ifdef STANDALONE_SOLVER
1186 , "intersectional analysis,"
1187 " %d in row %d vs block (%d,%d)",
1188 n, 1+YUNTRANS(y), 1+x/r, 1+y%r
1191 solver_intersect(usage, cubepos(x,y%r,n), r*cr,
1192 cubepos(0,y,n), cr*cr
1193 #ifdef STANDALONE_SOLVER
1194 , "intersectional analysis,"
1195 " %d in block (%d,%d) vs row %d",
1196 n, 1+x/r, 1+y%r, 1+YUNTRANS(y)
1199 diff = max(diff, DIFF_INTERSECT);
1204 * Intersectional analysis, columns vs blocks.
1206 for (x = 0; x < cr; x++)
1207 for (y = 0; y < r; y++)
1208 for (n = 1; n <= cr; n++)
1209 if (!usage->col[x*cr+n-1] &&
1210 !usage->blk[(y*c+(x/r))*cr+n-1] &&
1211 (solver_intersect(usage, cubepos(x,0,n), cr,
1212 cubepos((x/r)*r,y,n), r*cr
1213 #ifdef STANDALONE_SOLVER
1214 , "intersectional analysis,"
1215 " %d in column %d vs block (%d,%d)",
1219 solver_intersect(usage, cubepos((x/r)*r,y,n), r*cr,
1221 #ifdef STANDALONE_SOLVER
1222 , "intersectional analysis,"
1223 " %d in block (%d,%d) vs column %d",
1227 diff = max(diff, DIFF_INTERSECT);
1231 if (maxdiff <= DIFF_INTERSECT)
1235 * Blockwise set elimination.
1237 for (x = 0; x < cr; x += r)
1238 for (y = 0; y < r; y++) {
1239 ret = solver_set(usage, scratch, cubepos(x,y,1), r*cr, 1
1240 #ifdef STANDALONE_SOLVER
1241 , "set elimination, block (%d,%d)", 1+x/r, 1+y
1245 diff = DIFF_IMPOSSIBLE;
1247 } else if (ret > 0) {
1248 diff = max(diff, DIFF_SET);
1254 * Row-wise set elimination.
1256 for (y = 0; y < cr; y++) {
1257 ret = solver_set(usage, scratch, cubepos(0,y,1), cr*cr, 1
1258 #ifdef STANDALONE_SOLVER
1259 , "set elimination, row %d", 1+YUNTRANS(y)
1263 diff = DIFF_IMPOSSIBLE;
1265 } else if (ret > 0) {
1266 diff = max(diff, DIFF_SET);
1272 * Column-wise set elimination.
1274 for (x = 0; x < cr; x++) {
1275 ret = solver_set(usage, scratch, cubepos(x,0,1), cr, 1
1276 #ifdef STANDALONE_SOLVER
1277 , "set elimination, column %d", 1+x
1281 diff = DIFF_IMPOSSIBLE;
1283 } else if (ret > 0) {
1284 diff = max(diff, DIFF_SET);
1290 * Mutual neighbour elimination.
1292 for (y = 0; y+1 < cr; y++) {
1293 for (x = 0; x+1 < cr; x++) {
1294 for (y2 = y+1; y2 < cr; y2++) {
1295 for (x2 = x+1; x2 < cr; x2++) {
1297 * Can't do mutual neighbour elimination
1298 * between elements of the same actual
1301 if (x/r == x2/r && y%r == y2%r)
1305 * Otherwise, try (x,y) vs (x2,y2) in both
1306 * directions, and likewise (x2,y) vs
1309 if (!usage->grid[YUNTRANS(y)*cr+x] &&
1310 !usage->grid[YUNTRANS(y2)*cr+x2] &&
1311 (solver_mne(usage, scratch, x, y, x2, y2) ||
1312 solver_mne(usage, scratch, x2, y2, x, y))) {
1313 diff = max(diff, DIFF_NEIGHBOUR);
1316 if (!usage->grid[YUNTRANS(y)*cr+x2] &&
1317 !usage->grid[YUNTRANS(y2)*cr+x] &&
1318 (solver_mne(usage, scratch, x2, y, x, y2) ||
1319 solver_mne(usage, scratch, x, y2, x2, y))) {
1320 diff = max(diff, DIFF_NEIGHBOUR);
1329 * If we reach here, we have made no deductions in this
1330 * iteration, so the algorithm terminates.
1336 * Last chance: if we haven't fully solved the puzzle yet, try
1337 * recursing based on guesses for a particular square. We pick
1338 * one of the most constrained empty squares we can find, which
1339 * has the effect of pruning the search tree as much as
1342 if (maxdiff >= DIFF_RECURSIVE) {
1343 int best, bestcount;
1348 for (y = 0; y < cr; y++)
1349 for (x = 0; x < cr; x++)
1350 if (!grid[y*cr+x]) {
1354 * An unfilled square. Count the number of
1355 * possible digits in it.
1358 for (n = 1; n <= cr; n++)
1359 if (cube(x,YTRANS(y),n))
1363 * We should have found any impossibilities
1364 * already, so this can safely be an assert.
1368 if (count < bestcount) {
1376 digit *list, *ingrid, *outgrid;
1378 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
1381 * Attempt recursion.
1386 list = snewn(cr, digit);
1387 ingrid = snewn(cr * cr, digit);
1388 outgrid = snewn(cr * cr, digit);
1389 memcpy(ingrid, grid, cr * cr);
1391 /* Make a list of the possible digits. */
1392 for (j = 0, n = 1; n <= cr; n++)
1393 if (cube(x,YTRANS(y),n))
1396 #ifdef STANDALONE_SOLVER
1397 if (solver_show_working) {
1399 printf("%*srecursing on (%d,%d) [",
1400 solver_recurse_depth*4, "", x, y);
1401 for (i = 0; i < j; i++) {
1402 printf("%s%d", sep, list[i]);
1410 * And step along the list, recursing back into the
1411 * main solver at every stage.
1413 for (i = 0; i < j; i++) {
1416 memcpy(outgrid, ingrid, cr * cr);
1417 outgrid[y*cr+x] = list[i];
1419 #ifdef STANDALONE_SOLVER
1420 if (solver_show_working)
1421 printf("%*sguessing %d at (%d,%d)\n",
1422 solver_recurse_depth*4, "", list[i], x, y);
1423 solver_recurse_depth++;
1426 ret = solver(c, r, outgrid, maxdiff);
1428 #ifdef STANDALONE_SOLVER
1429 solver_recurse_depth--;
1430 if (solver_show_working) {
1431 printf("%*sretracting %d at (%d,%d)\n",
1432 solver_recurse_depth*4, "", list[i], x, y);
1437 * If we have our first solution, copy it into the
1438 * grid we will return.
1440 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1441 memcpy(grid, outgrid, cr*cr);
1443 if (ret == DIFF_AMBIGUOUS)
1444 diff = DIFF_AMBIGUOUS;
1445 else if (ret == DIFF_IMPOSSIBLE)
1446 /* do not change our return value */;
1448 /* the recursion turned up exactly one solution */
1449 if (diff == DIFF_IMPOSSIBLE)
1450 diff = DIFF_RECURSIVE;
1452 diff = DIFF_AMBIGUOUS;
1456 * As soon as we've found more than one solution,
1457 * give up immediately.
1459 if (diff == DIFF_AMBIGUOUS)
1470 * We're forbidden to use recursion, so we just see whether
1471 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1474 for (y = 0; y < cr; y++)
1475 for (x = 0; x < cr; x++)
1477 diff = DIFF_IMPOSSIBLE;
1482 #ifdef STANDALONE_SOLVER
1483 if (solver_show_working)
1484 printf("%*s%s found\n",
1485 solver_recurse_depth*4, "",
1486 diff == DIFF_IMPOSSIBLE ? "no solution" :
1487 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1497 solver_free_scratch(scratch);
1502 /* ----------------------------------------------------------------------
1503 * End of solver code.
1506 /* ----------------------------------------------------------------------
1507 * Solo filled-grid generator.
1509 * This grid generator works by essentially trying to solve a grid
1510 * starting from no clues, and not worrying that there's more than
1511 * one possible solution. Unfortunately, it isn't computationally
1512 * feasible to do this by calling the above solver with an empty
1513 * grid, because that one needs to allocate a lot of scratch space
1514 * at every recursion level. Instead, I have a much simpler
1515 * algorithm which I shamelessly copied from a Python solver
1516 * written by Andrew Wilkinson (which is GPLed, but I've reused
1517 * only ideas and no code). It mostly just does the obvious
1518 * recursive thing: pick an empty square, put one of the possible
1519 * digits in it, recurse until all squares are filled, backtrack
1520 * and change some choices if necessary.
1522 * The clever bit is that every time it chooses which square to
1523 * fill in next, it does so by counting the number of _possible_
1524 * numbers that can go in each square, and it prioritises so that
1525 * it picks a square with the _lowest_ number of possibilities. The
1526 * idea is that filling in lots of the obvious bits (particularly
1527 * any squares with only one possibility) will cut down on the list
1528 * of possibilities for other squares and hence reduce the enormous
1529 * search space as much as possible as early as possible.
1533 * Internal data structure used in gridgen to keep track of
1536 struct gridgen_coord { int x, y, r; };
1537 struct gridgen_usage {
1538 int c, r, cr; /* cr == c*r */
1539 /* grid is a copy of the input grid, modified as we go along */
1541 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1543 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1545 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1547 /* This lists all the empty spaces remaining in the grid. */
1548 struct gridgen_coord *spaces;
1550 /* If we need randomisation in the solve, this is our random state. */
1555 * The real recursive step in the generating function.
1557 static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1559 int c = usage->c, r = usage->r, cr = usage->cr;
1560 int i, j, n, sx, sy, bestm, bestr, ret;
1564 * Firstly, check for completion! If there are no spaces left
1565 * in the grid, we have a solution.
1567 if (usage->nspaces == 0) {
1568 memcpy(grid, usage->grid, cr * cr);
1573 * Otherwise, there must be at least one space. Find the most
1574 * constrained space, using the `r' field as a tie-breaker.
1576 bestm = cr+1; /* so that any space will beat it */
1579 for (j = 0; j < usage->nspaces; j++) {
1580 int x = usage->spaces[j].x, y = usage->spaces[j].y;
1584 * Find the number of digits that could go in this space.
1587 for (n = 0; n < cr; n++)
1588 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1589 !usage->blk[((y/c)*c+(x/r))*cr+n])
1592 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1594 bestr = usage->spaces[j].r;
1602 * Swap that square into the final place in the spaces array,
1603 * so that decrementing nspaces will remove it from the list.
1605 if (i != usage->nspaces-1) {
1606 struct gridgen_coord t;
1607 t = usage->spaces[usage->nspaces-1];
1608 usage->spaces[usage->nspaces-1] = usage->spaces[i];
1609 usage->spaces[i] = t;
1613 * Now we've decided which square to start our recursion at,
1614 * simply go through all possible values, shuffling them
1615 * randomly first if necessary.
1617 digits = snewn(bestm, int);
1619 for (n = 0; n < cr; n++)
1620 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1621 !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
1626 shuffle(digits, j, sizeof(*digits), usage->rs);
1628 /* And finally, go through the digit list and actually recurse. */
1630 for (i = 0; i < j; i++) {
1633 /* Update the usage structure to reflect the placing of this digit. */
1634 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1635 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
1636 usage->grid[sy*cr+sx] = n;
1639 /* Call the solver recursively. Stop when we find a solution. */
1640 if (gridgen_real(usage, grid))
1643 /* Revert the usage structure. */
1644 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1645 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
1646 usage->grid[sy*cr+sx] = 0;
1658 * Entry point to generator. You give it dimensions and a starting
1659 * grid, which is simply an array of cr*cr digits.
1661 static void gridgen(int c, int r, digit *grid, random_state *rs)
1663 struct gridgen_usage *usage;
1667 * Clear the grid to start with.
1669 memset(grid, 0, cr*cr);
1672 * Create a gridgen_usage structure.
1674 usage = snew(struct gridgen_usage);
1680 usage->grid = snewn(cr * cr, digit);
1681 memcpy(usage->grid, grid, cr * cr);
1683 usage->row = snewn(cr * cr, unsigned char);
1684 usage->col = snewn(cr * cr, unsigned char);
1685 usage->blk = snewn(cr * cr, unsigned char);
1686 memset(usage->row, FALSE, cr * cr);
1687 memset(usage->col, FALSE, cr * cr);
1688 memset(usage->blk, FALSE, cr * cr);
1690 usage->spaces = snewn(cr * cr, struct gridgen_coord);
1696 * Initialise the list of grid spaces.
1698 for (y = 0; y < cr; y++) {
1699 for (x = 0; x < cr; x++) {
1700 usage->spaces[usage->nspaces].x = x;
1701 usage->spaces[usage->nspaces].y = y;
1702 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
1708 * Run the real generator function.
1710 gridgen_real(usage, grid);
1713 * Clean up the usage structure now we have our answer.
1715 sfree(usage->spaces);
1723 /* ----------------------------------------------------------------------
1724 * End of grid generator code.
1728 * Check whether a grid contains a valid complete puzzle.
1730 static int check_valid(int c, int r, digit *grid)
1733 unsigned char *used;
1736 used = snewn(cr, unsigned char);
1739 * Check that each row contains precisely one of everything.
1741 for (y = 0; y < cr; y++) {
1742 memset(used, FALSE, cr);
1743 for (x = 0; x < cr; x++)
1744 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1745 used[grid[y*cr+x]-1] = TRUE;
1746 for (n = 0; n < cr; n++)
1754 * Check that each column contains precisely one of everything.
1756 for (x = 0; x < cr; x++) {
1757 memset(used, FALSE, cr);
1758 for (y = 0; y < cr; y++)
1759 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1760 used[grid[y*cr+x]-1] = TRUE;
1761 for (n = 0; n < cr; n++)
1769 * Check that each block contains precisely one of everything.
1771 for (x = 0; x < cr; x += r) {
1772 for (y = 0; y < cr; y += c) {
1774 memset(used, FALSE, cr);
1775 for (xx = x; xx < x+r; xx++)
1776 for (yy = 0; yy < y+c; yy++)
1777 if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
1778 used[grid[yy*cr+xx]-1] = TRUE;
1779 for (n = 0; n < cr; n++)
1791 static int symmetries(game_params *params, int x, int y, int *output, int s)
1793 int c = params->c, r = params->r, cr = c*r;
1796 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
1802 break; /* just x,y is all we need */
1804 ADD(cr - 1 - x, cr - 1 - y);
1809 ADD(cr - 1 - x, cr - 1 - y);
1820 ADD(cr - 1 - x, cr - 1 - y);
1824 ADD(cr - 1 - x, cr - 1 - y);
1825 ADD(cr - 1 - y, cr - 1 - x);
1830 ADD(cr - 1 - x, cr - 1 - y);
1834 ADD(cr - 1 - y, cr - 1 - x);
1843 static char *encode_solve_move(int cr, digit *grid)
1846 char *ret, *p, *sep;
1849 * It's surprisingly easy to work out _exactly_ how long this
1850 * string needs to be. To decimal-encode all the numbers from 1
1853 * - every number has a units digit; total is n.
1854 * - all numbers above 9 have a tens digit; total is max(n-9,0).
1855 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
1859 for (i = 1; i <= cr; i *= 10)
1860 len += max(cr - i + 1, 0);
1861 len += cr; /* don't forget the commas */
1862 len *= cr; /* there are cr rows of these */
1865 * Now len is one bigger than the total size of the
1866 * comma-separated numbers (because we counted an
1867 * additional leading comma). We need to have a leading S
1868 * and a trailing NUL, so we're off by one in total.
1872 ret = snewn(len, char);
1876 for (i = 0; i < cr*cr; i++) {
1877 p += sprintf(p, "%s%d", sep, grid[i]);
1881 assert(p - ret == len);
1886 static char *new_game_desc(game_params *params, random_state *rs,
1887 char **aux, int interactive)
1889 int c = params->c, r = params->r, cr = c*r;
1891 digit *grid, *grid2;
1892 struct xy { int x, y; } *locs;
1895 int coords[16], ncoords;
1900 * Adjust the maximum difficulty level to be consistent with
1901 * the puzzle size: all 2x2 puzzles appear to be Trivial
1902 * (DIFF_BLOCK) so we cannot hold out for even a Basic
1903 * (DIFF_SIMPLE) one.
1905 maxdiff = params->diff;
1906 if (c == 2 && r == 2)
1907 maxdiff = DIFF_BLOCK;
1909 grid = snewn(area, digit);
1910 locs = snewn(area, struct xy);
1911 grid2 = snewn(area, digit);
1914 * Loop until we get a grid of the required difficulty. This is
1915 * nasty, but it seems to be unpleasantly hard to generate
1916 * difficult grids otherwise.
1920 * Generate a random solved state.
1922 gridgen(c, r, grid, rs);
1923 assert(check_valid(c, r, grid));
1926 * Save the solved grid in aux.
1930 * We might already have written *aux the last time we
1931 * went round this loop, in which case we should free
1932 * the old aux before overwriting it with the new one.
1938 *aux = encode_solve_move(cr, grid);
1942 * Now we have a solved grid, start removing things from it
1943 * while preserving solubility.
1947 * Find the set of equivalence classes of squares permitted
1948 * by the selected symmetry. We do this by enumerating all
1949 * the grid squares which have no symmetric companion
1950 * sorting lower than themselves.
1953 for (y = 0; y < cr; y++)
1954 for (x = 0; x < cr; x++) {
1958 ncoords = symmetries(params, x, y, coords, params->symm);
1959 for (j = 0; j < ncoords; j++)
1960 if (coords[2*j+1]*cr+coords[2*j] < i)
1970 * Now shuffle that list.
1972 shuffle(locs, nlocs, sizeof(*locs), rs);
1975 * Now loop over the shuffled list and, for each element,
1976 * see whether removing that element (and its reflections)
1977 * from the grid will still leave the grid soluble.
1979 for (i = 0; i < nlocs; i++) {
1985 memcpy(grid2, grid, area);
1986 ncoords = symmetries(params, x, y, coords, params->symm);
1987 for (j = 0; j < ncoords; j++)
1988 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1990 ret = solver(c, r, grid2, maxdiff);
1991 if (ret != DIFF_IMPOSSIBLE && ret != DIFF_AMBIGUOUS) {
1992 for (j = 0; j < ncoords; j++)
1993 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1997 memcpy(grid2, grid, area);
1998 } while (solver(c, r, grid2, maxdiff) < maxdiff);
2004 * Now we have the grid as it will be presented to the user.
2005 * Encode it in a game desc.
2011 desc = snewn(5 * area, char);
2014 for (i = 0; i <= area; i++) {
2015 int n = (i < area ? grid[i] : -1);
2022 int c = 'a' - 1 + run;
2026 run -= c - ('a' - 1);
2030 * If there's a number in the very top left or
2031 * bottom right, there's no point putting an
2032 * unnecessary _ before or after it.
2034 if (p > desc && n > 0)
2038 p += sprintf(p, "%d", n);
2042 assert(p - desc < 5 * area);
2044 desc = sresize(desc, p - desc, char);
2052 static char *validate_desc(game_params *params, char *desc)
2054 int area = params->r * params->r * params->c * params->c;
2059 if (n >= 'a' && n <= 'z') {
2060 squares += n - 'a' + 1;
2061 } else if (n == '_') {
2063 } else if (n > '0' && n <= '9') {
2065 while (*desc >= '0' && *desc <= '9')
2068 return "Invalid character in game description";
2072 return "Not enough data to fill grid";
2075 return "Too much data to fit in grid";
2080 static game_state *new_game(midend *me, game_params *params, char *desc)
2082 game_state *state = snew(game_state);
2083 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2086 state->c = params->c;
2087 state->r = params->r;
2089 state->grid = snewn(area, digit);
2090 state->pencil = snewn(area * cr, unsigned char);
2091 memset(state->pencil, 0, area * cr);
2092 state->immutable = snewn(area, unsigned char);
2093 memset(state->immutable, FALSE, area);
2095 state->completed = state->cheated = FALSE;
2100 if (n >= 'a' && n <= 'z') {
2101 int run = n - 'a' + 1;
2102 assert(i + run <= area);
2104 state->grid[i++] = 0;
2105 } else if (n == '_') {
2107 } else if (n > '0' && n <= '9') {
2109 state->immutable[i] = TRUE;
2110 state->grid[i++] = atoi(desc-1);
2111 while (*desc >= '0' && *desc <= '9')
2114 assert(!"We can't get here");
2122 static game_state *dup_game(game_state *state)
2124 game_state *ret = snew(game_state);
2125 int c = state->c, r = state->r, cr = c*r, area = cr * cr;
2130 ret->grid = snewn(area, digit);
2131 memcpy(ret->grid, state->grid, area);
2133 ret->pencil = snewn(area * cr, unsigned char);
2134 memcpy(ret->pencil, state->pencil, area * cr);
2136 ret->immutable = snewn(area, unsigned char);
2137 memcpy(ret->immutable, state->immutable, area);
2139 ret->completed = state->completed;
2140 ret->cheated = state->cheated;
2145 static void free_game(game_state *state)
2147 sfree(state->immutable);
2148 sfree(state->pencil);
2153 static char *solve_game(game_state *state, game_state *currstate,
2154 char *ai, char **error)
2156 int c = state->c, r = state->r, cr = c*r;
2162 * If we already have the solution in ai, save ourselves some
2168 grid = snewn(cr*cr, digit);
2169 memcpy(grid, state->grid, cr*cr);
2170 solve_ret = solver(c, r, grid, DIFF_RECURSIVE);
2174 if (solve_ret == DIFF_IMPOSSIBLE)
2175 *error = "No solution exists for this puzzle";
2176 else if (solve_ret == DIFF_AMBIGUOUS)
2177 *error = "Multiple solutions exist for this puzzle";
2184 ret = encode_solve_move(cr, grid);
2191 static char *grid_text_format(int c, int r, digit *grid)
2199 * There are cr lines of digits, plus r-1 lines of block
2200 * separators. Each line contains cr digits, cr-1 separating
2201 * spaces, and c-1 two-character block separators. Thus, the
2202 * total length of a line is 2*cr+2*c-3 (not counting the
2203 * newline), and there are cr+r-1 of them.
2205 maxlen = (cr+r-1) * (2*cr+2*c-2);
2206 ret = snewn(maxlen+1, char);
2209 for (y = 0; y < cr; y++) {
2210 for (x = 0; x < cr; x++) {
2211 int ch = grid[y * cr + x];
2221 if ((x+1) % r == 0) {
2228 if (y+1 < cr && (y+1) % c == 0) {
2229 for (x = 0; x < cr; x++) {
2233 if ((x+1) % r == 0) {
2243 assert(p - ret == maxlen);
2248 static char *game_text_format(game_state *state)
2250 return grid_text_format(state->c, state->r, state->grid);
2255 * These are the coordinates of the currently highlighted
2256 * square on the grid, or -1,-1 if there isn't one. When there
2257 * is, pressing a valid number or letter key or Space will
2258 * enter that number or letter in the grid.
2262 * This indicates whether the current highlight is a
2263 * pencil-mark one or a real one.
2268 static game_ui *new_ui(game_state *state)
2270 game_ui *ui = snew(game_ui);
2272 ui->hx = ui->hy = -1;
2278 static void free_ui(game_ui *ui)
2283 static char *encode_ui(game_ui *ui)
2288 static void decode_ui(game_ui *ui, char *encoding)
2292 static void game_changed_state(game_ui *ui, game_state *oldstate,
2293 game_state *newstate)
2295 int c = newstate->c, r = newstate->r, cr = c*r;
2297 * We prevent pencil-mode highlighting of a filled square. So
2298 * if the user has just filled in a square which we had a
2299 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
2300 * then we cancel the highlight.
2302 if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
2303 newstate->grid[ui->hy * cr + ui->hx] != 0) {
2304 ui->hx = ui->hy = -1;
2308 struct game_drawstate {
2313 unsigned char *pencil;
2315 /* This is scratch space used within a single call to game_redraw. */
2319 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2320 int x, int y, int button)
2322 int c = state->c, r = state->r, cr = c*r;
2326 button &= ~MOD_MASK;
2328 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2329 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2331 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
2332 if (button == LEFT_BUTTON) {
2333 if (state->immutable[ty*cr+tx]) {
2334 ui->hx = ui->hy = -1;
2335 } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
2336 ui->hx = ui->hy = -1;
2342 return ""; /* UI activity occurred */
2344 if (button == RIGHT_BUTTON) {
2346 * Pencil-mode highlighting for non filled squares.
2348 if (state->grid[ty*cr+tx] == 0) {
2349 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
2350 ui->hx = ui->hy = -1;
2357 ui->hx = ui->hy = -1;
2359 return ""; /* UI activity occurred */
2363 if (ui->hx != -1 && ui->hy != -1 &&
2364 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
2365 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
2366 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
2367 button == ' ' || button == '\010' || button == '\177')) {
2368 int n = button - '0';
2369 if (button >= 'A' && button <= 'Z')
2370 n = button - 'A' + 10;
2371 if (button >= 'a' && button <= 'z')
2372 n = button - 'a' + 10;
2373 if (button == ' ' || button == '\010' || button == '\177')
2377 * Can't overwrite this square. In principle this shouldn't
2378 * happen anyway because we should never have even been
2379 * able to highlight the square, but it never hurts to be
2382 if (state->immutable[ui->hy*cr+ui->hx])
2386 * Can't make pencil marks in a filled square. In principle
2387 * this shouldn't happen anyway because we should never
2388 * have even been able to pencil-highlight the square, but
2389 * it never hurts to be careful.
2391 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
2394 sprintf(buf, "%c%d,%d,%d",
2395 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
2397 ui->hx = ui->hy = -1;
2405 static game_state *execute_move(game_state *from, char *move)
2407 int c = from->c, r = from->r, cr = c*r;
2411 if (move[0] == 'S') {
2414 ret = dup_game(from);
2415 ret->completed = ret->cheated = TRUE;
2418 for (n = 0; n < cr*cr; n++) {
2419 ret->grid[n] = atoi(p);
2421 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
2426 while (*p && isdigit((unsigned char)*p)) p++;
2431 } else if ((move[0] == 'P' || move[0] == 'R') &&
2432 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
2433 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
2435 ret = dup_game(from);
2436 if (move[0] == 'P' && n > 0) {
2437 int index = (y*cr+x) * cr + (n-1);
2438 ret->pencil[index] = !ret->pencil[index];
2440 ret->grid[y*cr+x] = n;
2441 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
2444 * We've made a real change to the grid. Check to see
2445 * if the game has been completed.
2447 if (!ret->completed && check_valid(c, r, ret->grid)) {
2448 ret->completed = TRUE;
2453 return NULL; /* couldn't parse move string */
2456 /* ----------------------------------------------------------------------
2460 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
2461 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
2463 static void game_compute_size(game_params *params, int tilesize,
2466 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2467 struct { int tilesize; } ads, *ds = &ads;
2468 ads.tilesize = tilesize;
2470 *x = SIZE(params->c * params->r);
2471 *y = SIZE(params->c * params->r);
2474 static void game_set_size(drawing *dr, game_drawstate *ds,
2475 game_params *params, int tilesize)
2477 ds->tilesize = tilesize;
2480 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2482 float *ret = snewn(3 * NCOLOURS, float);
2484 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2486 ret[COL_GRID * 3 + 0] = 0.0F;
2487 ret[COL_GRID * 3 + 1] = 0.0F;
2488 ret[COL_GRID * 3 + 2] = 0.0F;
2490 ret[COL_CLUE * 3 + 0] = 0.0F;
2491 ret[COL_CLUE * 3 + 1] = 0.0F;
2492 ret[COL_CLUE * 3 + 2] = 0.0F;
2494 ret[COL_USER * 3 + 0] = 0.0F;
2495 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
2496 ret[COL_USER * 3 + 2] = 0.0F;
2498 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
2499 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
2500 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
2502 ret[COL_ERROR * 3 + 0] = 1.0F;
2503 ret[COL_ERROR * 3 + 1] = 0.0F;
2504 ret[COL_ERROR * 3 + 2] = 0.0F;
2506 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2507 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2508 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
2510 *ncolours = NCOLOURS;
2514 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2516 struct game_drawstate *ds = snew(struct game_drawstate);
2517 int c = state->c, r = state->r, cr = c*r;
2519 ds->started = FALSE;
2523 ds->grid = snewn(cr*cr, digit);
2524 memset(ds->grid, 0, cr*cr);
2525 ds->pencil = snewn(cr*cr*cr, digit);
2526 memset(ds->pencil, 0, cr*cr*cr);
2527 ds->hl = snewn(cr*cr, unsigned char);
2528 memset(ds->hl, 0, cr*cr);
2529 ds->entered_items = snewn(cr*cr, int);
2530 ds->tilesize = 0; /* not decided yet */
2534 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2539 sfree(ds->entered_items);
2543 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
2544 int x, int y, int hl)
2546 int c = state->c, r = state->r, cr = c*r;
2551 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
2552 ds->hl[y*cr+x] == hl &&
2553 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
2554 return; /* no change required */
2556 tx = BORDER + x * TILE_SIZE + 2;
2557 ty = BORDER + y * TILE_SIZE + 2;
2573 clip(dr, cx, cy, cw, ch);
2575 /* background needs erasing */
2576 draw_rect(dr, cx, cy, cw, ch, (hl & 15) == 1 ? COL_HIGHLIGHT : COL_BACKGROUND);
2578 /* pencil-mode highlight */
2579 if ((hl & 15) == 2) {
2583 coords[2] = cx+cw/2;
2586 coords[5] = cy+ch/2;
2587 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
2590 /* new number needs drawing? */
2591 if (state->grid[y*cr+x]) {
2593 str[0] = state->grid[y*cr+x] + '0';
2595 str[0] += 'a' - ('9'+1);
2596 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
2597 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
2598 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
2601 int pw, ph, pmax, fontsize;
2603 /* count the pencil marks required */
2604 for (i = npencil = 0; i < cr; i++)
2605 if (state->pencil[(y*cr+x)*cr+i])
2609 * It's not sensible to arrange pencil marks in the same
2610 * layout as the squares within a block, because this leads
2611 * to the font being too small. Instead, we arrange pencil
2612 * marks in the nearest thing we can to a square layout,
2613 * and we adjust the square layout depending on the number
2614 * of pencil marks in the square.
2616 for (pw = 1; pw * pw < npencil; pw++);
2617 if (pw < 3) pw = 3; /* otherwise it just looks _silly_ */
2618 ph = (npencil + pw - 1) / pw;
2619 if (ph < 2) ph = 2; /* likewise */
2621 fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
2623 for (i = j = 0; i < cr; i++)
2624 if (state->pencil[(y*cr+x)*cr+i]) {
2625 int dx = j % pw, dy = j / pw;
2630 str[0] += 'a' - ('9'+1);
2631 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
2632 ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
2633 FONT_VARIABLE, fontsize,
2634 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
2641 draw_update(dr, cx, cy, cw, ch);
2643 ds->grid[y*cr+x] = state->grid[y*cr+x];
2644 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
2645 ds->hl[y*cr+x] = hl;
2648 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2649 game_state *state, int dir, game_ui *ui,
2650 float animtime, float flashtime)
2652 int c = state->c, r = state->r, cr = c*r;
2657 * The initial contents of the window are not guaranteed
2658 * and can vary with front ends. To be on the safe side,
2659 * all games should start by drawing a big
2660 * background-colour rectangle covering the whole window.
2662 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
2667 for (x = 0; x <= cr; x++) {
2668 int thick = (x % r ? 0 : 1);
2669 draw_rect(dr, BORDER + x*TILE_SIZE - thick, BORDER-1,
2670 1+2*thick, cr*TILE_SIZE+3, COL_GRID);
2672 for (y = 0; y <= cr; y++) {
2673 int thick = (y % c ? 0 : 1);
2674 draw_rect(dr, BORDER-1, BORDER + y*TILE_SIZE - thick,
2675 cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
2680 * This array is used to keep track of rows, columns and boxes
2681 * which contain a number more than once.
2683 for (x = 0; x < cr * cr; x++)
2684 ds->entered_items[x] = 0;
2685 for (x = 0; x < cr; x++)
2686 for (y = 0; y < cr; y++) {
2687 digit d = state->grid[y*cr+x];
2689 int box = (x/r)+(y/c)*c;
2690 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
2691 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
2692 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
2697 * Draw any numbers which need redrawing.
2699 for (x = 0; x < cr; x++) {
2700 for (y = 0; y < cr; y++) {
2702 digit d = state->grid[y*cr+x];
2704 if (flashtime > 0 &&
2705 (flashtime <= FLASH_TIME/3 ||
2706 flashtime >= FLASH_TIME*2/3))
2709 /* Highlight active input areas. */
2710 if (x == ui->hx && y == ui->hy)
2711 highlight = ui->hpencil ? 2 : 1;
2713 /* Mark obvious errors (ie, numbers which occur more than once
2714 * in a single row, column, or box). */
2715 if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
2716 (ds->entered_items[y*cr+d-1] & 8) ||
2717 (ds->entered_items[((x/r)+(y/c)*c)*cr+d-1] & 32)))
2720 draw_number(dr, ds, state, x, y, highlight);
2725 * Update the _entire_ grid if necessary.
2728 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
2733 static float game_anim_length(game_state *oldstate, game_state *newstate,
2734 int dir, game_ui *ui)
2739 static float game_flash_length(game_state *oldstate, game_state *newstate,
2740 int dir, game_ui *ui)
2742 if (!oldstate->completed && newstate->completed &&
2743 !oldstate->cheated && !newstate->cheated)
2748 static int game_wants_statusbar(void)
2753 static int game_timing_state(game_state *state, game_ui *ui)
2758 static void game_print_size(game_params *params, float *x, float *y)
2763 * I'll use 9mm squares by default. They should be quite big
2764 * for this game, because players will want to jot down no end
2765 * of pencil marks in the squares.
2767 game_compute_size(params, 900, &pw, &ph);
2772 static void game_print(drawing *dr, game_state *state, int tilesize)
2774 int c = state->c, r = state->r, cr = c*r;
2775 int ink = print_mono_colour(dr, 0);
2778 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2779 game_drawstate ads, *ds = &ads;
2780 ads.tilesize = tilesize;
2785 print_line_width(dr, 3 * TILE_SIZE / 40);
2786 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
2791 for (x = 1; x < cr; x++) {
2792 print_line_width(dr, (x % r ? 1 : 3) * TILE_SIZE / 40);
2793 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
2794 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
2796 for (y = 1; y < cr; y++) {
2797 print_line_width(dr, (y % c ? 1 : 3) * TILE_SIZE / 40);
2798 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
2799 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
2805 for (y = 0; y < cr; y++)
2806 for (x = 0; x < cr; x++)
2807 if (state->grid[y*cr+x]) {
2810 str[0] = state->grid[y*cr+x] + '0';
2812 str[0] += 'a' - ('9'+1);
2813 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
2814 BORDER + y*TILE_SIZE + TILE_SIZE/2,
2815 FONT_VARIABLE, TILE_SIZE/2,
2816 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2821 #define thegame solo
2824 const struct game thegame = {
2825 "Solo", "games.solo",
2832 TRUE, game_configure, custom_params,
2840 TRUE, game_text_format,
2848 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2851 game_free_drawstate,
2855 TRUE, FALSE, game_print_size, game_print,
2856 game_wants_statusbar,
2857 FALSE, game_timing_state,
2858 0, /* mouse_priorities */
2861 #ifdef STANDALONE_SOLVER
2864 * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2867 void frontend_default_colour(frontend *fe, float *output) {}
2868 void draw_text(drawing *dr, int x, int y, int fonttype, int fontsize,
2869 int align, int colour, char *text) {}
2870 void draw_rect(drawing *dr, int x, int y, int w, int h, int colour) {}
2871 void draw_rect_outline(drawing *dr, int x, int y, int w, int h, int colour) {}
2872 void draw_line(drawing *dr, int x1, int y1, int x2, int y2, int colour) {}
2873 void draw_polygon(drawing *dr, int *coords, int npoints,
2874 int fillcolour, int outlinecolour) {}
2875 void clip(drawing *dr, int x, int y, int w, int h) {}
2876 void unclip(drawing *dr) {}
2877 void start_draw(drawing *dr) {}
2878 void draw_update(drawing *dr, int x, int y, int w, int h) {}
2879 void end_draw(drawing *dr) {}
2880 int print_mono_colour(drawing *dr, int grey) { return 0; }
2881 void print_line_width(drawing *dr, int width) {}
2882 unsigned long random_bits(random_state *state, int bits)
2883 { assert(!"Shouldn't get randomness"); return 0; }
2884 unsigned long random_upto(random_state *state, unsigned long limit)
2885 { assert(!"Shouldn't get randomness"); return 0; }
2886 void shuffle(void *array, int nelts, int eltsize, random_state *rs)
2887 { assert(!"Shouldn't get randomness"); }
2889 void fatal(char *fmt, ...)
2893 fprintf(stderr, "fatal error: ");
2896 vfprintf(stderr, fmt, ap);
2899 fprintf(stderr, "\n");
2903 int main(int argc, char **argv)
2907 char *id = NULL, *desc, *err;
2911 while (--argc > 0) {
2913 if (!strcmp(p, "-v")) {
2914 solver_show_working = TRUE;
2915 } else if (!strcmp(p, "-g")) {
2917 } else if (*p == '-') {
2918 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2926 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2930 desc = strchr(id, ':');
2932 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2937 p = default_params();
2938 decode_params(p, id);
2939 err = validate_desc(p, desc);
2941 fprintf(stderr, "%s: %s\n", argv[0], err);
2944 s = new_game(NULL, p, desc);
2946 ret = solver(p->c, p->r, s->grid, DIFF_RECURSIVE);
2948 printf("Difficulty rating: %s\n",
2949 ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
2950 ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
2951 ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
2952 ret==DIFF_SET ? "Advanced (set elimination required)":
2953 ret==DIFF_NEIGHBOUR ? "Extreme (mutual neighbour elimination required)":
2954 ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
2955 ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
2956 ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
2957 "INTERNAL ERROR: unrecognised difficulty code");
2959 printf("%s\n", grid_text_format(p->c, p->r, s->grid));