2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - can we do anything about nasty centring of text in GTK? It
7 * seems to be taking ascenders/descenders into account when
10 * - implement stronger modes of reasoning in nsolve, thus
11 * enabling harder puzzles
12 * + and having done that, supply configurable difficulty
15 * - it might still be nice to do some prioritisation on the
16 * removal of numbers from the grid
17 * + one possibility is to try to minimise the maximum number
18 * of filled squares in any block, which in particular ought
19 * to enforce never leaving a completely filled block in the
20 * puzzle as presented.
21 * + be careful of being too clever here, though, until after
22 * I've tried implementing difficulty levels. It's not
23 * impossible that those might impose much more important
24 * constraints on this process.
26 * - alternative interface modes
27 * + sudoku.com's Windows program has a palette of possible
28 * entries; you select a palette entry first and then click
29 * on the square you want it to go in, thus enabling
30 * mouse-only play. Useful for PDAs! I don't think it's
31 * actually incompatible with the current highlight-then-type
32 * approach: you _either_ highlight a palette entry and then
33 * click, _or_ you highlight a square and then type. At most
34 * one thing is ever highlighted at a time, so there's no way
36 * + `pencil marks' might be useful for more subtle forms of
37 * deduction, once we implement creation of puzzles that
42 * Solo puzzles need to be square overall (since each row and each
43 * column must contain one of every digit), but they need not be
44 * subdivided the same way internally. I am going to adopt a
45 * convention whereby I _always_ refer to `r' as the number of rows
46 * of _big_ divisions, and `c' as the number of columns of _big_
47 * divisions. Thus, a 2c by 3r puzzle looks something like this:
51 * ------+------ (Of course, you can't subdivide it the other way
52 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
53 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
54 * ------+------ box down on the left-hand side.)
58 * The need for a strong naming convention should now be clear:
59 * each small box is two rows of digits by three columns, while the
60 * overall puzzle has three rows of small boxes by two columns. So
61 * I will (hopefully) consistently use `r' to denote the number of
62 * rows _of small boxes_ (here 3), which is also the number of
63 * columns of digits in each small box; and `c' vice versa (here
66 * I'm also going to choose arbitrarily to list c first wherever
67 * possible: the above is a 2x3 puzzle, not a 3x2 one.
80 * To save space, I store digits internally as unsigned char. This
81 * imposes a hard limit of 255 on the order of the puzzle. Since
82 * even a 5x5 takes unacceptably long to generate, I don't see this
83 * as a serious limitation unless something _really_ impressive
84 * happens in computing technology; but here's a typedef anyway for
85 * general good practice.
87 typedef unsigned char digit;
93 #define FLASH_TIME 0.4F
95 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF4 };
113 unsigned char *immutable; /* marks which digits are clues */
117 static game_params *default_params(void)
119 game_params *ret = snew(game_params);
122 ret->symm = SYMM_ROT2; /* a plausible default */
127 static int game_fetch_preset(int i, char **name, game_params **params)
134 case 0: c = 2, r = 2; break;
135 case 1: c = 2, r = 3; break;
136 case 2: c = 3, r = 3; break;
137 case 3: c = 3, r = 4; break;
138 case 4: c = 4, r = 4; break;
139 default: return FALSE;
142 sprintf(buf, "%dx%d", c, r);
144 *params = ret = snew(game_params);
147 ret->symm = SYMM_ROT2;
148 /* FIXME: difficulty presets? */
152 static void free_params(game_params *params)
157 static game_params *dup_params(game_params *params)
159 game_params *ret = snew(game_params);
160 *ret = *params; /* structure copy */
164 static game_params *decode_params(char const *string)
166 game_params *ret = default_params();
168 ret->c = ret->r = atoi(string);
169 ret->symm = SYMM_ROT2;
170 while (*string && isdigit((unsigned char)*string)) string++;
171 if (*string == 'x') {
173 ret->r = atoi(string);
174 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;
190 /* FIXME: difficulty levels */
195 static char *encode_params(game_params *params)
200 * Symmetry is a game generation preference and hence is left
201 * out of the encoding. Users can add it back in as they see
204 sprintf(str, "%dx%d", params->c, params->r);
208 static config_item *game_configure(game_params *params)
213 ret = snewn(5, config_item);
215 ret[0].name = "Columns of sub-blocks";
216 ret[0].type = C_STRING;
217 sprintf(buf, "%d", params->c);
218 ret[0].sval = dupstr(buf);
221 ret[1].name = "Rows of sub-blocks";
222 ret[1].type = C_STRING;
223 sprintf(buf, "%d", params->r);
224 ret[1].sval = dupstr(buf);
227 ret[2].name = "Symmetry";
228 ret[2].type = C_CHOICES;
229 ret[2].sval = ":None:2-way rotation:4-way rotation:4-way mirror";
230 ret[2].ival = params->symm;
233 * FIXME: difficulty level.
244 static game_params *custom_params(config_item *cfg)
246 game_params *ret = snew(game_params);
248 ret->c = atoi(cfg[0].sval);
249 ret->r = atoi(cfg[1].sval);
250 ret->symm = cfg[2].ival;
255 static char *validate_params(game_params *params)
257 if (params->c < 2 || params->r < 2)
258 return "Both dimensions must be at least 2";
259 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
260 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
264 /* ----------------------------------------------------------------------
265 * Full recursive Solo solver.
267 * The algorithm for this solver is shamelessly copied from a
268 * Python solver written by Andrew Wilkinson (which is GPLed, but
269 * I've reused only ideas and no code). It mostly just does the
270 * obvious recursive thing: pick an empty square, put one of the
271 * possible digits in it, recurse until all squares are filled,
272 * backtrack and change some choices if necessary.
274 * The clever bit is that every time it chooses which square to
275 * fill in next, it does so by counting the number of _possible_
276 * numbers that can go in each square, and it prioritises so that
277 * it picks a square with the _lowest_ number of possibilities. The
278 * idea is that filling in lots of the obvious bits (particularly
279 * any squares with only one possibility) will cut down on the list
280 * of possibilities for other squares and hence reduce the enormous
281 * search space as much as possible as early as possible.
283 * In practice the algorithm appeared to work very well; run on
284 * sample problems from the Times it completed in well under a
285 * second on my G5 even when written in Python, and given an empty
286 * grid (so that in principle it would enumerate _all_ solved
287 * grids!) it found the first valid solution just as quickly. So
288 * with a bit more randomisation I see no reason not to use this as
293 * Internal data structure used in solver to keep track of
296 struct rsolve_coord { int x, y, r; };
297 struct rsolve_usage {
298 int c, r, cr; /* cr == c*r */
299 /* grid is a copy of the input grid, modified as we go along */
301 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
303 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
305 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
307 /* This lists all the empty spaces remaining in the grid. */
308 struct rsolve_coord *spaces;
310 /* If we need randomisation in the solve, this is our random state. */
312 /* Number of solutions so far found, and maximum number we care about. */
317 * The real recursive step in the solving function.
319 static void rsolve_real(struct rsolve_usage *usage, digit *grid)
321 int c = usage->c, r = usage->r, cr = usage->cr;
322 int i, j, n, sx, sy, bestm, bestr;
326 * Firstly, check for completion! If there are no spaces left
327 * in the grid, we have a solution.
329 if (usage->nspaces == 0) {
332 * This is our first solution, so fill in the output grid.
334 memcpy(grid, usage->grid, cr * cr);
341 * Otherwise, there must be at least one space. Find the most
342 * constrained space, using the `r' field as a tie-breaker.
344 bestm = cr+1; /* so that any space will beat it */
347 for (j = 0; j < usage->nspaces; j++) {
348 int x = usage->spaces[j].x, y = usage->spaces[j].y;
352 * Find the number of digits that could go in this space.
355 for (n = 0; n < cr; n++)
356 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
357 !usage->blk[((y/c)*c+(x/r))*cr+n])
360 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
362 bestr = usage->spaces[j].r;
370 * Swap that square into the final place in the spaces array,
371 * so that decrementing nspaces will remove it from the list.
373 if (i != usage->nspaces-1) {
374 struct rsolve_coord t;
375 t = usage->spaces[usage->nspaces-1];
376 usage->spaces[usage->nspaces-1] = usage->spaces[i];
377 usage->spaces[i] = t;
381 * Now we've decided which square to start our recursion at,
382 * simply go through all possible values, shuffling them
383 * randomly first if necessary.
385 digits = snewn(bestm, int);
387 for (n = 0; n < cr; n++)
388 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
389 !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
395 for (i = j; i > 1; i--) {
396 int p = random_upto(usage->rs, i);
399 digits[p] = digits[i-1];
405 /* And finally, go through the digit list and actually recurse. */
406 for (i = 0; i < j; i++) {
409 /* Update the usage structure to reflect the placing of this digit. */
410 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
411 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
412 usage->grid[sy*cr+sx] = n;
415 /* Call the solver recursively. */
416 rsolve_real(usage, grid);
419 * If we have seen as many solutions as we need, terminate
420 * all processing immediately.
422 if (usage->solns >= usage->maxsolns)
425 /* Revert the usage structure. */
426 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
427 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
428 usage->grid[sy*cr+sx] = 0;
436 * Entry point to solver. You give it dimensions and a starting
437 * grid, which is simply an array of N^4 digits. In that array, 0
438 * means an empty square, and 1..N mean a clue square.
440 * Return value is the number of solutions found; searching will
441 * stop after the provided `max'. (Thus, you can pass max==1 to
442 * indicate that you only care about finding _one_ solution, or
443 * max==2 to indicate that you want to know the difference between
444 * a unique and non-unique solution.) The input parameter `grid' is
445 * also filled in with the _first_ (or only) solution found by the
448 static int rsolve(int c, int r, digit *grid, random_state *rs, int max)
450 struct rsolve_usage *usage;
455 * Create an rsolve_usage structure.
457 usage = snew(struct rsolve_usage);
463 usage->grid = snewn(cr * cr, digit);
464 memcpy(usage->grid, grid, cr * cr);
466 usage->row = snewn(cr * cr, unsigned char);
467 usage->col = snewn(cr * cr, unsigned char);
468 usage->blk = snewn(cr * cr, unsigned char);
469 memset(usage->row, FALSE, cr * cr);
470 memset(usage->col, FALSE, cr * cr);
471 memset(usage->blk, FALSE, cr * cr);
473 usage->spaces = snewn(cr * cr, struct rsolve_coord);
477 usage->maxsolns = max;
482 * Now fill it in with data from the input grid.
484 for (y = 0; y < cr; y++) {
485 for (x = 0; x < cr; x++) {
486 int v = grid[y*cr+x];
488 usage->spaces[usage->nspaces].x = x;
489 usage->spaces[usage->nspaces].y = y;
491 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
493 usage->spaces[usage->nspaces].r = usage->nspaces;
496 usage->row[y*cr+v-1] = TRUE;
497 usage->col[x*cr+v-1] = TRUE;
498 usage->blk[((y/c)*c+(x/r))*cr+v-1] = TRUE;
504 * Run the real recursive solving function.
506 rsolve_real(usage, grid);
510 * Clean up the usage structure now we have our answer.
512 sfree(usage->spaces);
525 /* ----------------------------------------------------------------------
526 * End of recursive solver code.
529 /* ----------------------------------------------------------------------
530 * Less capable non-recursive solver. This one is used to check
531 * solubility of a grid as we gradually remove numbers from it: by
532 * verifying a grid using this solver we can ensure it isn't _too_
533 * hard (e.g. does not actually require guessing and backtracking).
535 * It supports a variety of specific modes of reasoning. By
536 * enabling or disabling subsets of these modes we can arrange a
537 * range of difficulty levels.
541 * Modes of reasoning currently supported:
543 * - Positional elimination: a number must go in a particular
544 * square because all the other empty squares in a given
545 * row/col/blk are ruled out.
547 * - Numeric elimination: a square must have a particular number
548 * in because all the other numbers that could go in it are
551 * More advanced modes of reasoning I'd like to support in future:
553 * - Intersectional elimination: given two domains which overlap
554 * (hence one must be a block, and the other can be a row or
555 * col), if the possible locations for a particular number in
556 * one of the domains can be narrowed down to the overlap, then
557 * that number can be ruled out everywhere but the overlap in
558 * the other domain too.
560 * - Setwise numeric elimination: if there is a subset of the
561 * empty squares within a domain such that the union of the
562 * possible numbers in that subset has the same size as the
563 * subset itself, then those numbers can be ruled out everywhere
564 * else in the domain. (For example, if there are five empty
565 * squares and the possible numbers in each are 12, 23, 13, 134
566 * and 1345, then the first three empty squares form such a
567 * subset: the numbers 1, 2 and 3 _must_ be in those three
568 * squares in some permutation, and hence we can deduce none of
569 * them can be in the fourth or fifth squares.)
573 * Within this solver, I'm going to transform all y-coordinates by
574 * inverting the significance of the block number and the position
575 * within the block. That is, we will start with the top row of
576 * each block in order, then the second row of each block in order,
579 * This transformation has the enormous advantage that it means
580 * every row, column _and_ block is described by an arithmetic
581 * progression of coordinates within the cubic array, so that I can
582 * use the same very simple function to do blockwise, row-wise and
583 * column-wise elimination.
585 #define YTRANS(y) (((y)%c)*r+(y)/c)
586 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
588 struct nsolve_usage {
591 * We set up a cubic array, indexed by x, y and digit; each
592 * element of this array is TRUE or FALSE according to whether
593 * or not that digit _could_ in principle go in that position.
595 * The way to index this array is cube[(x*cr+y)*cr+n-1].
596 * y-coordinates in here are transformed.
600 * This is the grid in which we write down our final
601 * deductions. y-coordinates in here are _not_ transformed.
605 * Now we keep track, at a slightly higher level, of what we
606 * have yet to work out, to prevent doing the same deduction
609 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
611 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
613 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
616 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
617 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
620 * Function called when we are certain that a particular square has
621 * a particular number in it. The y-coordinate passed in here is
624 static void nsolve_place(struct nsolve_usage *usage, int x, int y, int n)
626 int c = usage->c, r = usage->r, cr = usage->cr;
632 * Rule out all other numbers in this square.
634 for (i = 1; i <= cr; i++)
639 * Rule out this number in all other positions in the row.
641 for (i = 0; i < cr; i++)
646 * Rule out this number in all other positions in the column.
648 for (i = 0; i < cr; i++)
653 * Rule out this number in all other positions in the block.
657 for (i = 0; i < r; i++)
658 for (j = 0; j < c; j++)
659 if (bx+i != x || by+j*r != y)
660 cube(bx+i,by+j*r,n) = FALSE;
663 * Enter the number in the result grid.
665 usage->grid[YUNTRANS(y)*cr+x] = n;
668 * Cross out this number from the list of numbers left to place
669 * in its row, its column and its block.
671 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
672 usage->blk[((y/c)*c+(x/r))*cr+n-1] = TRUE;
675 static int nsolve_elim(struct nsolve_usage *usage, int start, int step)
677 int c = usage->c, r = usage->r, cr = c*r;
681 * Count the number of set bits within this section of the
686 for (i = 0; i < cr; i++)
687 if (usage->cube[start+i*step]) {
701 nsolve_place(usage, x, y, n);
708 static int nsolve(int c, int r, digit *grid)
710 struct nsolve_usage *usage;
715 * Set up a usage structure as a clean slate (everything
718 usage = snew(struct nsolve_usage);
722 usage->cube = snewn(cr*cr*cr, unsigned char);
723 usage->grid = grid; /* write straight back to the input */
724 memset(usage->cube, TRUE, cr*cr*cr);
726 usage->row = snewn(cr * cr, unsigned char);
727 usage->col = snewn(cr * cr, unsigned char);
728 usage->blk = snewn(cr * cr, unsigned char);
729 memset(usage->row, FALSE, cr * cr);
730 memset(usage->col, FALSE, cr * cr);
731 memset(usage->blk, FALSE, cr * cr);
734 * Place all the clue numbers we are given.
736 for (x = 0; x < cr; x++)
737 for (y = 0; y < cr; y++)
739 nsolve_place(usage, x, YTRANS(y), grid[y*cr+x]);
742 * Now loop over the grid repeatedly trying all permitted modes
743 * of reasoning. The loop terminates if we complete an
744 * iteration without making any progress; we then return
745 * failure or success depending on whether the grid is full or
750 * Blockwise positional elimination.
752 for (x = 0; x < cr; x += r)
753 for (y = 0; y < r; y++)
754 for (n = 1; n <= cr; n++)
755 if (!usage->blk[(y*c+(x/r))*cr+n-1] &&
756 nsolve_elim(usage, cubepos(x,y,n), r*cr))
760 * Row-wise positional elimination.
762 for (y = 0; y < cr; y++)
763 for (n = 1; n <= cr; n++)
764 if (!usage->row[y*cr+n-1] &&
765 nsolve_elim(usage, cubepos(0,y,n), cr*cr))
768 * Column-wise positional elimination.
770 for (x = 0; x < cr; x++)
771 for (n = 1; n <= cr; n++)
772 if (!usage->col[x*cr+n-1] &&
773 nsolve_elim(usage, cubepos(x,0,n), cr))
777 * Numeric elimination.
779 for (x = 0; x < cr; x++)
780 for (y = 0; y < cr; y++)
781 if (!usage->grid[YUNTRANS(y)*cr+x] &&
782 nsolve_elim(usage, cubepos(x,y,1), 1))
786 * If we reach here, we have made no deductions in this
787 * iteration, so the algorithm terminates.
798 for (x = 0; x < cr; x++)
799 for (y = 0; y < cr; y++)
805 /* ----------------------------------------------------------------------
806 * End of non-recursive solver code.
810 * Check whether a grid contains a valid complete puzzle.
812 static int check_valid(int c, int r, digit *grid)
818 used = snewn(cr, unsigned char);
821 * Check that each row contains precisely one of everything.
823 for (y = 0; y < cr; y++) {
824 memset(used, FALSE, cr);
825 for (x = 0; x < cr; x++)
826 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
827 used[grid[y*cr+x]-1] = TRUE;
828 for (n = 0; n < cr; n++)
836 * Check that each column contains precisely one of everything.
838 for (x = 0; x < cr; x++) {
839 memset(used, FALSE, cr);
840 for (y = 0; y < cr; y++)
841 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
842 used[grid[y*cr+x]-1] = TRUE;
843 for (n = 0; n < cr; n++)
851 * Check that each block contains precisely one of everything.
853 for (x = 0; x < cr; x += r) {
854 for (y = 0; y < cr; y += c) {
856 memset(used, FALSE, cr);
857 for (xx = x; xx < x+r; xx++)
858 for (yy = 0; yy < y+c; yy++)
859 if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
860 used[grid[yy*cr+xx]-1] = TRUE;
861 for (n = 0; n < cr; n++)
873 static void symmetry_limit(game_params *params, int *xlim, int *ylim, int s)
875 int c = params->c, r = params->r, cr = c*r;
887 *xlim = *ylim = (cr+1) / 2;
892 static int symmetries(game_params *params, int x, int y, int *output, int s)
894 int c = params->c, r = params->r, cr = c*r;
903 break; /* just x,y is all we need */
908 *output++ = cr - 1 - x;
913 *output++ = cr - 1 - y;
917 *output++ = cr - 1 - y;
922 *output++ = cr - 1 - x;
928 *output++ = cr - 1 - x;
929 *output++ = cr - 1 - y;
937 static char *new_game_seed(game_params *params, random_state *rs)
939 int c = params->c, r = params->r, cr = c*r;
942 struct xy { int x, y; } *locs;
946 int coords[16], ncoords;
950 * Start the recursive solver with an empty grid to generate a
951 * random solved state.
953 grid = snewn(area, digit);
954 memset(grid, 0, area);
955 ret = rsolve(c, r, grid, rs, 1);
957 assert(check_valid(c, r, grid));
961 "\x0\x1\x0\x0\x6\x0\x0\x0\x0"
962 "\x5\x0\x0\x7\x0\x4\x0\x2\x0"
963 "\x0\x0\x6\x1\x0\x0\x0\x0\x0"
964 "\x8\x9\x7\x0\x0\x0\x0\x0\x0"
965 "\x0\x0\x3\x0\x4\x0\x9\x0\x0"
966 "\x0\x0\x0\x0\x0\x0\x8\x7\x6"
967 "\x0\x0\x0\x0\x0\x9\x1\x0\x0"
968 "\x0\x3\x0\x6\x0\x5\x0\x0\x7"
969 "\x0\x0\x0\x0\x8\x0\x0\x5\x0"
974 for (y = 0; y < cr; y++) {
975 for (x = 0; x < cr; x++) {
976 printf("%2.0d", grid[y*cr+x]);
987 for (y = 0; y < cr; y++) {
988 for (x = 0; x < cr; x++) {
989 printf("%2.0d", grid[y*cr+x]);
998 * Now we have a solved grid, start removing things from it
999 * while preserving solubility.
1001 locs = snewn(area, struct xy);
1002 grid2 = snewn(area, digit);
1003 symmetry_limit(params, &xlim, &ylim, params->symm);
1008 * Iterate over the grid and enumerate all the filled
1009 * squares we could empty.
1013 for (x = 0; x < xlim; x++)
1014 for (y = 0; y < ylim; y++)
1022 * Now shuffle that list.
1024 for (i = nlocs; i > 1; i--) {
1025 int p = random_upto(rs, i);
1027 struct xy t = locs[p];
1028 locs[p] = locs[i-1];
1034 * Now loop over the shuffled list and, for each element,
1035 * see whether removing that element (and its reflections)
1036 * from the grid will still leave the grid soluble by
1039 for (i = 0; i < nlocs; i++) {
1043 memcpy(grid2, grid, area);
1044 ncoords = symmetries(params, x, y, coords, params->symm);
1045 for (j = 0; j < ncoords; j++)
1046 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1048 if (nsolve(c, r, grid2)) {
1049 for (j = 0; j < ncoords; j++)
1050 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1057 * There was nothing we could remove without destroying
1069 for (y = 0; y < cr; y++) {
1070 for (x = 0; x < cr; x++) {
1071 printf("%2.0d", grid[y*cr+x]);
1080 * Now we have the grid as it will be presented to the user.
1081 * Encode it in a game seed.
1087 seed = snewn(5 * area, char);
1090 for (i = 0; i <= area; i++) {
1091 int n = (i < area ? grid[i] : -1);
1098 int c = 'a' - 1 + run;
1102 run -= c - ('a' - 1);
1106 * If there's a number in the very top left or
1107 * bottom right, there's no point putting an
1108 * unnecessary _ before or after it.
1110 if (p > seed && n > 0)
1114 p += sprintf(p, "%d", n);
1118 assert(p - seed < 5 * area);
1120 seed = sresize(seed, p - seed, char);
1128 static char *validate_seed(game_params *params, char *seed)
1130 int area = params->r * params->r * params->c * params->c;
1135 if (n >= 'a' && n <= 'z') {
1136 squares += n - 'a' + 1;
1137 } else if (n == '_') {
1139 } else if (n > '0' && n <= '9') {
1141 while (*seed >= '0' && *seed <= '9')
1144 return "Invalid character in game specification";
1148 return "Not enough data to fill grid";
1151 return "Too much data to fit in grid";
1156 static game_state *new_game(game_params *params, char *seed)
1158 game_state *state = snew(game_state);
1159 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
1162 state->c = params->c;
1163 state->r = params->r;
1165 state->grid = snewn(area, digit);
1166 state->immutable = snewn(area, unsigned char);
1167 memset(state->immutable, FALSE, area);
1169 state->completed = FALSE;
1174 if (n >= 'a' && n <= 'z') {
1175 int run = n - 'a' + 1;
1176 assert(i + run <= area);
1178 state->grid[i++] = 0;
1179 } else if (n == '_') {
1181 } else if (n > '0' && n <= '9') {
1183 state->immutable[i] = TRUE;
1184 state->grid[i++] = atoi(seed-1);
1185 while (*seed >= '0' && *seed <= '9')
1188 assert(!"We can't get here");
1196 static game_state *dup_game(game_state *state)
1198 game_state *ret = snew(game_state);
1199 int c = state->c, r = state->r, cr = c*r, area = cr * cr;
1204 ret->grid = snewn(area, digit);
1205 memcpy(ret->grid, state->grid, area);
1207 ret->immutable = snewn(area, unsigned char);
1208 memcpy(ret->immutable, state->immutable, area);
1210 ret->completed = state->completed;
1215 static void free_game(game_state *state)
1217 sfree(state->immutable);
1224 * These are the coordinates of the currently highlighted
1225 * square on the grid, or -1,-1 if there isn't one. When there
1226 * is, pressing a valid number or letter key or Space will
1227 * enter that number or letter in the grid.
1232 static game_ui *new_ui(game_state *state)
1234 game_ui *ui = snew(game_ui);
1236 ui->hx = ui->hy = -1;
1241 static void free_ui(game_ui *ui)
1246 static game_state *make_move(game_state *from, game_ui *ui, int x, int y,
1249 int c = from->c, r = from->r, cr = c*r;
1253 tx = (x - BORDER) / TILE_SIZE;
1254 ty = (y - BORDER) / TILE_SIZE;
1256 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr && button == LEFT_BUTTON) {
1257 if (tx == ui->hx && ty == ui->hy) {
1258 ui->hx = ui->hy = -1;
1263 return from; /* UI activity occurred */
1266 if (ui->hx != -1 && ui->hy != -1 &&
1267 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
1268 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
1269 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
1271 int n = button - '0';
1272 if (button >= 'A' && button <= 'Z')
1273 n = button - 'A' + 10;
1274 if (button >= 'a' && button <= 'z')
1275 n = button - 'a' + 10;
1279 if (from->immutable[ui->hy*cr+ui->hx])
1280 return NULL; /* can't overwrite this square */
1282 ret = dup_game(from);
1283 ret->grid[ui->hy*cr+ui->hx] = n;
1284 ui->hx = ui->hy = -1;
1287 * We've made a real change to the grid. Check to see
1288 * if the game has been completed.
1290 if (!ret->completed && check_valid(c, r, ret->grid)) {
1291 ret->completed = TRUE;
1294 return ret; /* made a valid move */
1300 /* ----------------------------------------------------------------------
1304 struct game_drawstate {
1311 #define XSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1312 #define YSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1314 static void game_size(game_params *params, int *x, int *y)
1316 int c = params->c, r = params->r, cr = c*r;
1322 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1324 float *ret = snewn(3 * NCOLOURS, float);
1326 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1328 ret[COL_GRID * 3 + 0] = 0.0F;
1329 ret[COL_GRID * 3 + 1] = 0.0F;
1330 ret[COL_GRID * 3 + 2] = 0.0F;
1332 ret[COL_CLUE * 3 + 0] = 0.0F;
1333 ret[COL_CLUE * 3 + 1] = 0.0F;
1334 ret[COL_CLUE * 3 + 2] = 0.0F;
1336 ret[COL_USER * 3 + 0] = 0.0F;
1337 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1338 ret[COL_USER * 3 + 2] = 0.0F;
1340 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1341 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1342 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1344 *ncolours = NCOLOURS;
1348 static game_drawstate *game_new_drawstate(game_state *state)
1350 struct game_drawstate *ds = snew(struct game_drawstate);
1351 int c = state->c, r = state->r, cr = c*r;
1353 ds->started = FALSE;
1357 ds->grid = snewn(cr*cr, digit);
1358 memset(ds->grid, 0, cr*cr);
1359 ds->hl = snewn(cr*cr, unsigned char);
1360 memset(ds->hl, 0, cr*cr);
1365 static void game_free_drawstate(game_drawstate *ds)
1372 static void draw_number(frontend *fe, game_drawstate *ds, game_state *state,
1373 int x, int y, int hl)
1375 int c = state->c, r = state->r, cr = c*r;
1380 if (ds->grid[y*cr+x] == state->grid[y*cr+x] && ds->hl[y*cr+x] == hl)
1381 return; /* no change required */
1383 tx = BORDER + x * TILE_SIZE + 2;
1384 ty = BORDER + y * TILE_SIZE + 2;
1400 clip(fe, cx, cy, cw, ch);
1402 /* background needs erasing? */
1403 if (ds->grid[y*cr+x] || ds->hl[y*cr+x] != hl)
1404 draw_rect(fe, cx, cy, cw, ch, hl ? COL_HIGHLIGHT : COL_BACKGROUND);
1406 /* new number needs drawing? */
1407 if (state->grid[y*cr+x]) {
1409 str[0] = state->grid[y*cr+x] + '0';
1411 str[0] += 'a' - ('9'+1);
1412 draw_text(fe, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
1413 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1414 state->immutable[y*cr+x] ? COL_CLUE : COL_USER, str);
1419 draw_update(fe, cx, cy, cw, ch);
1421 ds->grid[y*cr+x] = state->grid[y*cr+x];
1422 ds->hl[y*cr+x] = hl;
1425 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1426 game_state *state, int dir, game_ui *ui,
1427 float animtime, float flashtime)
1429 int c = state->c, r = state->r, cr = c*r;
1434 * The initial contents of the window are not guaranteed
1435 * and can vary with front ends. To be on the safe side,
1436 * all games should start by drawing a big
1437 * background-colour rectangle covering the whole window.
1439 draw_rect(fe, 0, 0, XSIZE(cr), YSIZE(cr), COL_BACKGROUND);
1444 for (x = 0; x <= cr; x++) {
1445 int thick = (x % r ? 0 : 1);
1446 draw_rect(fe, BORDER + x*TILE_SIZE - thick, BORDER-1,
1447 1+2*thick, cr*TILE_SIZE+3, COL_GRID);
1449 for (y = 0; y <= cr; y++) {
1450 int thick = (y % c ? 0 : 1);
1451 draw_rect(fe, BORDER-1, BORDER + y*TILE_SIZE - thick,
1452 cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
1457 * Draw any numbers which need redrawing.
1459 for (x = 0; x < cr; x++) {
1460 for (y = 0; y < cr; y++) {
1461 draw_number(fe, ds, state, x, y,
1462 (x == ui->hx && y == ui->hy) ||
1464 (flashtime <= FLASH_TIME/3 ||
1465 flashtime >= FLASH_TIME*2/3)));
1470 * Update the _entire_ grid if necessary.
1473 draw_update(fe, 0, 0, XSIZE(cr), YSIZE(cr));
1478 static float game_anim_length(game_state *oldstate, game_state *newstate,
1484 static float game_flash_length(game_state *oldstate, game_state *newstate,
1487 if (!oldstate->completed && newstate->completed)
1492 static int game_wants_statusbar(void)
1498 #define thegame solo
1501 const struct game thegame = {
1502 "Solo", "games.solo", TRUE,
1523 game_free_drawstate,
1527 game_wants_statusbar,