chiark / gitweb /
Oops; _actually_ add the reasoning mode I mentioned in the last
[sgt-puzzles.git] / solo.c
1 /*
2  * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3  *
4  * TODO:
5  *
6  *  - can we do anything about nasty centring of text in GTK? It
7  *    seems to be taking ascenders/descenders into account when
8  *    centring. Ick.
9  *
10  *  - implement stronger modes of reasoning in nsolve, thus
11  *    enabling harder puzzles
12  *     + and having done that, supply configurable difficulty
13  *       levels
14  *
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.
25  *
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
35  *       to confuse the two.
36  *     + `pencil marks' might be useful for more subtle forms of
37  *       deduction, once we implement creation of puzzles that
38  *       require it.
39  */
40
41 /*
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:
48  *
49  *   4 5 1 | 2 6 3
50  *   6 3 2 | 5 4 1
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.)
55  *   5 1 4 | 3 2 6
56  *   2 6 3 | 1 5 4
57  *
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
64  * 2).
65  *
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.
68  */
69
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <assert.h>
74 #include <ctype.h>
75 #include <math.h>
76
77 #include "puzzles.h"
78
79 /*
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.
86  */
87 typedef unsigned char digit;
88 #define ORDER_MAX 255
89
90 #define TILE_SIZE 32
91 #define BORDER 18
92
93 #define FLASH_TIME 0.4F
94
95 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF4 };
96
97 enum {
98     COL_BACKGROUND,
99     COL_GRID,
100     COL_CLUE,
101     COL_USER,
102     COL_HIGHLIGHT,
103     NCOLOURS
104 };
105
106 struct game_params {
107     int c, r, symm;
108 };
109
110 struct game_state {
111     int c, r;
112     digit *grid;
113     unsigned char *immutable;          /* marks which digits are clues */
114     int completed;
115 };
116
117 static game_params *default_params(void)
118 {
119     game_params *ret = snew(game_params);
120
121     ret->c = ret->r = 3;
122     ret->symm = SYMM_ROT2;             /* a plausible default */
123
124     return ret;
125 }
126
127 static int game_fetch_preset(int i, char **name, game_params **params)
128 {
129     game_params *ret;
130     int c, r;
131     char buf[80];
132
133     switch (i) {
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;
140     }
141
142     sprintf(buf, "%dx%d", c, r);
143     *name = dupstr(buf);
144     *params = ret = snew(game_params);
145     ret->c = c;
146     ret->r = r;
147     ret->symm = SYMM_ROT2;
148     /* FIXME: difficulty presets? */
149     return TRUE;
150 }
151
152 static void free_params(game_params *params)
153 {
154     sfree(params);
155 }
156
157 static game_params *dup_params(game_params *params)
158 {
159     game_params *ret = snew(game_params);
160     *ret = *params;                    /* structure copy */
161     return ret;
162 }
163
164 static game_params *decode_params(char const *string)
165 {
166     game_params *ret = default_params();
167
168     ret->c = ret->r = atoi(string);
169     ret->symm = SYMM_ROT2;
170     while (*string && isdigit((unsigned char)*string)) string++;
171     if (*string == 'x') {
172         string++;
173         ret->r = atoi(string);
174         while (*string && isdigit((unsigned char)*string)) string++;
175     }
176     if (*string == 'r' || *string == 'm' || *string == 'a') {
177         int sn, sc;
178         sc = *string++;
179         sn = atoi(string);
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;
187         if (sc == 'a')
188             ret->symm = SYMM_NONE;
189     }
190     /* FIXME: difficulty levels */
191
192     return ret;
193 }
194
195 static char *encode_params(game_params *params)
196 {
197     char str[80];
198
199     /*
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
202      * fit.
203      */
204     sprintf(str, "%dx%d", params->c, params->r);
205     return dupstr(str);
206 }
207
208 static config_item *game_configure(game_params *params)
209 {
210     config_item *ret;
211     char buf[80];
212
213     ret = snewn(5, config_item);
214
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);
219     ret[0].ival = 0;
220
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);
225     ret[1].ival = 0;
226
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;
231
232     /*
233      * FIXME: difficulty level.
234      */
235
236     ret[3].name = NULL;
237     ret[3].type = C_END;
238     ret[3].sval = NULL;
239     ret[3].ival = 0;
240
241     return ret;
242 }
243
244 static game_params *custom_params(config_item *cfg)
245 {
246     game_params *ret = snew(game_params);
247
248     ret->c = atoi(cfg[0].sval);
249     ret->r = atoi(cfg[1].sval);
250     ret->symm = cfg[2].ival;
251
252     return ret;
253 }
254
255 static char *validate_params(game_params *params)
256 {
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";
261     return NULL;
262 }
263
264 /* ----------------------------------------------------------------------
265  * Full recursive Solo solver.
266  *
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.
273  *
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.
282  *
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
289  * my grid generator.
290  */
291
292 /*
293  * Internal data structure used in solver to keep track of
294  * progress.
295  */
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 */
300     digit *grid;
301     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
302     unsigned char *row;
303     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
304     unsigned char *col;
305     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
306     unsigned char *blk;
307     /* This lists all the empty spaces remaining in the grid. */
308     struct rsolve_coord *spaces;
309     int nspaces;
310     /* If we need randomisation in the solve, this is our random state. */
311     random_state *rs;
312     /* Number of solutions so far found, and maximum number we care about. */
313     int solns, maxsolns;
314 };
315
316 /*
317  * The real recursive step in the solving function.
318  */
319 static void rsolve_real(struct rsolve_usage *usage, digit *grid)
320 {
321     int c = usage->c, r = usage->r, cr = usage->cr;
322     int i, j, n, sx, sy, bestm, bestr;
323     int *digits;
324
325     /*
326      * Firstly, check for completion! If there are no spaces left
327      * in the grid, we have a solution.
328      */
329     if (usage->nspaces == 0) {
330         if (!usage->solns) {
331             /*
332              * This is our first solution, so fill in the output grid.
333              */
334             memcpy(grid, usage->grid, cr * cr);
335         }
336         usage->solns++;
337         return;
338     }
339
340     /*
341      * Otherwise, there must be at least one space. Find the most
342      * constrained space, using the `r' field as a tie-breaker.
343      */
344     bestm = cr+1;                      /* so that any space will beat it */
345     bestr = 0;
346     i = sx = sy = -1;
347     for (j = 0; j < usage->nspaces; j++) {
348         int x = usage->spaces[j].x, y = usage->spaces[j].y;
349         int m;
350
351         /*
352          * Find the number of digits that could go in this space.
353          */
354         m = 0;
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])
358                 m++;
359
360         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
361             bestm = m;
362             bestr = usage->spaces[j].r;
363             sx = x;
364             sy = y;
365             i = j;
366         }
367     }
368
369     /*
370      * Swap that square into the final place in the spaces array,
371      * so that decrementing nspaces will remove it from the list.
372      */
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;
378     }
379
380     /*
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.
384      */
385     digits = snewn(bestm, int);
386     j = 0;
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]) {
390             digits[j++] = n+1;
391         }
392
393     if (usage->rs) {
394         /* shuffle */
395         for (i = j; i > 1; i--) {
396             int p = random_upto(usage->rs, i);
397             if (p != i-1) {
398                 int t = digits[p];
399                 digits[p] = digits[i-1];
400                 digits[i-1] = t;
401             }
402         }
403     }
404
405     /* And finally, go through the digit list and actually recurse. */
406     for (i = 0; i < j; i++) {
407         n = digits[i];
408
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;
413         usage->nspaces--;
414
415         /* Call the solver recursively. */
416         rsolve_real(usage, grid);
417
418         /*
419          * If we have seen as many solutions as we need, terminate
420          * all processing immediately.
421          */
422         if (usage->solns >= usage->maxsolns)
423             break;
424
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;
429         usage->nspaces++;
430     }
431
432     sfree(digits);
433 }
434
435 /*
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.
439  *
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
446  * solver.
447  */
448 static int rsolve(int c, int r, digit *grid, random_state *rs, int max)
449 {
450     struct rsolve_usage *usage;
451     int x, y, cr = c*r;
452     int ret;
453
454     /*
455      * Create an rsolve_usage structure.
456      */
457     usage = snew(struct rsolve_usage);
458
459     usage->c = c;
460     usage->r = r;
461     usage->cr = cr;
462
463     usage->grid = snewn(cr * cr, digit);
464     memcpy(usage->grid, grid, cr * cr);
465
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);
472
473     usage->spaces = snewn(cr * cr, struct rsolve_coord);
474     usage->nspaces = 0;
475
476     usage->solns = 0;
477     usage->maxsolns = max;
478
479     usage->rs = rs;
480
481     /*
482      * Now fill it in with data from the input grid.
483      */
484     for (y = 0; y < cr; y++) {
485         for (x = 0; x < cr; x++) {
486             int v = grid[y*cr+x];
487             if (v == 0) {
488                 usage->spaces[usage->nspaces].x = x;
489                 usage->spaces[usage->nspaces].y = y;
490                 if (rs)
491                     usage->spaces[usage->nspaces].r = random_bits(rs, 31);
492                 else
493                     usage->spaces[usage->nspaces].r = usage->nspaces;
494                 usage->nspaces++;
495             } else {
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;
499             }
500         }
501     }
502
503     /*
504      * Run the real recursive solving function.
505      */
506     rsolve_real(usage, grid);
507     ret = usage->solns;
508
509     /*
510      * Clean up the usage structure now we have our answer.
511      */
512     sfree(usage->spaces);
513     sfree(usage->blk);
514     sfree(usage->col);
515     sfree(usage->row);
516     sfree(usage->grid);
517     sfree(usage);
518
519     /*
520      * And return.
521      */
522     return ret;
523 }
524
525 /* ----------------------------------------------------------------------
526  * End of recursive solver code.
527  */
528
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).
534  *
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.
538  */
539
540 /*
541  * Modes of reasoning currently supported:
542  *
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.
546  *
547  *  - Numeric elimination: a square must have a particular number
548  *    in because all the other numbers that could go in it are
549  *    ruled out.
550  *
551  * More advanced modes of reasoning I'd like to support in future:
552  *
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.
559  *
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.)
570  * 
571  *  - Setwise positional elimination: if there is a subset of the
572  *    unplaced numbers within a domain such that the union of all
573  *    their possible positions has the same size as the subset
574  *    itself, then all other numbers can be ruled out for those
575  *    positions.
576  */
577
578 /*
579  * Within this solver, I'm going to transform all y-coordinates by
580  * inverting the significance of the block number and the position
581  * within the block. That is, we will start with the top row of
582  * each block in order, then the second row of each block in order,
583  * etc.
584  * 
585  * This transformation has the enormous advantage that it means
586  * every row, column _and_ block is described by an arithmetic
587  * progression of coordinates within the cubic array, so that I can
588  * use the same very simple function to do blockwise, row-wise and
589  * column-wise elimination.
590  */
591 #define YTRANS(y) (((y)%c)*r+(y)/c)
592 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
593
594 struct nsolve_usage {
595     int c, r, cr;
596     /*
597      * We set up a cubic array, indexed by x, y and digit; each
598      * element of this array is TRUE or FALSE according to whether
599      * or not that digit _could_ in principle go in that position.
600      *
601      * The way to index this array is cube[(x*cr+y)*cr+n-1].
602      * y-coordinates in here are transformed.
603      */
604     unsigned char *cube;
605     /*
606      * This is the grid in which we write down our final
607      * deductions. y-coordinates in here are _not_ transformed.
608      */
609     digit *grid;
610     /*
611      * Now we keep track, at a slightly higher level, of what we
612      * have yet to work out, to prevent doing the same deduction
613      * many times.
614      */
615     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
616     unsigned char *row;
617     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
618     unsigned char *col;
619     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
620     unsigned char *blk;
621 };
622 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
623 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
624
625 /*
626  * Function called when we are certain that a particular square has
627  * a particular number in it. The y-coordinate passed in here is
628  * transformed.
629  */
630 static void nsolve_place(struct nsolve_usage *usage, int x, int y, int n)
631 {
632     int c = usage->c, r = usage->r, cr = usage->cr;
633     int i, j, bx, by;
634
635     assert(cube(x,y,n));
636
637     /*
638      * Rule out all other numbers in this square.
639      */
640     for (i = 1; i <= cr; i++)
641         if (i != n)
642             cube(x,y,i) = FALSE;
643
644     /*
645      * Rule out this number in all other positions in the row.
646      */
647     for (i = 0; i < cr; i++)
648         if (i != y)
649             cube(x,i,n) = FALSE;
650
651     /*
652      * Rule out this number in all other positions in the column.
653      */
654     for (i = 0; i < cr; i++)
655         if (i != x)
656             cube(i,y,n) = FALSE;
657
658     /*
659      * Rule out this number in all other positions in the block.
660      */
661     bx = (x/r)*r;
662     by = y % r;
663     for (i = 0; i < r; i++)
664         for (j = 0; j < c; j++)
665             if (bx+i != x || by+j*r != y)
666                 cube(bx+i,by+j*r,n) = FALSE;
667
668     /*
669      * Enter the number in the result grid.
670      */
671     usage->grid[YUNTRANS(y)*cr+x] = n;
672
673     /*
674      * Cross out this number from the list of numbers left to place
675      * in its row, its column and its block.
676      */
677     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
678         usage->blk[((y/c)*c+(x/r))*cr+n-1] = TRUE;
679 }
680
681 static int nsolve_elim(struct nsolve_usage *usage, int start, int step)
682 {
683     int c = usage->c, r = usage->r, cr = c*r;
684     int fpos, m, i;
685
686     /*
687      * Count the number of set bits within this section of the
688      * cube.
689      */
690     m = 0;
691     fpos = -1;
692     for (i = 0; i < cr; i++)
693         if (usage->cube[start+i*step]) {
694             fpos = start+i*step;
695             m++;
696         }
697
698     if (m == 1) {
699         int x, y, n;
700         assert(fpos >= 0);
701
702         n = 1 + fpos % cr;
703         y = fpos / cr;
704         x = y / cr;
705         y %= cr;
706
707         if (!usage->grid[YUNTRANS(y)*cr+x]) {
708             nsolve_place(usage, x, y, n);
709             return TRUE;
710         }
711     }
712
713     return FALSE;
714 }
715
716 static int nsolve(int c, int r, digit *grid)
717 {
718     struct nsolve_usage *usage;
719     int cr = c*r;
720     int x, y, n;
721
722     /*
723      * Set up a usage structure as a clean slate (everything
724      * possible).
725      */
726     usage = snew(struct nsolve_usage);
727     usage->c = c;
728     usage->r = r;
729     usage->cr = cr;
730     usage->cube = snewn(cr*cr*cr, unsigned char);
731     usage->grid = grid;                /* write straight back to the input */
732     memset(usage->cube, TRUE, cr*cr*cr);
733
734     usage->row = snewn(cr * cr, unsigned char);
735     usage->col = snewn(cr * cr, unsigned char);
736     usage->blk = snewn(cr * cr, unsigned char);
737     memset(usage->row, FALSE, cr * cr);
738     memset(usage->col, FALSE, cr * cr);
739     memset(usage->blk, FALSE, cr * cr);
740
741     /*
742      * Place all the clue numbers we are given.
743      */
744     for (x = 0; x < cr; x++)
745         for (y = 0; y < cr; y++)
746             if (grid[y*cr+x])
747                 nsolve_place(usage, x, YTRANS(y), grid[y*cr+x]);
748
749     /*
750      * Now loop over the grid repeatedly trying all permitted modes
751      * of reasoning. The loop terminates if we complete an
752      * iteration without making any progress; we then return
753      * failure or success depending on whether the grid is full or
754      * not.
755      */
756     while (1) {
757         cont:
758
759         /*
760          * Blockwise positional elimination.
761          */
762         for (x = 0; x < cr; x += r)
763             for (y = 0; y < r; y++)
764                 for (n = 1; n <= cr; n++)
765                     if (!usage->blk[(y*c+(x/r))*cr+n-1] &&
766                         nsolve_elim(usage, cubepos(x,y,n), r*cr))
767                         goto cont;
768
769         /*
770          * Row-wise positional elimination.
771          */
772         for (y = 0; y < cr; y++)
773             for (n = 1; n <= cr; n++)
774                 if (!usage->row[y*cr+n-1] &&
775                     nsolve_elim(usage, cubepos(0,y,n), cr*cr))
776                     goto cont;
777         /*
778          * Column-wise positional elimination.
779          */
780         for (x = 0; x < cr; x++)
781             for (n = 1; n <= cr; n++)
782                 if (!usage->col[x*cr+n-1] &&
783                     nsolve_elim(usage, cubepos(x,0,n), cr))
784                     goto cont;
785
786         /*
787          * Numeric elimination.
788          */
789         for (x = 0; x < cr; x++)
790             for (y = 0; y < cr; y++)
791                 if (!usage->grid[YUNTRANS(y)*cr+x] &&
792                     nsolve_elim(usage, cubepos(x,y,1), 1))
793                     goto cont;
794
795         /*
796          * If we reach here, we have made no deductions in this
797          * iteration, so the algorithm terminates.
798          */
799         break;
800     }
801
802     sfree(usage->cube);
803     sfree(usage->row);
804     sfree(usage->col);
805     sfree(usage->blk);
806     sfree(usage);
807
808     for (x = 0; x < cr; x++)
809         for (y = 0; y < cr; y++)
810             if (!grid[y*cr+x])
811                 return FALSE;
812     return TRUE;
813 }
814
815 /* ----------------------------------------------------------------------
816  * End of non-recursive solver code.
817  */
818
819 /*
820  * Check whether a grid contains a valid complete puzzle.
821  */
822 static int check_valid(int c, int r, digit *grid)
823 {
824     int cr = c*r;
825     unsigned char *used;
826     int x, y, n;
827
828     used = snewn(cr, unsigned char);
829
830     /*
831      * Check that each row contains precisely one of everything.
832      */
833     for (y = 0; y < cr; y++) {
834         memset(used, FALSE, cr);
835         for (x = 0; x < cr; x++)
836             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
837                 used[grid[y*cr+x]-1] = TRUE;
838         for (n = 0; n < cr; n++)
839             if (!used[n]) {
840                 sfree(used);
841                 return FALSE;
842             }
843     }
844
845     /*
846      * Check that each column contains precisely one of everything.
847      */
848     for (x = 0; x < cr; x++) {
849         memset(used, FALSE, cr);
850         for (y = 0; y < cr; y++)
851             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
852                 used[grid[y*cr+x]-1] = TRUE;
853         for (n = 0; n < cr; n++)
854             if (!used[n]) {
855                 sfree(used);
856                 return FALSE;
857             }
858     }
859
860     /*
861      * Check that each block contains precisely one of everything.
862      */
863     for (x = 0; x < cr; x += r) {
864         for (y = 0; y < cr; y += c) {
865             int xx, yy;
866             memset(used, FALSE, cr);
867             for (xx = x; xx < x+r; xx++)
868                 for (yy = 0; yy < y+c; yy++)
869                     if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
870                         used[grid[yy*cr+xx]-1] = TRUE;
871             for (n = 0; n < cr; n++)
872                 if (!used[n]) {
873                     sfree(used);
874                     return FALSE;
875                 }
876         }
877     }
878
879     sfree(used);
880     return TRUE;
881 }
882
883 static void symmetry_limit(game_params *params, int *xlim, int *ylim, int s)
884 {
885     int c = params->c, r = params->r, cr = c*r;
886
887     switch (s) {
888       case SYMM_NONE:
889         *xlim = *ylim = cr;
890         break;
891       case SYMM_ROT2:
892         *xlim = (cr+1) / 2;
893         *ylim = cr;
894         break;
895       case SYMM_REF4:
896       case SYMM_ROT4:
897         *xlim = *ylim = (cr+1) / 2;
898         break;
899     }
900 }
901
902 static int symmetries(game_params *params, int x, int y, int *output, int s)
903 {
904     int c = params->c, r = params->r, cr = c*r;
905     int i = 0;
906
907     *output++ = x;
908     *output++ = y;
909     i++;
910
911     switch (s) {
912       case SYMM_NONE:
913         break;                         /* just x,y is all we need */
914       case SYMM_REF4:
915       case SYMM_ROT4:
916         switch (s) {
917           case SYMM_REF4:
918             *output++ = cr - 1 - x;
919             *output++ = y;
920             i++;
921
922             *output++ = x;
923             *output++ = cr - 1 - y;
924             i++;
925             break;
926           case SYMM_ROT4:
927             *output++ = cr - 1 - y;
928             *output++ = x;
929             i++;
930
931             *output++ = y;
932             *output++ = cr - 1 - x;
933             i++;
934             break;
935         }
936         /* fall through */
937       case SYMM_ROT2:
938         *output++ = cr - 1 - x;
939         *output++ = cr - 1 - y;
940         i++;
941         break;
942     }
943
944     return i;
945 }
946
947 static char *new_game_seed(game_params *params, random_state *rs)
948 {
949     int c = params->c, r = params->r, cr = c*r;
950     int area = cr*cr;
951     digit *grid, *grid2;
952     struct xy { int x, y; } *locs;
953     int nlocs;
954     int ret;
955     char *seed;
956     int coords[16], ncoords;
957     int xlim, ylim;
958
959     /*
960      * Start the recursive solver with an empty grid to generate a
961      * random solved state.
962      */
963     grid = snewn(area, digit);
964     memset(grid, 0, area);
965     ret = rsolve(c, r, grid, rs, 1);
966     assert(ret == 1);
967     assert(check_valid(c, r, grid));
968
969 #ifdef DEBUG
970     memcpy(grid,
971            "\x0\x1\x0\x0\x6\x0\x0\x0\x0"
972            "\x5\x0\x0\x7\x0\x4\x0\x2\x0"
973            "\x0\x0\x6\x1\x0\x0\x0\x0\x0"
974            "\x8\x9\x7\x0\x0\x0\x0\x0\x0"
975            "\x0\x0\x3\x0\x4\x0\x9\x0\x0"
976            "\x0\x0\x0\x0\x0\x0\x8\x7\x6"
977            "\x0\x0\x0\x0\x0\x9\x1\x0\x0"
978            "\x0\x3\x0\x6\x0\x5\x0\x0\x7"
979            "\x0\x0\x0\x0\x8\x0\x0\x5\x0"
980            , area);
981
982     {
983         int y, x;
984         for (y = 0; y < cr; y++) {
985             for (x = 0; x < cr; x++) {
986                 printf("%2.0d", grid[y*cr+x]);
987             }
988             printf("\n");
989         }
990         printf("\n");
991     }
992
993     nsolve(c, r, grid);
994
995     {
996         int y, x;
997         for (y = 0; y < cr; y++) {
998             for (x = 0; x < cr; x++) {
999                 printf("%2.0d", grid[y*cr+x]);
1000             }
1001             printf("\n");
1002         }
1003         printf("\n");
1004     }
1005 #endif
1006
1007     /*
1008      * Now we have a solved grid, start removing things from it
1009      * while preserving solubility.
1010      */
1011     locs = snewn(area, struct xy);
1012     grid2 = snewn(area, digit);
1013     symmetry_limit(params, &xlim, &ylim, params->symm);
1014     while (1) {
1015         int x, y, i, j;
1016
1017         /*
1018          * Iterate over the grid and enumerate all the filled
1019          * squares we could empty.
1020          */
1021         nlocs = 0;
1022
1023         for (x = 0; x < xlim; x++)
1024             for (y = 0; y < ylim; y++)
1025                 if (grid[y*cr+x]) {
1026                     locs[nlocs].x = x;
1027                     locs[nlocs].y = y;
1028                     nlocs++;
1029                 }
1030
1031         /*
1032          * Now shuffle that list.
1033          */
1034         for (i = nlocs; i > 1; i--) {
1035             int p = random_upto(rs, i);
1036             if (p != i-1) {
1037                 struct xy t = locs[p];
1038                 locs[p] = locs[i-1];
1039                 locs[i-1] = t;
1040             }
1041         }
1042
1043         /*
1044          * Now loop over the shuffled list and, for each element,
1045          * see whether removing that element (and its reflections)
1046          * from the grid will still leave the grid soluble by
1047          * nsolve.
1048          */
1049         for (i = 0; i < nlocs; i++) {
1050             x = locs[i].x;
1051             y = locs[i].y;
1052
1053             memcpy(grid2, grid, area);
1054             ncoords = symmetries(params, x, y, coords, params->symm);
1055             for (j = 0; j < ncoords; j++)
1056                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1057
1058             if (nsolve(c, r, grid2)) {
1059                 for (j = 0; j < ncoords; j++)
1060                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1061                 break;
1062             }
1063         }
1064
1065         if (i == nlocs) {
1066             /*
1067              * There was nothing we could remove without destroying
1068              * solvability.
1069              */
1070             break;
1071         }
1072     }
1073     sfree(grid2);
1074     sfree(locs);
1075
1076 #ifdef DEBUG
1077     {
1078         int y, x;
1079         for (y = 0; y < cr; y++) {
1080             for (x = 0; x < cr; x++) {
1081                 printf("%2.0d", grid[y*cr+x]);
1082             }
1083             printf("\n");
1084         }
1085         printf("\n");
1086     }
1087 #endif
1088
1089     /*
1090      * Now we have the grid as it will be presented to the user.
1091      * Encode it in a game seed.
1092      */
1093     {
1094         char *p;
1095         int run, i;
1096
1097         seed = snewn(5 * area, char);
1098         p = seed;
1099         run = 0;
1100         for (i = 0; i <= area; i++) {
1101             int n = (i < area ? grid[i] : -1);
1102
1103             if (!n)
1104                 run++;
1105             else {
1106                 if (run) {
1107                     while (run > 0) {
1108                         int c = 'a' - 1 + run;
1109                         if (run > 26)
1110                             c = 'z';
1111                         *p++ = c;
1112                         run -= c - ('a' - 1);
1113                     }
1114                 } else {
1115                     /*
1116                      * If there's a number in the very top left or
1117                      * bottom right, there's no point putting an
1118                      * unnecessary _ before or after it.
1119                      */
1120                     if (p > seed && n > 0)
1121                         *p++ = '_';
1122                 }
1123                 if (n > 0)
1124                     p += sprintf(p, "%d", n);
1125                 run = 0;
1126             }
1127         }
1128         assert(p - seed < 5 * area);
1129         *p++ = '\0';
1130         seed = sresize(seed, p - seed, char);
1131     }
1132
1133     sfree(grid);
1134
1135     return seed;
1136 }
1137
1138 static char *validate_seed(game_params *params, char *seed)
1139 {
1140     int area = params->r * params->r * params->c * params->c;
1141     int squares = 0;
1142
1143     while (*seed) {
1144         int n = *seed++;
1145         if (n >= 'a' && n <= 'z') {
1146             squares += n - 'a' + 1;
1147         } else if (n == '_') {
1148             /* do nothing */;
1149         } else if (n > '0' && n <= '9') {
1150             squares++;
1151             while (*seed >= '0' && *seed <= '9')
1152                 seed++;
1153         } else
1154             return "Invalid character in game specification";
1155     }
1156
1157     if (squares < area)
1158         return "Not enough data to fill grid";
1159
1160     if (squares > area)
1161         return "Too much data to fit in grid";
1162
1163     return NULL;
1164 }
1165
1166 static game_state *new_game(game_params *params, char *seed)
1167 {
1168     game_state *state = snew(game_state);
1169     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
1170     int i;
1171
1172     state->c = params->c;
1173     state->r = params->r;
1174
1175     state->grid = snewn(area, digit);
1176     state->immutable = snewn(area, unsigned char);
1177     memset(state->immutable, FALSE, area);
1178
1179     state->completed = FALSE;
1180
1181     i = 0;
1182     while (*seed) {
1183         int n = *seed++;
1184         if (n >= 'a' && n <= 'z') {
1185             int run = n - 'a' + 1;
1186             assert(i + run <= area);
1187             while (run-- > 0)
1188                 state->grid[i++] = 0;
1189         } else if (n == '_') {
1190             /* do nothing */;
1191         } else if (n > '0' && n <= '9') {
1192             assert(i < area);
1193             state->immutable[i] = TRUE;
1194             state->grid[i++] = atoi(seed-1);
1195             while (*seed >= '0' && *seed <= '9')
1196                 seed++;
1197         } else {
1198             assert(!"We can't get here");
1199         }
1200     }
1201     assert(i == area);
1202
1203     return state;
1204 }
1205
1206 static game_state *dup_game(game_state *state)
1207 {
1208     game_state *ret = snew(game_state);
1209     int c = state->c, r = state->r, cr = c*r, area = cr * cr;
1210
1211     ret->c = state->c;
1212     ret->r = state->r;
1213
1214     ret->grid = snewn(area, digit);
1215     memcpy(ret->grid, state->grid, area);
1216
1217     ret->immutable = snewn(area, unsigned char);
1218     memcpy(ret->immutable, state->immutable, area);
1219
1220     ret->completed = state->completed;
1221
1222     return ret;
1223 }
1224
1225 static void free_game(game_state *state)
1226 {
1227     sfree(state->immutable);
1228     sfree(state->grid);
1229     sfree(state);
1230 }
1231
1232 struct game_ui {
1233     /*
1234      * These are the coordinates of the currently highlighted
1235      * square on the grid, or -1,-1 if there isn't one. When there
1236      * is, pressing a valid number or letter key or Space will
1237      * enter that number or letter in the grid.
1238      */
1239     int hx, hy;
1240 };
1241
1242 static game_ui *new_ui(game_state *state)
1243 {
1244     game_ui *ui = snew(game_ui);
1245
1246     ui->hx = ui->hy = -1;
1247
1248     return ui;
1249 }
1250
1251 static void free_ui(game_ui *ui)
1252 {
1253     sfree(ui);
1254 }
1255
1256 static game_state *make_move(game_state *from, game_ui *ui, int x, int y,
1257                              int button)
1258 {
1259     int c = from->c, r = from->r, cr = c*r;
1260     int tx, ty;
1261     game_state *ret;
1262
1263     tx = (x - BORDER) / TILE_SIZE;
1264     ty = (y - BORDER) / TILE_SIZE;
1265
1266     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr && button == LEFT_BUTTON) {
1267         if (tx == ui->hx && ty == ui->hy) {
1268             ui->hx = ui->hy = -1;
1269         } else {
1270             ui->hx = tx;
1271             ui->hy = ty;
1272         }
1273         return from;                   /* UI activity occurred */
1274     }
1275
1276     if (ui->hx != -1 && ui->hy != -1 &&
1277         ((button >= '1' && button <= '9' && button - '0' <= cr) ||
1278          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
1279          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
1280          button == ' ')) {
1281         int n = button - '0';
1282         if (button >= 'A' && button <= 'Z')
1283             n = button - 'A' + 10;
1284         if (button >= 'a' && button <= 'z')
1285             n = button - 'a' + 10;
1286         if (button == ' ')
1287             n = 0;
1288
1289         if (from->immutable[ui->hy*cr+ui->hx])
1290             return NULL;               /* can't overwrite this square */
1291
1292         ret = dup_game(from);
1293         ret->grid[ui->hy*cr+ui->hx] = n;
1294         ui->hx = ui->hy = -1;
1295
1296         /*
1297          * We've made a real change to the grid. Check to see
1298          * if the game has been completed.
1299          */
1300         if (!ret->completed && check_valid(c, r, ret->grid)) {
1301             ret->completed = TRUE;
1302         }
1303
1304         return ret;                    /* made a valid move */
1305     }
1306
1307     return NULL;
1308 }
1309
1310 /* ----------------------------------------------------------------------
1311  * Drawing routines.
1312  */
1313
1314 struct game_drawstate {
1315     int started;
1316     int c, r, cr;
1317     digit *grid;
1318     unsigned char *hl;
1319 };
1320
1321 #define XSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1322 #define YSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1323
1324 static void game_size(game_params *params, int *x, int *y)
1325 {
1326     int c = params->c, r = params->r, cr = c*r;
1327
1328     *x = XSIZE(cr);
1329     *y = YSIZE(cr);
1330 }
1331
1332 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1333 {
1334     float *ret = snewn(3 * NCOLOURS, float);
1335
1336     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1337
1338     ret[COL_GRID * 3 + 0] = 0.0F;
1339     ret[COL_GRID * 3 + 1] = 0.0F;
1340     ret[COL_GRID * 3 + 2] = 0.0F;
1341
1342     ret[COL_CLUE * 3 + 0] = 0.0F;
1343     ret[COL_CLUE * 3 + 1] = 0.0F;
1344     ret[COL_CLUE * 3 + 2] = 0.0F;
1345
1346     ret[COL_USER * 3 + 0] = 0.0F;
1347     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1348     ret[COL_USER * 3 + 2] = 0.0F;
1349
1350     ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1351     ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1352     ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1353
1354     *ncolours = NCOLOURS;
1355     return ret;
1356 }
1357
1358 static game_drawstate *game_new_drawstate(game_state *state)
1359 {
1360     struct game_drawstate *ds = snew(struct game_drawstate);
1361     int c = state->c, r = state->r, cr = c*r;
1362
1363     ds->started = FALSE;
1364     ds->c = c;
1365     ds->r = r;
1366     ds->cr = cr;
1367     ds->grid = snewn(cr*cr, digit);
1368     memset(ds->grid, 0, cr*cr);
1369     ds->hl = snewn(cr*cr, unsigned char);
1370     memset(ds->hl, 0, cr*cr);
1371
1372     return ds;
1373 }
1374
1375 static void game_free_drawstate(game_drawstate *ds)
1376 {
1377     sfree(ds->hl);
1378     sfree(ds->grid);
1379     sfree(ds);
1380 }
1381
1382 static void draw_number(frontend *fe, game_drawstate *ds, game_state *state,
1383                         int x, int y, int hl)
1384 {
1385     int c = state->c, r = state->r, cr = c*r;
1386     int tx, ty;
1387     int cx, cy, cw, ch;
1388     char str[2];
1389
1390     if (ds->grid[y*cr+x] == state->grid[y*cr+x] && ds->hl[y*cr+x] == hl)
1391         return;                        /* no change required */
1392
1393     tx = BORDER + x * TILE_SIZE + 2;
1394     ty = BORDER + y * TILE_SIZE + 2;
1395
1396     cx = tx;
1397     cy = ty;
1398     cw = TILE_SIZE-3;
1399     ch = TILE_SIZE-3;
1400
1401     if (x % r)
1402         cx--, cw++;
1403     if ((x+1) % r)
1404         cw++;
1405     if (y % c)
1406         cy--, ch++;
1407     if ((y+1) % c)
1408         ch++;
1409
1410     clip(fe, cx, cy, cw, ch);
1411
1412     /* background needs erasing? */
1413     if (ds->grid[y*cr+x] || ds->hl[y*cr+x] != hl)
1414         draw_rect(fe, cx, cy, cw, ch, hl ? COL_HIGHLIGHT : COL_BACKGROUND);
1415
1416     /* new number needs drawing? */
1417     if (state->grid[y*cr+x]) {
1418         str[1] = '\0';
1419         str[0] = state->grid[y*cr+x] + '0';
1420         if (str[0] > '9')
1421             str[0] += 'a' - ('9'+1);
1422         draw_text(fe, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
1423                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1424                   state->immutable[y*cr+x] ? COL_CLUE : COL_USER, str);
1425     }
1426
1427     unclip(fe);
1428
1429     draw_update(fe, cx, cy, cw, ch);
1430
1431     ds->grid[y*cr+x] = state->grid[y*cr+x];
1432     ds->hl[y*cr+x] = hl;
1433 }
1434
1435 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1436                         game_state *state, int dir, game_ui *ui,
1437                         float animtime, float flashtime)
1438 {
1439     int c = state->c, r = state->r, cr = c*r;
1440     int x, y;
1441
1442     if (!ds->started) {
1443         /*
1444          * The initial contents of the window are not guaranteed
1445          * and can vary with front ends. To be on the safe side,
1446          * all games should start by drawing a big
1447          * background-colour rectangle covering the whole window.
1448          */
1449         draw_rect(fe, 0, 0, XSIZE(cr), YSIZE(cr), COL_BACKGROUND);
1450
1451         /*
1452          * Draw the grid.
1453          */
1454         for (x = 0; x <= cr; x++) {
1455             int thick = (x % r ? 0 : 1);
1456             draw_rect(fe, BORDER + x*TILE_SIZE - thick, BORDER-1,
1457                       1+2*thick, cr*TILE_SIZE+3, COL_GRID);
1458         }
1459         for (y = 0; y <= cr; y++) {
1460             int thick = (y % c ? 0 : 1);
1461             draw_rect(fe, BORDER-1, BORDER + y*TILE_SIZE - thick,
1462                       cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
1463         }
1464     }
1465
1466     /*
1467      * Draw any numbers which need redrawing.
1468      */
1469     for (x = 0; x < cr; x++) {
1470         for (y = 0; y < cr; y++) {
1471             draw_number(fe, ds, state, x, y,
1472                         (x == ui->hx && y == ui->hy) ||
1473                         (flashtime > 0 &&
1474                          (flashtime <= FLASH_TIME/3 ||
1475                           flashtime >= FLASH_TIME*2/3)));
1476         }
1477     }
1478
1479     /*
1480      * Update the _entire_ grid if necessary.
1481      */
1482     if (!ds->started) {
1483         draw_update(fe, 0, 0, XSIZE(cr), YSIZE(cr));
1484         ds->started = TRUE;
1485     }
1486 }
1487
1488 static float game_anim_length(game_state *oldstate, game_state *newstate,
1489                               int dir)
1490 {
1491     return 0.0F;
1492 }
1493
1494 static float game_flash_length(game_state *oldstate, game_state *newstate,
1495                                int dir)
1496 {
1497     if (!oldstate->completed && newstate->completed)
1498         return FLASH_TIME;
1499     return 0.0F;
1500 }
1501
1502 static int game_wants_statusbar(void)
1503 {
1504     return FALSE;
1505 }
1506
1507 #ifdef COMBINED
1508 #define thegame solo
1509 #endif
1510
1511 const struct game thegame = {
1512     "Solo", "games.solo", TRUE,
1513     default_params,
1514     game_fetch_preset,
1515     decode_params,
1516     encode_params,
1517     free_params,
1518     dup_params,
1519     game_configure,
1520     custom_params,
1521     validate_params,
1522     new_game_seed,
1523     validate_seed,
1524     new_game,
1525     dup_game,
1526     free_game,
1527     new_ui,
1528     free_ui,
1529     make_move,
1530     game_size,
1531     game_colours,
1532     game_new_drawstate,
1533     game_free_drawstate,
1534     game_redraw,
1535     game_anim_length,
1536     game_flash_length,
1537     game_wants_statusbar,
1538 };
1539
1540 #ifdef STANDALONE_SOLVER
1541
1542 void frontend_default_colour(frontend *fe, float *output) {}
1543 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1544                int align, int colour, char *text) {}
1545 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
1546 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
1547 void draw_polygon(frontend *fe, int *coords, int npoints,
1548                   int fill, int colour) {}
1549 void clip(frontend *fe, int x, int y, int w, int h) {}
1550 void unclip(frontend *fe) {}
1551 void start_draw(frontend *fe) {}
1552 void draw_update(frontend *fe, int x, int y, int w, int h) {}
1553 void end_draw(frontend *fe) {}
1554
1555 #include <stdarg.h>
1556
1557 void fatal(char *fmt, ...)
1558 {
1559     va_list ap;
1560
1561     fprintf(stderr, "fatal error: ");
1562
1563     va_start(ap, fmt);
1564     vfprintf(stderr, fmt, ap);
1565     va_end(ap);
1566
1567     fprintf(stderr, "\n");
1568     exit(1);
1569 }
1570
1571 int main(int argc, char **argv)
1572 {
1573     game_params *p;
1574     game_state *s;
1575     int recurse = FALSE;
1576     char *id = NULL, *seed, *err;
1577     int y, x;
1578
1579     while (--argc > 0) {
1580         char *p = *++argv;
1581         if (!strcmp(p, "-r")) {
1582             recurse = TRUE;
1583         } else if (!strcmp(p, "-n")) {
1584             recurse = FALSE;
1585         } else if (*p == '-') {
1586             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
1587             return 1;
1588         } else {
1589             id = p;
1590         }
1591     }
1592
1593     if (!id) {
1594         fprintf(stderr, "usage: %s [-n | -r] <game_id>\n", argv[0]);
1595         return 1;
1596     }
1597
1598     seed = strchr(id, ':');
1599     if (!seed) {
1600         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1601         return 1;
1602     }
1603     *seed++ = '\0';
1604
1605     p = decode_params(id);
1606     err = validate_seed(p, seed);
1607     if (err) {
1608         fprintf(stderr, "%s: %s\n", argv[0], err);
1609         return 1;
1610     }
1611     s = new_game(p, seed);
1612
1613     if (recurse) {
1614         int ret = rsolve(p->c, p->r, s->grid, NULL, 2);
1615         if (ret > 1) {
1616             printf("multiple solutions detected; only first one output\n");
1617         }
1618     } else {
1619         nsolve(p->c, p->r, s->grid);
1620     }
1621
1622     for (y = 0; y < p->c * p->r; y++) {
1623         for (x = 0; x < p->c * p->r; x++) {
1624             printf("%2.0d", s->grid[y * p->c * p->r + x]);
1625         }
1626         printf("\n");
1627     }
1628     printf("\n");
1629
1630     return 0;
1631 }
1632
1633 #endif