Cleanups from James H: a few missing statics, a precautionary cast
[sgt/puzzles] / solo.c
CommitLineData
1d8e8ad8 1/*
2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3 *
4 * TODO:
5 *
c8266e03 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
16 * for
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
19 * them
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.
29 *
ef57b17d 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.
1d8e8ad8 36 *
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
46 * to confuse the two.
c8266e03 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.
1d8e8ad8 54 */
55
56/*
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:
63 *
64 * 4 5 1 | 2 6 3
65 * 6 3 2 | 5 4 1
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.)
70 * 5 1 4 | 3 2 6
71 * 2 6 3 | 1 5 4
72 *
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
79 * 2).
80 *
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.
83 */
84
85#include <stdio.h>
86#include <stdlib.h>
87#include <string.h>
88#include <assert.h>
89#include <ctype.h>
90#include <math.h>
91
7c568a48 92#ifdef STANDALONE_SOLVER
93#include <stdarg.h>
ab362080 94int solver_show_working, solver_recurse_depth;
7c568a48 95#endif
96
1d8e8ad8 97#include "puzzles.h"
98
99/*
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.
106 */
107typedef unsigned char digit;
108#define ORDER_MAX 255
109
1e3e152d 110#define PREFERRED_TILE_SIZE 32
111#define TILE_SIZE (ds->tilesize)
112#define BORDER (TILE_SIZE / 2)
1d8e8ad8 113
114#define FLASH_TIME 0.4F
115
154bf9b1 116enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
117 SYMM_REF4D, SYMM_REF8 };
ef57b17d 118
7c568a48 119enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT,
120 DIFF_SET, DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
121
1d8e8ad8 122enum {
123 COL_BACKGROUND,
ef57b17d 124 COL_GRID,
125 COL_CLUE,
126 COL_USER,
127 COL_HIGHLIGHT,
7b14a9ec 128 COL_ERROR,
c8266e03 129 COL_PENCIL,
ef57b17d 130 NCOLOURS
1d8e8ad8 131};
132
133struct game_params {
7c568a48 134 int c, r, symm, diff;
1d8e8ad8 135};
136
137struct game_state {
138 int c, r;
139 digit *grid;
c8266e03 140 unsigned char *pencil; /* c*r*c*r elements */
1d8e8ad8 141 unsigned char *immutable; /* marks which digits are clues */
2ac6d24e 142 int completed, cheated;
1d8e8ad8 143};
144
145static game_params *default_params(void)
146{
147 game_params *ret = snew(game_params);
148
149 ret->c = ret->r = 3;
ef57b17d 150 ret->symm = SYMM_ROT2; /* a plausible default */
4f36adaa 151 ret->diff = DIFF_BLOCK; /* so is this */
1d8e8ad8 152
153 return ret;
154}
155
1d8e8ad8 156static void free_params(game_params *params)
157{
158 sfree(params);
159}
160
161static game_params *dup_params(game_params *params)
162{
163 game_params *ret = snew(game_params);
164 *ret = *params; /* structure copy */
165 return ret;
166}
167
7c568a48 168static int game_fetch_preset(int i, char **name, game_params **params)
169{
170 static struct {
171 char *title;
172 game_params params;
173 } presets[] = {
174 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK } },
175 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE } },
4f36adaa 176 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK } },
7c568a48 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 } },
de60d8bd 180 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE } },
ab53eb64 181#ifndef SLOW_SYSTEM
7c568a48 182 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE } },
183 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE } },
ab53eb64 184#endif
7c568a48 185 };
186
187 if (i < 0 || i >= lenof(presets))
188 return FALSE;
189
190 *name = dupstr(presets[i].title);
191 *params = dup_params(&presets[i].params);
192
193 return TRUE;
194}
195
1185e3c5 196static void decode_params(game_params *ret, char const *string)
1d8e8ad8 197{
1d8e8ad8 198 ret->c = ret->r = atoi(string);
199 while (*string && isdigit((unsigned char)*string)) string++;
200 if (*string == 'x') {
201 string++;
202 ret->r = atoi(string);
203 while (*string && isdigit((unsigned char)*string)) string++;
204 }
7c568a48 205 while (*string) {
206 if (*string == 'r' || *string == 'm' || *string == 'a') {
154bf9b1 207 int sn, sc, sd;
7c568a48 208 sc = *string++;
154bf9b1 209 if (*string == 'd') {
210 sd = TRUE;
211 string++;
212 } else {
213 sd = FALSE;
214 }
7c568a48 215 sn = atoi(string);
216 while (*string && isdigit((unsigned char)*string)) string++;
154bf9b1 217 if (sc == 'm' && sn == 8)
218 ret->symm = SYMM_REF8;
7c568a48 219 if (sc == 'm' && sn == 4)
154bf9b1 220 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
221 if (sc == 'm' && sn == 2)
222 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
7c568a48 223 if (sc == 'r' && sn == 4)
224 ret->symm = SYMM_ROT4;
225 if (sc == 'r' && sn == 2)
226 ret->symm = SYMM_ROT2;
227 if (sc == 'a')
228 ret->symm = SYMM_NONE;
229 } else if (*string == 'd') {
230 string++;
231 if (*string == 't') /* trivial */
232 string++, ret->diff = DIFF_BLOCK;
233 else if (*string == 'b') /* basic */
234 string++, ret->diff = DIFF_SIMPLE;
235 else if (*string == 'i') /* intermediate */
236 string++, ret->diff = DIFF_INTERSECT;
237 else if (*string == 'a') /* advanced */
238 string++, ret->diff = DIFF_SET;
de60d8bd 239 else if (*string == 'u') /* unreasonable */
240 string++, ret->diff = DIFF_RECURSIVE;
7c568a48 241 } else
242 string++; /* eat unknown character */
ef57b17d 243 }
1d8e8ad8 244}
245
1185e3c5 246static char *encode_params(game_params *params, int full)
1d8e8ad8 247{
248 char str[80];
249
250 sprintf(str, "%dx%d", params->c, params->r);
1185e3c5 251 if (full) {
252 switch (params->symm) {
154bf9b1 253 case SYMM_REF8: strcat(str, "m8"); break;
1185e3c5 254 case SYMM_REF4: strcat(str, "m4"); break;
154bf9b1 255 case SYMM_REF4D: strcat(str, "md4"); break;
256 case SYMM_REF2: strcat(str, "m2"); break;
257 case SYMM_REF2D: strcat(str, "md2"); break;
1185e3c5 258 case SYMM_ROT4: strcat(str, "r4"); break;
259 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
260 case SYMM_NONE: strcat(str, "a"); break;
261 }
262 switch (params->diff) {
263 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
264 case DIFF_SIMPLE: strcat(str, "db"); break;
265 case DIFF_INTERSECT: strcat(str, "di"); break;
266 case DIFF_SET: strcat(str, "da"); break;
267 case DIFF_RECURSIVE: strcat(str, "du"); break;
268 }
269 }
1d8e8ad8 270 return dupstr(str);
271}
272
273static config_item *game_configure(game_params *params)
274{
275 config_item *ret;
276 char buf[80];
277
278 ret = snewn(5, config_item);
279
280 ret[0].name = "Columns of sub-blocks";
281 ret[0].type = C_STRING;
282 sprintf(buf, "%d", params->c);
283 ret[0].sval = dupstr(buf);
284 ret[0].ival = 0;
285
286 ret[1].name = "Rows of sub-blocks";
287 ret[1].type = C_STRING;
288 sprintf(buf, "%d", params->r);
289 ret[1].sval = dupstr(buf);
290 ret[1].ival = 0;
291
ef57b17d 292 ret[2].name = "Symmetry";
293 ret[2].type = C_CHOICES;
154bf9b1 294 ret[2].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
295 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
296 "8-way mirror";
ef57b17d 297 ret[2].ival = params->symm;
298
7c568a48 299 ret[3].name = "Difficulty";
300 ret[3].type = C_CHOICES;
de60d8bd 301 ret[3].sval = ":Trivial:Basic:Intermediate:Advanced:Unreasonable";
7c568a48 302 ret[3].ival = params->diff;
1d8e8ad8 303
7c568a48 304 ret[4].name = NULL;
305 ret[4].type = C_END;
306 ret[4].sval = NULL;
307 ret[4].ival = 0;
1d8e8ad8 308
309 return ret;
310}
311
312static game_params *custom_params(config_item *cfg)
313{
314 game_params *ret = snew(game_params);
315
c1f743c8 316 ret->c = atoi(cfg[0].sval);
317 ret->r = atoi(cfg[1].sval);
ef57b17d 318 ret->symm = cfg[2].ival;
7c568a48 319 ret->diff = cfg[3].ival;
1d8e8ad8 320
321 return ret;
322}
323
3ff276f2 324static char *validate_params(game_params *params, int full)
1d8e8ad8 325{
326 if (params->c < 2 || params->r < 2)
327 return "Both dimensions must be at least 2";
328 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
329 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
95057cc5 330 if ((params->c * params->r) > 36)
331 return "Unable to support more than 36 distinct symbols in a puzzle";
1d8e8ad8 332 return NULL;
333}
334
335/* ----------------------------------------------------------------------
ab362080 336 * Solver.
337 *
338 * This solver is used for several purposes:
339 * + to generate filled grids as the basis for new puzzles (by
340 * supplying no clue squares at all)
341 * + to check solubility of a grid as we gradually remove numbers
342 * from it
343 * + to solve an externally generated puzzle when the user selects
344 * `Solve'.
345 *
1d8e8ad8 346 * It supports a variety of specific modes of reasoning. By
347 * enabling or disabling subsets of these modes we can arrange a
348 * range of difficulty levels.
349 */
350
351/*
352 * Modes of reasoning currently supported:
353 *
354 * - Positional elimination: a number must go in a particular
355 * square because all the other empty squares in a given
356 * row/col/blk are ruled out.
357 *
358 * - Numeric elimination: a square must have a particular number
359 * in because all the other numbers that could go in it are
360 * ruled out.
361 *
7c568a48 362 * - Intersectional analysis: given two domains which overlap
1d8e8ad8 363 * (hence one must be a block, and the other can be a row or
364 * col), if the possible locations for a particular number in
365 * one of the domains can be narrowed down to the overlap, then
366 * that number can be ruled out everywhere but the overlap in
367 * the other domain too.
368 *
7c568a48 369 * - Set elimination: if there is a subset of the empty squares
370 * within a domain such that the union of the possible numbers
371 * in that subset has the same size as the subset itself, then
372 * those numbers can be ruled out everywhere else in the domain.
373 * (For example, if there are five empty squares and the
374 * possible numbers in each are 12, 23, 13, 134 and 1345, then
375 * the first three empty squares form such a subset: the numbers
376 * 1, 2 and 3 _must_ be in those three squares in some
377 * permutation, and hence we can deduce none of them can be in
378 * the fourth or fifth squares.)
379 * + You can also see this the other way round, concentrating
380 * on numbers rather than squares: if there is a subset of
381 * the unplaced numbers within a domain such that the union
382 * of all their possible positions has the same size as the
383 * subset itself, then all other numbers can be ruled out for
384 * those positions. However, it turns out that this is
385 * exactly equivalent to the first formulation at all times:
386 * there is a 1-1 correspondence between suitable subsets of
387 * the unplaced numbers and suitable subsets of the unfilled
388 * places, found by taking the _complement_ of the union of
389 * the numbers' possible positions (or the spaces' possible
390 * contents).
ab362080 391 *
392 * - Recursion. If all else fails, we pick one of the currently
393 * most constrained empty squares and take a random guess at its
394 * contents, then continue solving on that basis and see if we
395 * get any further.
1d8e8ad8 396 */
397
4846f788 398/*
399 * Within this solver, I'm going to transform all y-coordinates by
400 * inverting the significance of the block number and the position
401 * within the block. That is, we will start with the top row of
402 * each block in order, then the second row of each block in order,
403 * etc.
404 *
405 * This transformation has the enormous advantage that it means
406 * every row, column _and_ block is described by an arithmetic
407 * progression of coordinates within the cubic array, so that I can
408 * use the same very simple function to do blockwise, row-wise and
409 * column-wise elimination.
410 */
411#define YTRANS(y) (((y)%c)*r+(y)/c)
412#define YUNTRANS(y) (((y)%r)*c+(y)/r)
413
ab362080 414struct solver_usage {
1d8e8ad8 415 int c, r, cr;
416 /*
417 * We set up a cubic array, indexed by x, y and digit; each
418 * element of this array is TRUE or FALSE according to whether
419 * or not that digit _could_ in principle go in that position.
420 *
421 * The way to index this array is cube[(x*cr+y)*cr+n-1].
4846f788 422 * y-coordinates in here are transformed.
1d8e8ad8 423 */
424 unsigned char *cube;
425 /*
426 * This is the grid in which we write down our final
4846f788 427 * deductions. y-coordinates in here are _not_ transformed.
1d8e8ad8 428 */
429 digit *grid;
430 /*
431 * Now we keep track, at a slightly higher level, of what we
432 * have yet to work out, to prevent doing the same deduction
433 * many times.
434 */
435 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
436 unsigned char *row;
437 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
438 unsigned char *col;
439 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
440 unsigned char *blk;
441};
4846f788 442#define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
443#define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
1d8e8ad8 444
445/*
446 * Function called when we are certain that a particular square has
4846f788 447 * a particular number in it. The y-coordinate passed in here is
448 * transformed.
1d8e8ad8 449 */
ab362080 450static void solver_place(struct solver_usage *usage, int x, int y, int n)
1d8e8ad8 451{
452 int c = usage->c, r = usage->r, cr = usage->cr;
453 int i, j, bx, by;
454
455 assert(cube(x,y,n));
456
457 /*
458 * Rule out all other numbers in this square.
459 */
460 for (i = 1; i <= cr; i++)
461 if (i != n)
462 cube(x,y,i) = FALSE;
463
464 /*
465 * Rule out this number in all other positions in the row.
466 */
467 for (i = 0; i < cr; i++)
468 if (i != y)
469 cube(x,i,n) = FALSE;
470
471 /*
472 * Rule out this number in all other positions in the column.
473 */
474 for (i = 0; i < cr; i++)
475 if (i != x)
476 cube(i,y,n) = FALSE;
477
478 /*
479 * Rule out this number in all other positions in the block.
480 */
481 bx = (x/r)*r;
4846f788 482 by = y % r;
1d8e8ad8 483 for (i = 0; i < r; i++)
484 for (j = 0; j < c; j++)
4846f788 485 if (bx+i != x || by+j*r != y)
486 cube(bx+i,by+j*r,n) = FALSE;
1d8e8ad8 487
488 /*
489 * Enter the number in the result grid.
490 */
4846f788 491 usage->grid[YUNTRANS(y)*cr+x] = n;
1d8e8ad8 492
493 /*
494 * Cross out this number from the list of numbers left to place
495 * in its row, its column and its block.
496 */
497 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
7c568a48 498 usage->blk[((y%r)*c+(x/r))*cr+n-1] = TRUE;
1d8e8ad8 499}
500
ab362080 501static int solver_elim(struct solver_usage *usage, int start, int step
7c568a48 502#ifdef STANDALONE_SOLVER
503 , char *fmt, ...
504#endif
505 )
1d8e8ad8 506{
4846f788 507 int c = usage->c, r = usage->r, cr = c*r;
508 int fpos, m, i;
1d8e8ad8 509
510 /*
4846f788 511 * Count the number of set bits within this section of the
512 * cube.
1d8e8ad8 513 */
514 m = 0;
4846f788 515 fpos = -1;
516 for (i = 0; i < cr; i++)
517 if (usage->cube[start+i*step]) {
518 fpos = start+i*step;
1d8e8ad8 519 m++;
520 }
521
522 if (m == 1) {
4846f788 523 int x, y, n;
524 assert(fpos >= 0);
1d8e8ad8 525
4846f788 526 n = 1 + fpos % cr;
527 y = fpos / cr;
528 x = y / cr;
529 y %= cr;
1d8e8ad8 530
3ddae0ff 531 if (!usage->grid[YUNTRANS(y)*cr+x]) {
7c568a48 532#ifdef STANDALONE_SOLVER
533 if (solver_show_working) {
534 va_list ap;
fdb3b29a 535 printf("%*s", solver_recurse_depth*4, "");
7c568a48 536 va_start(ap, fmt);
537 vprintf(fmt, ap);
538 va_end(ap);
ab362080 539 printf(":\n%*s placing %d at (%d,%d)\n",
540 solver_recurse_depth*4, "", n, 1+x, 1+YUNTRANS(y));
7c568a48 541 }
542#endif
ab362080 543 solver_place(usage, x, y, n);
544 return +1;
3ddae0ff 545 }
ab362080 546 } else if (m == 0) {
547#ifdef STANDALONE_SOLVER
548 if (solver_show_working) {
ab362080 549 va_list ap;
fdb3b29a 550 printf("%*s", solver_recurse_depth*4, "");
ab362080 551 va_start(ap, fmt);
552 vprintf(fmt, ap);
553 va_end(ap);
554 printf(":\n%*s no possibilities available\n",
555 solver_recurse_depth*4, "");
556 }
557#endif
558 return -1;
1d8e8ad8 559 }
560
ab362080 561 return 0;
1d8e8ad8 562}
563
ab362080 564static int solver_intersect(struct solver_usage *usage,
7c568a48 565 int start1, int step1, int start2, int step2
566#ifdef STANDALONE_SOLVER
567 , char *fmt, ...
568#endif
569 )
570{
571 int c = usage->c, r = usage->r, cr = c*r;
572 int ret, i;
573
574 /*
575 * Loop over the first domain and see if there's any set bit
576 * not also in the second.
577 */
578 for (i = 0; i < cr; i++) {
579 int p = start1+i*step1;
580 if (usage->cube[p] &&
581 !(p >= start2 && p < start2+cr*step2 &&
582 (p - start2) % step2 == 0))
ab362080 583 return 0; /* there is, so we can't deduce */
7c568a48 584 }
585
586 /*
587 * We have determined that all set bits in the first domain are
588 * within its overlap with the second. So loop over the second
589 * domain and remove all set bits that aren't also in that
ab362080 590 * overlap; return +1 iff we actually _did_ anything.
7c568a48 591 */
ab362080 592 ret = 0;
7c568a48 593 for (i = 0; i < cr; i++) {
594 int p = start2+i*step2;
595 if (usage->cube[p] &&
596 !(p >= start1 && p < start1+cr*step1 && (p - start1) % step1 == 0))
597 {
598#ifdef STANDALONE_SOLVER
599 if (solver_show_working) {
600 int px, py, pn;
601
602 if (!ret) {
603 va_list ap;
fdb3b29a 604 printf("%*s", solver_recurse_depth*4, "");
7c568a48 605 va_start(ap, fmt);
606 vprintf(fmt, ap);
607 va_end(ap);
608 printf(":\n");
609 }
610
611 pn = 1 + p % cr;
612 py = p / cr;
613 px = py / cr;
614 py %= cr;
615
ab362080 616 printf("%*s ruling out %d at (%d,%d)\n",
617 solver_recurse_depth*4, "", pn, 1+px, 1+YUNTRANS(py));
7c568a48 618 }
619#endif
ab362080 620 ret = +1; /* we did something */
7c568a48 621 usage->cube[p] = 0;
622 }
623 }
624
625 return ret;
626}
627
ab362080 628struct solver_scratch {
ab53eb64 629 unsigned char *grid, *rowidx, *colidx, *set;
630};
631
ab362080 632static int solver_set(struct solver_usage *usage,
633 struct solver_scratch *scratch,
7c568a48 634 int start, int step1, int step2
635#ifdef STANDALONE_SOLVER
636 , char *fmt, ...
637#endif
638 )
639{
640 int c = usage->c, r = usage->r, cr = c*r;
641 int i, j, n, count;
ab53eb64 642 unsigned char *grid = scratch->grid;
643 unsigned char *rowidx = scratch->rowidx;
644 unsigned char *colidx = scratch->colidx;
645 unsigned char *set = scratch->set;
7c568a48 646
647 /*
648 * We are passed a cr-by-cr matrix of booleans. Our first job
649 * is to winnow it by finding any definite placements - i.e.
650 * any row with a solitary 1 - and discarding that row and the
651 * column containing the 1.
652 */
653 memset(rowidx, TRUE, cr);
654 memset(colidx, TRUE, cr);
655 for (i = 0; i < cr; i++) {
656 int count = 0, first = -1;
657 for (j = 0; j < cr; j++)
658 if (usage->cube[start+i*step1+j*step2])
659 first = j, count++;
ab362080 660
661 /*
662 * If count == 0, then there's a row with no 1s at all and
663 * the puzzle is internally inconsistent. However, we ought
664 * to have caught this already during the simpler reasoning
665 * methods, so we can safely fail an assertion if we reach
666 * this point here.
667 */
668 assert(count > 0);
7c568a48 669 if (count == 1)
670 rowidx[i] = colidx[first] = FALSE;
671 }
672
673 /*
674 * Convert each of rowidx/colidx from a list of 0s and 1s to a
675 * list of the indices of the 1s.
676 */
677 for (i = j = 0; i < cr; i++)
678 if (rowidx[i])
679 rowidx[j++] = i;
680 n = j;
681 for (i = j = 0; i < cr; i++)
682 if (colidx[i])
683 colidx[j++] = i;
684 assert(n == j);
685
686 /*
687 * And create the smaller matrix.
688 */
689 for (i = 0; i < n; i++)
690 for (j = 0; j < n; j++)
691 grid[i*cr+j] = usage->cube[start+rowidx[i]*step1+colidx[j]*step2];
692
693 /*
694 * Having done that, we now have a matrix in which every row
695 * has at least two 1s in. Now we search to see if we can find
696 * a rectangle of zeroes (in the set-theoretic sense of
697 * `rectangle', i.e. a subset of rows crossed with a subset of
698 * columns) whose width and height add up to n.
699 */
700
701 memset(set, 0, n);
702 count = 0;
703 while (1) {
704 /*
705 * We have a candidate set. If its size is <=1 or >=n-1
706 * then we move on immediately.
707 */
708 if (count > 1 && count < n-1) {
709 /*
710 * The number of rows we need is n-count. See if we can
711 * find that many rows which each have a zero in all
712 * the positions listed in `set'.
713 */
714 int rows = 0;
715 for (i = 0; i < n; i++) {
716 int ok = TRUE;
717 for (j = 0; j < n; j++)
718 if (set[j] && grid[i*cr+j]) {
719 ok = FALSE;
720 break;
721 }
722 if (ok)
723 rows++;
724 }
725
726 /*
727 * We expect never to be able to get _more_ than
728 * n-count suitable rows: this would imply that (for
729 * example) there are four numbers which between them
730 * have at most three possible positions, and hence it
731 * indicates a faulty deduction before this point or
732 * even a bogus clue.
733 */
ab362080 734 if (rows > n - count) {
735#ifdef STANDALONE_SOLVER
736 if (solver_show_working) {
fdb3b29a 737 va_list ap;
ab362080 738 printf("%*s", solver_recurse_depth*4,
739 "");
ab362080 740 va_start(ap, fmt);
741 vprintf(fmt, ap);
742 va_end(ap);
743 printf(":\n%*s contradiction reached\n",
744 solver_recurse_depth*4, "");
745 }
746#endif
747 return -1;
748 }
749
7c568a48 750 if (rows >= n - count) {
751 int progress = FALSE;
752
753 /*
754 * We've got one! Now, for each row which _doesn't_
755 * satisfy the criterion, eliminate all its set
756 * bits in the positions _not_ listed in `set'.
ab362080 757 * Return +1 (meaning progress has been made) if we
758 * successfully eliminated anything at all.
7c568a48 759 *
760 * This involves referring back through
761 * rowidx/colidx in order to work out which actual
762 * positions in the cube to meddle with.
763 */
764 for (i = 0; i < n; i++) {
765 int ok = TRUE;
766 for (j = 0; j < n; j++)
767 if (set[j] && grid[i*cr+j]) {
768 ok = FALSE;
769 break;
770 }
771 if (!ok) {
772 for (j = 0; j < n; j++)
773 if (!set[j] && grid[i*cr+j]) {
774 int fpos = (start+rowidx[i]*step1+
775 colidx[j]*step2);
776#ifdef STANDALONE_SOLVER
777 if (solver_show_working) {
778 int px, py, pn;
ab362080 779
7c568a48 780 if (!progress) {
fdb3b29a 781 va_list ap;
ab362080 782 printf("%*s", solver_recurse_depth*4,
783 "");
7c568a48 784 va_start(ap, fmt);
785 vprintf(fmt, ap);
786 va_end(ap);
787 printf(":\n");
788 }
789
790 pn = 1 + fpos % cr;
791 py = fpos / cr;
792 px = py / cr;
793 py %= cr;
794
ab362080 795 printf("%*s ruling out %d at (%d,%d)\n",
796 solver_recurse_depth*4, "",
7c568a48 797 pn, 1+px, 1+YUNTRANS(py));
798 }
799#endif
800 progress = TRUE;
801 usage->cube[fpos] = FALSE;
802 }
803 }
804 }
805
806 if (progress) {
ab362080 807 return +1;
7c568a48 808 }
809 }
810 }
811
812 /*
813 * Binary increment: change the rightmost 0 to a 1, and
814 * change all 1s to the right of it to 0s.
815 */
816 i = n;
817 while (i > 0 && set[i-1])
818 set[--i] = 0, count--;
819 if (i > 0)
820 set[--i] = 1, count++;
821 else
822 break; /* done */
823 }
824
ab362080 825 return 0;
7c568a48 826}
827
ab362080 828static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
ab53eb64 829{
ab362080 830 struct solver_scratch *scratch = snew(struct solver_scratch);
ab53eb64 831 int cr = usage->cr;
832 scratch->grid = snewn(cr*cr, unsigned char);
833 scratch->rowidx = snewn(cr, unsigned char);
834 scratch->colidx = snewn(cr, unsigned char);
835 scratch->set = snewn(cr, unsigned char);
836 return scratch;
837}
838
ab362080 839static void solver_free_scratch(struct solver_scratch *scratch)
ab53eb64 840{
841 sfree(scratch->set);
842 sfree(scratch->colidx);
843 sfree(scratch->rowidx);
844 sfree(scratch->grid);
845 sfree(scratch);
846}
847
947a07d6 848static int solver(int c, int r, digit *grid, int maxdiff)
1d8e8ad8 849{
ab362080 850 struct solver_usage *usage;
851 struct solver_scratch *scratch;
1d8e8ad8 852 int cr = c*r;
ab362080 853 int x, y, n, ret;
7c568a48 854 int diff = DIFF_BLOCK;
1d8e8ad8 855
856 /*
857 * Set up a usage structure as a clean slate (everything
858 * possible).
859 */
ab362080 860 usage = snew(struct solver_usage);
1d8e8ad8 861 usage->c = c;
862 usage->r = r;
863 usage->cr = cr;
864 usage->cube = snewn(cr*cr*cr, unsigned char);
865 usage->grid = grid; /* write straight back to the input */
866 memset(usage->cube, TRUE, cr*cr*cr);
867
868 usage->row = snewn(cr * cr, unsigned char);
869 usage->col = snewn(cr * cr, unsigned char);
870 usage->blk = snewn(cr * cr, unsigned char);
871 memset(usage->row, FALSE, cr * cr);
872 memset(usage->col, FALSE, cr * cr);
873 memset(usage->blk, FALSE, cr * cr);
874
ab362080 875 scratch = solver_new_scratch(usage);
ab53eb64 876
1d8e8ad8 877 /*
878 * Place all the clue numbers we are given.
879 */
880 for (x = 0; x < cr; x++)
881 for (y = 0; y < cr; y++)
882 if (grid[y*cr+x])
ab362080 883 solver_place(usage, x, YTRANS(y), grid[y*cr+x]);
1d8e8ad8 884
885 /*
886 * Now loop over the grid repeatedly trying all permitted modes
887 * of reasoning. The loop terminates if we complete an
888 * iteration without making any progress; we then return
889 * failure or success depending on whether the grid is full or
890 * not.
891 */
892 while (1) {
7c568a48 893 /*
894 * I'd like to write `continue;' inside each of the
895 * following loops, so that the solver returns here after
896 * making some progress. However, I can't specify that I
897 * want to continue an outer loop rather than the innermost
898 * one, so I'm apologetically resorting to a goto.
899 */
3ddae0ff 900 cont:
901
1d8e8ad8 902 /*
903 * Blockwise positional elimination.
904 */
4846f788 905 for (x = 0; x < cr; x += r)
1d8e8ad8 906 for (y = 0; y < r; y++)
907 for (n = 1; n <= cr; n++)
ab362080 908 if (!usage->blk[(y*c+(x/r))*cr+n-1]) {
909 ret = solver_elim(usage, cubepos(x,y,n), r*cr
7c568a48 910#ifdef STANDALONE_SOLVER
ab362080 911 , "positional elimination,"
912 " %d in block (%d,%d)", n, 1+x/r, 1+y
7c568a48 913#endif
ab362080 914 );
915 if (ret < 0) {
916 diff = DIFF_IMPOSSIBLE;
917 goto got_result;
918 } else if (ret > 0) {
919 diff = max(diff, DIFF_BLOCK);
920 goto cont;
921 }
7c568a48 922 }
1d8e8ad8 923
ab362080 924 if (maxdiff <= DIFF_BLOCK)
925 break;
926
1d8e8ad8 927 /*
928 * Row-wise positional elimination.
929 */
930 for (y = 0; y < cr; y++)
931 for (n = 1; n <= cr; n++)
ab362080 932 if (!usage->row[y*cr+n-1]) {
933 ret = solver_elim(usage, cubepos(0,y,n), cr*cr
7c568a48 934#ifdef STANDALONE_SOLVER
ab362080 935 , "positional elimination,"
936 " %d in row %d", n, 1+YUNTRANS(y)
7c568a48 937#endif
ab362080 938 );
939 if (ret < 0) {
940 diff = DIFF_IMPOSSIBLE;
941 goto got_result;
942 } else if (ret > 0) {
943 diff = max(diff, DIFF_SIMPLE);
944 goto cont;
945 }
7c568a48 946 }
1d8e8ad8 947 /*
948 * Column-wise positional elimination.
949 */
950 for (x = 0; x < cr; x++)
951 for (n = 1; n <= cr; n++)
ab362080 952 if (!usage->col[x*cr+n-1]) {
953 ret = solver_elim(usage, cubepos(x,0,n), cr
7c568a48 954#ifdef STANDALONE_SOLVER
ab362080 955 , "positional elimination,"
956 " %d in column %d", n, 1+x
7c568a48 957#endif
ab362080 958 );
959 if (ret < 0) {
960 diff = DIFF_IMPOSSIBLE;
961 goto got_result;
962 } else if (ret > 0) {
963 diff = max(diff, DIFF_SIMPLE);
964 goto cont;
965 }
7c568a48 966 }
1d8e8ad8 967
968 /*
969 * Numeric elimination.
970 */
971 for (x = 0; x < cr; x++)
972 for (y = 0; y < cr; y++)
ab362080 973 if (!usage->grid[YUNTRANS(y)*cr+x]) {
974 ret = solver_elim(usage, cubepos(x,y,1), 1
7c568a48 975#ifdef STANDALONE_SOLVER
ab362080 976 , "numeric elimination at (%d,%d)", 1+x,
977 1+YUNTRANS(y)
7c568a48 978#endif
ab362080 979 );
980 if (ret < 0) {
981 diff = DIFF_IMPOSSIBLE;
982 goto got_result;
983 } else if (ret > 0) {
984 diff = max(diff, DIFF_SIMPLE);
985 goto cont;
986 }
7c568a48 987 }
988
ab362080 989 if (maxdiff <= DIFF_SIMPLE)
990 break;
991
7c568a48 992 /*
993 * Intersectional analysis, rows vs blocks.
994 */
995 for (y = 0; y < cr; y++)
996 for (x = 0; x < cr; x += r)
997 for (n = 1; n <= cr; n++)
ab362080 998 /*
999 * solver_intersect() never returns -1.
1000 */
7c568a48 1001 if (!usage->row[y*cr+n-1] &&
1002 !usage->blk[((y%r)*c+(x/r))*cr+n-1] &&
ab362080 1003 (solver_intersect(usage, cubepos(0,y,n), cr*cr,
7c568a48 1004 cubepos(x,y%r,n), r*cr
1005#ifdef STANDALONE_SOLVER
1006 , "intersectional analysis,"
ab362080 1007 " %d in row %d vs block (%d,%d)",
1008 n, 1+YUNTRANS(y), 1+x/r, 1+y%r
7c568a48 1009#endif
1010 ) ||
ab362080 1011 solver_intersect(usage, cubepos(x,y%r,n), r*cr,
7c568a48 1012 cubepos(0,y,n), cr*cr
1013#ifdef STANDALONE_SOLVER
1014 , "intersectional analysis,"
ab362080 1015 " %d in block (%d,%d) vs row %d",
1016 n, 1+x/r, 1+y%r, 1+YUNTRANS(y)
7c568a48 1017#endif
1018 ))) {
1019 diff = max(diff, DIFF_INTERSECT);
1020 goto cont;
1021 }
1022
1023 /*
1024 * Intersectional analysis, columns vs blocks.
1025 */
1026 for (x = 0; x < cr; x++)
1027 for (y = 0; y < r; y++)
1028 for (n = 1; n <= cr; n++)
1029 if (!usage->col[x*cr+n-1] &&
1030 !usage->blk[(y*c+(x/r))*cr+n-1] &&
ab362080 1031 (solver_intersect(usage, cubepos(x,0,n), cr,
7c568a48 1032 cubepos((x/r)*r,y,n), r*cr
1033#ifdef STANDALONE_SOLVER
1034 , "intersectional analysis,"
ab362080 1035 " %d in column %d vs block (%d,%d)",
1036 n, 1+x, 1+x/r, 1+y
7c568a48 1037#endif
1038 ) ||
ab362080 1039 solver_intersect(usage, cubepos((x/r)*r,y,n), r*cr,
7c568a48 1040 cubepos(x,0,n), cr
1041#ifdef STANDALONE_SOLVER
1042 , "intersectional analysis,"
ab362080 1043 " %d in block (%d,%d) vs column %d",
1044 n, 1+x/r, 1+y, 1+x
7c568a48 1045#endif
1046 ))) {
1047 diff = max(diff, DIFF_INTERSECT);
1048 goto cont;
1049 }
1050
ab362080 1051 if (maxdiff <= DIFF_INTERSECT)
1052 break;
1053
7c568a48 1054 /*
1055 * Blockwise set elimination.
1056 */
1057 for (x = 0; x < cr; x += r)
ab362080 1058 for (y = 0; y < r; y++) {
1059 ret = solver_set(usage, scratch, cubepos(x,y,1), r*cr, 1
7c568a48 1060#ifdef STANDALONE_SOLVER
ab362080 1061 , "set elimination, block (%d,%d)", 1+x/r, 1+y
7c568a48 1062#endif
ab362080 1063 );
1064 if (ret < 0) {
1065 diff = DIFF_IMPOSSIBLE;
1066 goto got_result;
1067 } else if (ret > 0) {
1068 diff = max(diff, DIFF_SET);
1069 goto cont;
1070 }
1071 }
7c568a48 1072
1073 /*
1074 * Row-wise set elimination.
1075 */
ab362080 1076 for (y = 0; y < cr; y++) {
1077 ret = solver_set(usage, scratch, cubepos(0,y,1), cr*cr, 1
7c568a48 1078#ifdef STANDALONE_SOLVER
ab362080 1079 , "set elimination, row %d", 1+YUNTRANS(y)
7c568a48 1080#endif
ab362080 1081 );
1082 if (ret < 0) {
1083 diff = DIFF_IMPOSSIBLE;
1084 goto got_result;
1085 } else if (ret > 0) {
1086 diff = max(diff, DIFF_SET);
1087 goto cont;
1088 }
1089 }
7c568a48 1090
1091 /*
1092 * Column-wise set elimination.
1093 */
ab362080 1094 for (x = 0; x < cr; x++) {
1095 ret = solver_set(usage, scratch, cubepos(x,0,1), cr, 1
7c568a48 1096#ifdef STANDALONE_SOLVER
ab362080 1097 , "set elimination, column %d", 1+x
7c568a48 1098#endif
ab362080 1099 );
1100 if (ret < 0) {
1101 diff = DIFF_IMPOSSIBLE;
1102 goto got_result;
1103 } else if (ret > 0) {
1104 diff = max(diff, DIFF_SET);
1105 goto cont;
1106 }
1107 }
1d8e8ad8 1108
1109 /*
1110 * If we reach here, we have made no deductions in this
1111 * iteration, so the algorithm terminates.
1112 */
1113 break;
1114 }
1115
ab362080 1116 /*
1117 * Last chance: if we haven't fully solved the puzzle yet, try
1118 * recursing based on guesses for a particular square. We pick
1119 * one of the most constrained empty squares we can find, which
1120 * has the effect of pruning the search tree as much as
1121 * possible.
1122 */
1123 if (maxdiff >= DIFF_RECURSIVE) {
947a07d6 1124 int best, bestcount;
ab362080 1125
1126 best = -1;
1127 bestcount = cr+1;
ab362080 1128
1129 for (y = 0; y < cr; y++)
1130 for (x = 0; x < cr; x++)
1131 if (!grid[y*cr+x]) {
1132 int count;
1133
1134 /*
1135 * An unfilled square. Count the number of
1136 * possible digits in it.
1137 */
1138 count = 0;
1139 for (n = 1; n <= cr; n++)
1140 if (cube(x,YTRANS(y),n))
1141 count++;
1142
1143 /*
1144 * We should have found any impossibilities
1145 * already, so this can safely be an assert.
1146 */
1147 assert(count > 1);
1148
1149 if (count < bestcount) {
1150 bestcount = count;
947a07d6 1151 best = y*cr+x;
ab362080 1152 }
1153 }
1154
1155 if (best != -1) {
1156 int i, j;
1157 digit *list, *ingrid, *outgrid;
1158
1159 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
1160
1161 /*
1162 * Attempt recursion.
1163 */
1164 y = best / cr;
1165 x = best % cr;
1166
1167 list = snewn(cr, digit);
1168 ingrid = snewn(cr * cr, digit);
1169 outgrid = snewn(cr * cr, digit);
1170 memcpy(ingrid, grid, cr * cr);
1171
1172 /* Make a list of the possible digits. */
1173 for (j = 0, n = 1; n <= cr; n++)
1174 if (cube(x,YTRANS(y),n))
1175 list[j++] = n;
1176
1177#ifdef STANDALONE_SOLVER
1178 if (solver_show_working) {
1179 char *sep = "";
1180 printf("%*srecursing on (%d,%d) [",
1181 solver_recurse_depth*4, "", x, y);
1182 for (i = 0; i < j; i++) {
1183 printf("%s%d", sep, list[i]);
1184 sep = " or ";
1185 }
1186 printf("]\n");
1187 }
1188#endif
1189
ab362080 1190 /*
1191 * And step along the list, recursing back into the
1192 * main solver at every stage.
1193 */
1194 for (i = 0; i < j; i++) {
1195 int ret;
1196
1197 memcpy(outgrid, ingrid, cr * cr);
1198 outgrid[y*cr+x] = list[i];
1199
1200#ifdef STANDALONE_SOLVER
1201 if (solver_show_working)
1202 printf("%*sguessing %d at (%d,%d)\n",
1203 solver_recurse_depth*4, "", list[i], x, y);
1204 solver_recurse_depth++;
1205#endif
1206
947a07d6 1207 ret = solver(c, r, outgrid, maxdiff);
ab362080 1208
1209#ifdef STANDALONE_SOLVER
1210 solver_recurse_depth--;
1211 if (solver_show_working) {
1212 printf("%*sretracting %d at (%d,%d)\n",
1213 solver_recurse_depth*4, "", list[i], x, y);
1214 }
1215#endif
1216
1217 /*
1218 * If we have our first solution, copy it into the
1219 * grid we will return.
1220 */
1221 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1222 memcpy(grid, outgrid, cr*cr);
1223
1224 if (ret == DIFF_AMBIGUOUS)
1225 diff = DIFF_AMBIGUOUS;
1226 else if (ret == DIFF_IMPOSSIBLE)
1227 /* do not change our return value */;
1228 else {
1229 /* the recursion turned up exactly one solution */
1230 if (diff == DIFF_IMPOSSIBLE)
1231 diff = DIFF_RECURSIVE;
1232 else
1233 diff = DIFF_AMBIGUOUS;
1234 }
1235
1236 /*
1237 * As soon as we've found more than one solution,
1238 * give up immediately.
1239 */
1240 if (diff == DIFF_AMBIGUOUS)
1241 break;
1242 }
1243
1244 sfree(outgrid);
1245 sfree(ingrid);
1246 sfree(list);
1247 }
1248
1249 } else {
1250 /*
1251 * We're forbidden to use recursion, so we just see whether
1252 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1253 * otherwise.
1254 */
1255 for (y = 0; y < cr; y++)
1256 for (x = 0; x < cr; x++)
1257 if (!grid[y*cr+x])
1258 diff = DIFF_IMPOSSIBLE;
1259 }
1260
1261 got_result:;
1262
1263#ifdef STANDALONE_SOLVER
1264 if (solver_show_working)
1265 printf("%*s%s found\n",
1266 solver_recurse_depth*4, "",
1267 diff == DIFF_IMPOSSIBLE ? "no solution" :
1268 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1269 "one solution");
1270#endif
ab53eb64 1271
1d8e8ad8 1272 sfree(usage->cube);
1273 sfree(usage->row);
1274 sfree(usage->col);
1275 sfree(usage->blk);
1276 sfree(usage);
1277
ab362080 1278 solver_free_scratch(scratch);
1279
7c568a48 1280 return diff;
1d8e8ad8 1281}
1282
1283/* ----------------------------------------------------------------------
ab362080 1284 * End of solver code.
1285 */
1286
1287/* ----------------------------------------------------------------------
1288 * Solo filled-grid generator.
1289 *
1290 * This grid generator works by essentially trying to solve a grid
1291 * starting from no clues, and not worrying that there's more than
1292 * one possible solution. Unfortunately, it isn't computationally
1293 * feasible to do this by calling the above solver with an empty
1294 * grid, because that one needs to allocate a lot of scratch space
1295 * at every recursion level. Instead, I have a much simpler
1296 * algorithm which I shamelessly copied from a Python solver
1297 * written by Andrew Wilkinson (which is GPLed, but I've reused
1298 * only ideas and no code). It mostly just does the obvious
1299 * recursive thing: pick an empty square, put one of the possible
1300 * digits in it, recurse until all squares are filled, backtrack
1301 * and change some choices if necessary.
1302 *
1303 * The clever bit is that every time it chooses which square to
1304 * fill in next, it does so by counting the number of _possible_
1305 * numbers that can go in each square, and it prioritises so that
1306 * it picks a square with the _lowest_ number of possibilities. The
1307 * idea is that filling in lots of the obvious bits (particularly
1308 * any squares with only one possibility) will cut down on the list
1309 * of possibilities for other squares and hence reduce the enormous
1310 * search space as much as possible as early as possible.
1311 */
1312
1313/*
1314 * Internal data structure used in gridgen to keep track of
1315 * progress.
1316 */
1317struct gridgen_coord { int x, y, r; };
1318struct gridgen_usage {
1319 int c, r, cr; /* cr == c*r */
1320 /* grid is a copy of the input grid, modified as we go along */
1321 digit *grid;
1322 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1323 unsigned char *row;
1324 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1325 unsigned char *col;
1326 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1327 unsigned char *blk;
1328 /* This lists all the empty spaces remaining in the grid. */
1329 struct gridgen_coord *spaces;
1330 int nspaces;
1331 /* If we need randomisation in the solve, this is our random state. */
1332 random_state *rs;
1333};
1334
1335/*
1336 * The real recursive step in the generating function.
1337 */
1338static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1339{
1340 int c = usage->c, r = usage->r, cr = usage->cr;
1341 int i, j, n, sx, sy, bestm, bestr, ret;
1342 int *digits;
1343
1344 /*
1345 * Firstly, check for completion! If there are no spaces left
1346 * in the grid, we have a solution.
1347 */
1348 if (usage->nspaces == 0) {
1349 memcpy(grid, usage->grid, cr * cr);
1350 return TRUE;
1351 }
1352
1353 /*
1354 * Otherwise, there must be at least one space. Find the most
1355 * constrained space, using the `r' field as a tie-breaker.
1356 */
1357 bestm = cr+1; /* so that any space will beat it */
1358 bestr = 0;
1359 i = sx = sy = -1;
1360 for (j = 0; j < usage->nspaces; j++) {
1361 int x = usage->spaces[j].x, y = usage->spaces[j].y;
1362 int m;
1363
1364 /*
1365 * Find the number of digits that could go in this space.
1366 */
1367 m = 0;
1368 for (n = 0; n < cr; n++)
1369 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1370 !usage->blk[((y/c)*c+(x/r))*cr+n])
1371 m++;
1372
1373 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1374 bestm = m;
1375 bestr = usage->spaces[j].r;
1376 sx = x;
1377 sy = y;
1378 i = j;
1379 }
1380 }
1381
1382 /*
1383 * Swap that square into the final place in the spaces array,
1384 * so that decrementing nspaces will remove it from the list.
1385 */
1386 if (i != usage->nspaces-1) {
1387 struct gridgen_coord t;
1388 t = usage->spaces[usage->nspaces-1];
1389 usage->spaces[usage->nspaces-1] = usage->spaces[i];
1390 usage->spaces[i] = t;
1391 }
1392
1393 /*
1394 * Now we've decided which square to start our recursion at,
1395 * simply go through all possible values, shuffling them
1396 * randomly first if necessary.
1397 */
1398 digits = snewn(bestm, int);
1399 j = 0;
1400 for (n = 0; n < cr; n++)
1401 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1402 !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
1403 digits[j++] = n+1;
1404 }
1405
947a07d6 1406 if (usage->rs)
1407 shuffle(digits, j, sizeof(*digits), usage->rs);
ab362080 1408
1409 /* And finally, go through the digit list and actually recurse. */
1410 ret = FALSE;
1411 for (i = 0; i < j; i++) {
1412 n = digits[i];
1413
1414 /* Update the usage structure to reflect the placing of this digit. */
1415 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1416 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
1417 usage->grid[sy*cr+sx] = n;
1418 usage->nspaces--;
1419
1420 /* Call the solver recursively. Stop when we find a solution. */
1421 if (gridgen_real(usage, grid))
1422 ret = TRUE;
1423
1424 /* Revert the usage structure. */
1425 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1426 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
1427 usage->grid[sy*cr+sx] = 0;
1428 usage->nspaces++;
1429
1430 if (ret)
1431 break;
1432 }
1433
1434 sfree(digits);
1435 return ret;
1436}
1437
1438/*
1439 * Entry point to generator. You give it dimensions and a starting
1440 * grid, which is simply an array of cr*cr digits.
1441 */
1442static void gridgen(int c, int r, digit *grid, random_state *rs)
1443{
1444 struct gridgen_usage *usage;
1445 int x, y, cr = c*r;
1446
1447 /*
1448 * Clear the grid to start with.
1449 */
1450 memset(grid, 0, cr*cr);
1451
1452 /*
1453 * Create a gridgen_usage structure.
1454 */
1455 usage = snew(struct gridgen_usage);
1456
1457 usage->c = c;
1458 usage->r = r;
1459 usage->cr = cr;
1460
1461 usage->grid = snewn(cr * cr, digit);
1462 memcpy(usage->grid, grid, cr * cr);
1463
1464 usage->row = snewn(cr * cr, unsigned char);
1465 usage->col = snewn(cr * cr, unsigned char);
1466 usage->blk = snewn(cr * cr, unsigned char);
1467 memset(usage->row, FALSE, cr * cr);
1468 memset(usage->col, FALSE, cr * cr);
1469 memset(usage->blk, FALSE, cr * cr);
1470
1471 usage->spaces = snewn(cr * cr, struct gridgen_coord);
1472 usage->nspaces = 0;
1473
1474 usage->rs = rs;
1475
1476 /*
1477 * Initialise the list of grid spaces.
1478 */
1479 for (y = 0; y < cr; y++) {
1480 for (x = 0; x < cr; x++) {
1481 usage->spaces[usage->nspaces].x = x;
1482 usage->spaces[usage->nspaces].y = y;
1483 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
1484 usage->nspaces++;
1485 }
1486 }
1487
1488 /*
1489 * Run the real generator function.
1490 */
1491 gridgen_real(usage, grid);
1492
1493 /*
1494 * Clean up the usage structure now we have our answer.
1495 */
1496 sfree(usage->spaces);
1497 sfree(usage->blk);
1498 sfree(usage->col);
1499 sfree(usage->row);
1500 sfree(usage->grid);
1501 sfree(usage);
1502}
1503
1504/* ----------------------------------------------------------------------
1505 * End of grid generator code.
1d8e8ad8 1506 */
1507
1508/*
1509 * Check whether a grid contains a valid complete puzzle.
1510 */
1511static int check_valid(int c, int r, digit *grid)
1512{
1513 int cr = c*r;
1514 unsigned char *used;
1515 int x, y, n;
1516
1517 used = snewn(cr, unsigned char);
1518
1519 /*
1520 * Check that each row contains precisely one of everything.
1521 */
1522 for (y = 0; y < cr; y++) {
1523 memset(used, FALSE, cr);
1524 for (x = 0; x < cr; x++)
1525 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1526 used[grid[y*cr+x]-1] = TRUE;
1527 for (n = 0; n < cr; n++)
1528 if (!used[n]) {
1529 sfree(used);
1530 return FALSE;
1531 }
1532 }
1533
1534 /*
1535 * Check that each column contains precisely one of everything.
1536 */
1537 for (x = 0; x < cr; x++) {
1538 memset(used, FALSE, cr);
1539 for (y = 0; y < cr; y++)
1540 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1541 used[grid[y*cr+x]-1] = TRUE;
1542 for (n = 0; n < cr; n++)
1543 if (!used[n]) {
1544 sfree(used);
1545 return FALSE;
1546 }
1547 }
1548
1549 /*
1550 * Check that each block contains precisely one of everything.
1551 */
1552 for (x = 0; x < cr; x += r) {
1553 for (y = 0; y < cr; y += c) {
1554 int xx, yy;
1555 memset(used, FALSE, cr);
1556 for (xx = x; xx < x+r; xx++)
1557 for (yy = 0; yy < y+c; yy++)
1558 if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
1559 used[grid[yy*cr+xx]-1] = TRUE;
1560 for (n = 0; n < cr; n++)
1561 if (!used[n]) {
1562 sfree(used);
1563 return FALSE;
1564 }
1565 }
1566 }
1567
1568 sfree(used);
1569 return TRUE;
1570}
1571
ef57b17d 1572static int symmetries(game_params *params, int x, int y, int *output, int s)
1573{
1574 int c = params->c, r = params->r, cr = c*r;
1575 int i = 0;
1576
154bf9b1 1577#define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
1578
1579 ADD(x, y);
ef57b17d 1580
1581 switch (s) {
1582 case SYMM_NONE:
1583 break; /* just x,y is all we need */
ef57b17d 1584 case SYMM_ROT2:
154bf9b1 1585 ADD(cr - 1 - x, cr - 1 - y);
1586 break;
1587 case SYMM_ROT4:
1588 ADD(cr - 1 - y, x);
1589 ADD(y, cr - 1 - x);
1590 ADD(cr - 1 - x, cr - 1 - y);
1591 break;
1592 case SYMM_REF2:
1593 ADD(cr - 1 - x, y);
1594 break;
1595 case SYMM_REF2D:
1596 ADD(y, x);
1597 break;
1598 case SYMM_REF4:
1599 ADD(cr - 1 - x, y);
1600 ADD(x, cr - 1 - y);
1601 ADD(cr - 1 - x, cr - 1 - y);
1602 break;
1603 case SYMM_REF4D:
1604 ADD(y, x);
1605 ADD(cr - 1 - x, cr - 1 - y);
1606 ADD(cr - 1 - y, cr - 1 - x);
1607 break;
1608 case SYMM_REF8:
1609 ADD(cr - 1 - x, y);
1610 ADD(x, cr - 1 - y);
1611 ADD(cr - 1 - x, cr - 1 - y);
1612 ADD(y, x);
1613 ADD(y, cr - 1 - x);
1614 ADD(cr - 1 - y, x);
1615 ADD(cr - 1 - y, cr - 1 - x);
1616 break;
ef57b17d 1617 }
1618
154bf9b1 1619#undef ADD
1620
ef57b17d 1621 return i;
1622}
1623
c566778e 1624static char *encode_solve_move(int cr, digit *grid)
1625{
1626 int i, len;
1627 char *ret, *p, *sep;
1628
1629 /*
1630 * It's surprisingly easy to work out _exactly_ how long this
1631 * string needs to be. To decimal-encode all the numbers from 1
1632 * to n:
1633 *
1634 * - every number has a units digit; total is n.
1635 * - all numbers above 9 have a tens digit; total is max(n-9,0).
1636 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
1637 * - and so on.
1638 */
1639 len = 0;
1640 for (i = 1; i <= cr; i *= 10)
1641 len += max(cr - i + 1, 0);
1642 len += cr; /* don't forget the commas */
1643 len *= cr; /* there are cr rows of these */
1644
1645 /*
1646 * Now len is one bigger than the total size of the
1647 * comma-separated numbers (because we counted an
1648 * additional leading comma). We need to have a leading S
1649 * and a trailing NUL, so we're off by one in total.
1650 */
1651 len++;
1652
1653 ret = snewn(len, char);
1654 p = ret;
1655 *p++ = 'S';
1656 sep = "";
1657 for (i = 0; i < cr*cr; i++) {
1658 p += sprintf(p, "%s%d", sep, grid[i]);
1659 sep = ",";
1660 }
1661 *p++ = '\0';
1662 assert(p - ret == len);
1663
1664 return ret;
1665}
3220eba4 1666
1185e3c5 1667static char *new_game_desc(game_params *params, random_state *rs,
c566778e 1668 char **aux, int interactive)
1d8e8ad8 1669{
1670 int c = params->c, r = params->r, cr = c*r;
1671 int area = cr*cr;
1672 digit *grid, *grid2;
1673 struct xy { int x, y; } *locs;
1674 int nlocs;
1185e3c5 1675 char *desc;
ef57b17d 1676 int coords[16], ncoords;
154bf9b1 1677 int *symmclasses, nsymmclasses;
de60d8bd 1678 int maxdiff, recursing;
1d8e8ad8 1679
1680 /*
7c568a48 1681 * Adjust the maximum difficulty level to be consistent with
1682 * the puzzle size: all 2x2 puzzles appear to be Trivial
1683 * (DIFF_BLOCK) so we cannot hold out for even a Basic
1684 * (DIFF_SIMPLE) one.
1d8e8ad8 1685 */
7c568a48 1686 maxdiff = params->diff;
1687 if (c == 2 && r == 2)
1688 maxdiff = DIFF_BLOCK;
1d8e8ad8 1689
7c568a48 1690 grid = snewn(area, digit);
ef57b17d 1691 locs = snewn(area, struct xy);
1d8e8ad8 1692 grid2 = snewn(area, digit);
1d8e8ad8 1693
7c568a48 1694 /*
154bf9b1 1695 * Find the set of equivalence classes of squares permitted
1696 * by the selected symmetry. We do this by enumerating all
1697 * the grid squares which have no symmetric companion
1698 * sorting lower than themselves.
1699 */
1700 nsymmclasses = 0;
1701 symmclasses = snewn(cr * cr, int);
1702 {
1703 int x, y;
1704
1705 for (y = 0; y < cr; y++)
1706 for (x = 0; x < cr; x++) {
1707 int i = y*cr+x;
1708 int j;
1709
1710 ncoords = symmetries(params, x, y, coords, params->symm);
1711 for (j = 0; j < ncoords; j++)
1712 if (coords[2*j+1]*cr+coords[2*j] < i)
1713 break;
1714 if (j == ncoords)
1715 symmclasses[nsymmclasses++] = i;
1716 }
1717 }
1718
1719 /*
7c568a48 1720 * Loop until we get a grid of the required difficulty. This is
1721 * nasty, but it seems to be unpleasantly hard to generate
1722 * difficult grids otherwise.
1723 */
1724 do {
1725 /*
ab362080 1726 * Generate a random solved state.
7c568a48 1727 */
ab362080 1728 gridgen(c, r, grid, rs);
7c568a48 1729 assert(check_valid(c, r, grid));
1730
3220eba4 1731 /*
c566778e 1732 * Save the solved grid in aux.
3220eba4 1733 */
1734 {
ab53eb64 1735 /*
1736 * We might already have written *aux the last time we
1737 * went round this loop, in which case we should free
c566778e 1738 * the old aux before overwriting it with the new one.
ab53eb64 1739 */
1740 if (*aux) {
ab53eb64 1741 sfree(*aux);
1742 }
c566778e 1743
1744 *aux = encode_solve_move(cr, grid);
3220eba4 1745 }
1746
7c568a48 1747 /*
1748 * Now we have a solved grid, start removing things from it
1749 * while preserving solubility.
1750 */
de60d8bd 1751 recursing = FALSE;
7c568a48 1752 while (1) {
1753 int x, y, i, j;
1754
1755 /*
1756 * Iterate over the grid and enumerate all the filled
1757 * squares we could empty.
1758 */
1759 nlocs = 0;
1760
154bf9b1 1761 for (i = 0; i < nsymmclasses; i++) {
1762 x = symmclasses[i] % cr;
1763 y = symmclasses[i] / cr;
1764 if (grid[y*cr+x]) {
1765 locs[nlocs].x = x;
1766 locs[nlocs].y = y;
1767 nlocs++;
1768 }
1769 }
7c568a48 1770
1771 /*
1772 * Now shuffle that list.
1773 */
947a07d6 1774 shuffle(locs, nlocs, sizeof(*locs), rs);
7c568a48 1775
1776 /*
1777 * Now loop over the shuffled list and, for each element,
1778 * see whether removing that element (and its reflections)
1779 * from the grid will still leave the grid soluble by
ab362080 1780 * solver.
7c568a48 1781 */
1782 for (i = 0; i < nlocs; i++) {
de60d8bd 1783 int ret;
1784
7c568a48 1785 x = locs[i].x;
1786 y = locs[i].y;
1787
1788 memcpy(grid2, grid, area);
1789 ncoords = symmetries(params, x, y, coords, params->symm);
1790 for (j = 0; j < ncoords; j++)
1791 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1792
947a07d6 1793 ret = solver(c, r, grid2, maxdiff);
ab362080 1794 if (ret != DIFF_IMPOSSIBLE && ret != DIFF_AMBIGUOUS) {
7c568a48 1795 for (j = 0; j < ncoords; j++)
1796 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1797 break;
1798 }
1799 }
1800
1801 if (i == nlocs) {
1802 /*
de60d8bd 1803 * There was nothing we could remove without
ab362080 1804 * destroying solvability. Give up.
7c568a48 1805 */
ab362080 1806 break;
7c568a48 1807 }
1808 }
1d8e8ad8 1809
7c568a48 1810 memcpy(grid2, grid, area);
947a07d6 1811 } while (solver(c, r, grid2, maxdiff) < maxdiff);
1d8e8ad8 1812
1d8e8ad8 1813 sfree(grid2);
1814 sfree(locs);
1815
154bf9b1 1816 sfree(symmclasses);
1817
1d8e8ad8 1818 /*
1819 * Now we have the grid as it will be presented to the user.
1185e3c5 1820 * Encode it in a game desc.
1d8e8ad8 1821 */
1822 {
1823 char *p;
1824 int run, i;
1825
1185e3c5 1826 desc = snewn(5 * area, char);
1827 p = desc;
1d8e8ad8 1828 run = 0;
1829 for (i = 0; i <= area; i++) {
1830 int n = (i < area ? grid[i] : -1);
1831
1832 if (!n)
1833 run++;
1834 else {
1835 if (run) {
1836 while (run > 0) {
1837 int c = 'a' - 1 + run;
1838 if (run > 26)
1839 c = 'z';
1840 *p++ = c;
1841 run -= c - ('a' - 1);
1842 }
1843 } else {
1844 /*
1845 * If there's a number in the very top left or
1846 * bottom right, there's no point putting an
1847 * unnecessary _ before or after it.
1848 */
1185e3c5 1849 if (p > desc && n > 0)
1d8e8ad8 1850 *p++ = '_';
1851 }
1852 if (n > 0)
1853 p += sprintf(p, "%d", n);
1854 run = 0;
1855 }
1856 }
1185e3c5 1857 assert(p - desc < 5 * area);
1d8e8ad8 1858 *p++ = '\0';
1185e3c5 1859 desc = sresize(desc, p - desc, char);
1d8e8ad8 1860 }
1861
1862 sfree(grid);
1863
1185e3c5 1864 return desc;
1d8e8ad8 1865}
1866
1185e3c5 1867static char *validate_desc(game_params *params, char *desc)
1d8e8ad8 1868{
1869 int area = params->r * params->r * params->c * params->c;
1870 int squares = 0;
1871
1185e3c5 1872 while (*desc) {
1873 int n = *desc++;
1d8e8ad8 1874 if (n >= 'a' && n <= 'z') {
1875 squares += n - 'a' + 1;
1876 } else if (n == '_') {
1877 /* do nothing */;
1878 } else if (n > '0' && n <= '9') {
1879 squares++;
1185e3c5 1880 while (*desc >= '0' && *desc <= '9')
1881 desc++;
1d8e8ad8 1882 } else
1185e3c5 1883 return "Invalid character in game description";
1d8e8ad8 1884 }
1885
1886 if (squares < area)
1887 return "Not enough data to fill grid";
1888
1889 if (squares > area)
1890 return "Too much data to fit in grid";
1891
1892 return NULL;
1893}
1894
c380832d 1895static game_state *new_game(midend_data *me, game_params *params, char *desc)
1d8e8ad8 1896{
1897 game_state *state = snew(game_state);
1898 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
1899 int i;
1900
1901 state->c = params->c;
1902 state->r = params->r;
1903
1904 state->grid = snewn(area, digit);
c8266e03 1905 state->pencil = snewn(area * cr, unsigned char);
1906 memset(state->pencil, 0, area * cr);
1d8e8ad8 1907 state->immutable = snewn(area, unsigned char);
1908 memset(state->immutable, FALSE, area);
1909
2ac6d24e 1910 state->completed = state->cheated = FALSE;
1d8e8ad8 1911
1912 i = 0;
1185e3c5 1913 while (*desc) {
1914 int n = *desc++;
1d8e8ad8 1915 if (n >= 'a' && n <= 'z') {
1916 int run = n - 'a' + 1;
1917 assert(i + run <= area);
1918 while (run-- > 0)
1919 state->grid[i++] = 0;
1920 } else if (n == '_') {
1921 /* do nothing */;
1922 } else if (n > '0' && n <= '9') {
1923 assert(i < area);
1924 state->immutable[i] = TRUE;
1185e3c5 1925 state->grid[i++] = atoi(desc-1);
1926 while (*desc >= '0' && *desc <= '9')
1927 desc++;
1d8e8ad8 1928 } else {
1929 assert(!"We can't get here");
1930 }
1931 }
1932 assert(i == area);
1933
1934 return state;
1935}
1936
1937static game_state *dup_game(game_state *state)
1938{
1939 game_state *ret = snew(game_state);
1940 int c = state->c, r = state->r, cr = c*r, area = cr * cr;
1941
1942 ret->c = state->c;
1943 ret->r = state->r;
1944
1945 ret->grid = snewn(area, digit);
1946 memcpy(ret->grid, state->grid, area);
1947
c8266e03 1948 ret->pencil = snewn(area * cr, unsigned char);
1949 memcpy(ret->pencil, state->pencil, area * cr);
1950
1d8e8ad8 1951 ret->immutable = snewn(area, unsigned char);
1952 memcpy(ret->immutable, state->immutable, area);
1953
1954 ret->completed = state->completed;
2ac6d24e 1955 ret->cheated = state->cheated;
1d8e8ad8 1956
1957 return ret;
1958}
1959
1960static void free_game(game_state *state)
1961{
1962 sfree(state->immutable);
c8266e03 1963 sfree(state->pencil);
1d8e8ad8 1964 sfree(state->grid);
1965 sfree(state);
1966}
1967
df11cd4e 1968static char *solve_game(game_state *state, game_state *currstate,
c566778e 1969 char *ai, char **error)
2ac6d24e 1970{
3220eba4 1971 int c = state->c, r = state->r, cr = c*r;
c566778e 1972 char *ret;
df11cd4e 1973 digit *grid;
ab362080 1974 int solve_ret;
2ac6d24e 1975
3220eba4 1976 /*
c566778e 1977 * If we already have the solution in ai, save ourselves some
1978 * time.
3220eba4 1979 */
c566778e 1980 if (ai)
1981 return dupstr(ai);
3220eba4 1982
c566778e 1983 grid = snewn(cr*cr, digit);
1984 memcpy(grid, state->grid, cr*cr);
947a07d6 1985 solve_ret = solver(c, r, grid, DIFF_RECURSIVE);
ab362080 1986
1987 *error = NULL;
df11cd4e 1988
ab362080 1989 if (solve_ret == DIFF_IMPOSSIBLE)
1990 *error = "No solution exists for this puzzle";
1991 else if (solve_ret == DIFF_AMBIGUOUS)
1992 *error = "Multiple solutions exist for this puzzle";
1993
1994 if (*error) {
c566778e 1995 sfree(grid);
c566778e 1996 return NULL;
df11cd4e 1997 }
1998
c566778e 1999 ret = encode_solve_move(cr, grid);
df11cd4e 2000
c566778e 2001 sfree(grid);
2ac6d24e 2002
2003 return ret;
2004}
2005
9b4b03d3 2006static char *grid_text_format(int c, int r, digit *grid)
2007{
2008 int cr = c*r;
2009 int x, y;
2010 int maxlen;
2011 char *ret, *p;
2012
2013 /*
2014 * There are cr lines of digits, plus r-1 lines of block
2015 * separators. Each line contains cr digits, cr-1 separating
2016 * spaces, and c-1 two-character block separators. Thus, the
2017 * total length of a line is 2*cr+2*c-3 (not counting the
2018 * newline), and there are cr+r-1 of them.
2019 */
2020 maxlen = (cr+r-1) * (2*cr+2*c-2);
2021 ret = snewn(maxlen+1, char);
2022 p = ret;
2023
2024 for (y = 0; y < cr; y++) {
2025 for (x = 0; x < cr; x++) {
2026 int ch = grid[y * cr + x];
2027 if (ch == 0)
2028 ch = ' ';
2029 else if (ch <= 9)
2030 ch = '0' + ch;
2031 else
2032 ch = 'a' + ch-10;
2033 *p++ = ch;
2034 if (x+1 < cr) {
2035 *p++ = ' ';
2036 if ((x+1) % r == 0) {
2037 *p++ = '|';
2038 *p++ = ' ';
2039 }
2040 }
2041 }
2042 *p++ = '\n';
2043 if (y+1 < cr && (y+1) % c == 0) {
2044 for (x = 0; x < cr; x++) {
2045 *p++ = '-';
2046 if (x+1 < cr) {
2047 *p++ = '-';
2048 if ((x+1) % r == 0) {
2049 *p++ = '+';
2050 *p++ = '-';
2051 }
2052 }
2053 }
2054 *p++ = '\n';
2055 }
2056 }
2057
2058 assert(p - ret == maxlen);
2059 *p = '\0';
2060 return ret;
2061}
2062
2063static char *game_text_format(game_state *state)
2064{
2065 return grid_text_format(state->c, state->r, state->grid);
2066}
2067
1d8e8ad8 2068struct game_ui {
2069 /*
2070 * These are the coordinates of the currently highlighted
2071 * square on the grid, or -1,-1 if there isn't one. When there
2072 * is, pressing a valid number or letter key or Space will
2073 * enter that number or letter in the grid.
2074 */
2075 int hx, hy;
c8266e03 2076 /*
2077 * This indicates whether the current highlight is a
2078 * pencil-mark one or a real one.
2079 */
2080 int hpencil;
1d8e8ad8 2081};
2082
2083static game_ui *new_ui(game_state *state)
2084{
2085 game_ui *ui = snew(game_ui);
2086
2087 ui->hx = ui->hy = -1;
c8266e03 2088 ui->hpencil = 0;
1d8e8ad8 2089
2090 return ui;
2091}
2092
2093static void free_ui(game_ui *ui)
2094{
2095 sfree(ui);
2096}
2097
844f605f 2098static char *encode_ui(game_ui *ui)
ae8290c6 2099{
2100 return NULL;
2101}
2102
844f605f 2103static void decode_ui(game_ui *ui, char *encoding)
ae8290c6 2104{
2105}
2106
07dfb697 2107static void game_changed_state(game_ui *ui, game_state *oldstate,
2108 game_state *newstate)
2109{
2110 int c = newstate->c, r = newstate->r, cr = c*r;
2111 /*
2112 * We prevent pencil-mode highlighting of a filled square. So
2113 * if the user has just filled in a square which we had a
2114 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
2115 * then we cancel the highlight.
2116 */
2117 if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
2118 newstate->grid[ui->hy * cr + ui->hx] != 0) {
2119 ui->hx = ui->hy = -1;
2120 }
2121}
2122
1e3e152d 2123struct game_drawstate {
2124 int started;
2125 int c, r, cr;
2126 int tilesize;
2127 digit *grid;
2128 unsigned char *pencil;
2129 unsigned char *hl;
2130 /* This is scratch space used within a single call to game_redraw. */
2131 int *entered_items;
2132};
2133
df11cd4e 2134static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2135 int x, int y, int button)
1d8e8ad8 2136{
df11cd4e 2137 int c = state->c, r = state->r, cr = c*r;
1d8e8ad8 2138 int tx, ty;
df11cd4e 2139 char buf[80];
1d8e8ad8 2140
f0ee053c 2141 button &= ~MOD_MASK;
3c833d45 2142
ae812854 2143 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2144 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1d8e8ad8 2145
39d682c9 2146 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
2147 if (button == LEFT_BUTTON) {
df11cd4e 2148 if (state->immutable[ty*cr+tx]) {
39d682c9 2149 ui->hx = ui->hy = -1;
2150 } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
2151 ui->hx = ui->hy = -1;
2152 } else {
2153 ui->hx = tx;
2154 ui->hy = ty;
2155 ui->hpencil = 0;
2156 }
df11cd4e 2157 return ""; /* UI activity occurred */
39d682c9 2158 }
2159 if (button == RIGHT_BUTTON) {
2160 /*
2161 * Pencil-mode highlighting for non filled squares.
2162 */
df11cd4e 2163 if (state->grid[ty*cr+tx] == 0) {
39d682c9 2164 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
2165 ui->hx = ui->hy = -1;
2166 } else {
2167 ui->hpencil = 1;
2168 ui->hx = tx;
2169 ui->hy = ty;
2170 }
2171 } else {
2172 ui->hx = ui->hy = -1;
2173 }
df11cd4e 2174 return ""; /* UI activity occurred */
39d682c9 2175 }
1d8e8ad8 2176 }
2177
2178 if (ui->hx != -1 && ui->hy != -1 &&
2179 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
2180 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
2181 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
2182 button == ' ')) {
2183 int n = button - '0';
2184 if (button >= 'A' && button <= 'Z')
2185 n = button - 'A' + 10;
2186 if (button >= 'a' && button <= 'z')
2187 n = button - 'a' + 10;
2188 if (button == ' ')
2189 n = 0;
2190
39d682c9 2191 /*
2192 * Can't overwrite this square. In principle this shouldn't
2193 * happen anyway because we should never have even been
2194 * able to highlight the square, but it never hurts to be
2195 * careful.
2196 */
df11cd4e 2197 if (state->immutable[ui->hy*cr+ui->hx])
39d682c9 2198 return NULL;
1d8e8ad8 2199
c8266e03 2200 /*
2201 * Can't make pencil marks in a filled square. In principle
2202 * this shouldn't happen anyway because we should never
2203 * have even been able to pencil-highlight the square, but
2204 * it never hurts to be careful.
2205 */
df11cd4e 2206 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
c8266e03 2207 return NULL;
2208
df11cd4e 2209 sprintf(buf, "%c%d,%d,%d",
871bf294 2210 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
df11cd4e 2211
2212 ui->hx = ui->hy = -1;
2213
2214 return dupstr(buf);
2215 }
2216
2217 return NULL;
2218}
2219
2220static game_state *execute_move(game_state *from, char *move)
2221{
2222 int c = from->c, r = from->r, cr = c*r;
2223 game_state *ret;
2224 int x, y, n;
2225
2226 if (move[0] == 'S') {
2227 char *p;
2228
1d8e8ad8 2229 ret = dup_game(from);
df11cd4e 2230 ret->completed = ret->cheated = TRUE;
2231
2232 p = move+1;
2233 for (n = 0; n < cr*cr; n++) {
2234 ret->grid[n] = atoi(p);
2235
2236 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
2237 free_game(ret);
2238 return NULL;
2239 }
2240
2241 while (*p && isdigit((unsigned char)*p)) p++;
2242 if (*p == ',') p++;
2243 }
2244
2245 return ret;
2246 } else if ((move[0] == 'P' || move[0] == 'R') &&
2247 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
2248 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
2249
2250 ret = dup_game(from);
2251 if (move[0] == 'P' && n > 0) {
2252 int index = (y*cr+x) * cr + (n-1);
c8266e03 2253 ret->pencil[index] = !ret->pencil[index];
2254 } else {
df11cd4e 2255 ret->grid[y*cr+x] = n;
2256 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
1d8e8ad8 2257
c8266e03 2258 /*
2259 * We've made a real change to the grid. Check to see
2260 * if the game has been completed.
2261 */
2262 if (!ret->completed && check_valid(c, r, ret->grid)) {
2263 ret->completed = TRUE;
2264 }
2265 }
df11cd4e 2266 return ret;
2267 } else
2268 return NULL; /* couldn't parse move string */
1d8e8ad8 2269}
2270
2271/* ----------------------------------------------------------------------
2272 * Drawing routines.
2273 */
2274
1e3e152d 2275#define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
871bf294 2276#define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
1d8e8ad8 2277
1f3ee4ee 2278static void game_compute_size(game_params *params, int tilesize,
2279 int *x, int *y)
1d8e8ad8 2280{
1f3ee4ee 2281 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2282 struct { int tilesize; } ads, *ds = &ads;
2283 ads.tilesize = tilesize;
1e3e152d 2284
1f3ee4ee 2285 *x = SIZE(params->c * params->r);
2286 *y = SIZE(params->c * params->r);
2287}
1d8e8ad8 2288
1f3ee4ee 2289static void game_set_size(game_drawstate *ds, game_params *params,
2290 int tilesize)
2291{
2292 ds->tilesize = tilesize;
1d8e8ad8 2293}
2294
2295static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2296{
2297 float *ret = snewn(3 * NCOLOURS, float);
2298
2299 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2300
2301 ret[COL_GRID * 3 + 0] = 0.0F;
2302 ret[COL_GRID * 3 + 1] = 0.0F;
2303 ret[COL_GRID * 3 + 2] = 0.0F;
2304
2305 ret[COL_CLUE * 3 + 0] = 0.0F;
2306 ret[COL_CLUE * 3 + 1] = 0.0F;
2307 ret[COL_CLUE * 3 + 2] = 0.0F;
2308
2309 ret[COL_USER * 3 + 0] = 0.0F;
2310 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
2311 ret[COL_USER * 3 + 2] = 0.0F;
2312
2313 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
2314 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
2315 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
2316
7b14a9ec 2317 ret[COL_ERROR * 3 + 0] = 1.0F;
2318 ret[COL_ERROR * 3 + 1] = 0.0F;
2319 ret[COL_ERROR * 3 + 2] = 0.0F;
2320
c8266e03 2321 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2322 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2323 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
2324
1d8e8ad8 2325 *ncolours = NCOLOURS;
2326 return ret;
2327}
2328
2329static game_drawstate *game_new_drawstate(game_state *state)
2330{
2331 struct game_drawstate *ds = snew(struct game_drawstate);
2332 int c = state->c, r = state->r, cr = c*r;
2333
2334 ds->started = FALSE;
2335 ds->c = c;
2336 ds->r = r;
2337 ds->cr = cr;
2338 ds->grid = snewn(cr*cr, digit);
2339 memset(ds->grid, 0, cr*cr);
c8266e03 2340 ds->pencil = snewn(cr*cr*cr, digit);
2341 memset(ds->pencil, 0, cr*cr*cr);
1d8e8ad8 2342 ds->hl = snewn(cr*cr, unsigned char);
2343 memset(ds->hl, 0, cr*cr);
b71dd7fc 2344 ds->entered_items = snewn(cr*cr, int);
1e3e152d 2345 ds->tilesize = 0; /* not decided yet */
1d8e8ad8 2346 return ds;
2347}
2348
2349static void game_free_drawstate(game_drawstate *ds)
2350{
2351 sfree(ds->hl);
c8266e03 2352 sfree(ds->pencil);
1d8e8ad8 2353 sfree(ds->grid);
b71dd7fc 2354 sfree(ds->entered_items);
1d8e8ad8 2355 sfree(ds);
2356}
2357
2358static void draw_number(frontend *fe, game_drawstate *ds, game_state *state,
2359 int x, int y, int hl)
2360{
2361 int c = state->c, r = state->r, cr = c*r;
2362 int tx, ty;
2363 int cx, cy, cw, ch;
2364 char str[2];
2365
c8266e03 2366 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
2367 ds->hl[y*cr+x] == hl &&
2368 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
1d8e8ad8 2369 return; /* no change required */
2370
2371 tx = BORDER + x * TILE_SIZE + 2;
2372 ty = BORDER + y * TILE_SIZE + 2;
2373
2374 cx = tx;
2375 cy = ty;
2376 cw = TILE_SIZE-3;
2377 ch = TILE_SIZE-3;
2378
2379 if (x % r)
2380 cx--, cw++;
2381 if ((x+1) % r)
2382 cw++;
2383 if (y % c)
2384 cy--, ch++;
2385 if ((y+1) % c)
2386 ch++;
2387
2388 clip(fe, cx, cy, cw, ch);
2389
c8266e03 2390 /* background needs erasing */
7b14a9ec 2391 draw_rect(fe, cx, cy, cw, ch, (hl & 15) == 1 ? COL_HIGHLIGHT : COL_BACKGROUND);
c8266e03 2392
2393 /* pencil-mode highlight */
7b14a9ec 2394 if ((hl & 15) == 2) {
c8266e03 2395 int coords[6];
2396 coords[0] = cx;
2397 coords[1] = cy;
2398 coords[2] = cx+cw/2;
2399 coords[3] = cy;
2400 coords[4] = cx;
2401 coords[5] = cy+ch/2;
28b5987d 2402 draw_polygon(fe, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
c8266e03 2403 }
1d8e8ad8 2404
2405 /* new number needs drawing? */
2406 if (state->grid[y*cr+x]) {
2407 str[1] = '\0';
2408 str[0] = state->grid[y*cr+x] + '0';
2409 if (str[0] > '9')
2410 str[0] += 'a' - ('9'+1);
2411 draw_text(fe, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
2412 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
7b14a9ec 2413 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
c8266e03 2414 } else {
edf63745 2415 int i, j, npencil;
2416 int pw, ph, pmax, fontsize;
2417
2418 /* count the pencil marks required */
2419 for (i = npencil = 0; i < cr; i++)
2420 if (state->pencil[(y*cr+x)*cr+i])
2421 npencil++;
2422
2423 /*
2424 * It's not sensible to arrange pencil marks in the same
2425 * layout as the squares within a block, because this leads
2426 * to the font being too small. Instead, we arrange pencil
2427 * marks in the nearest thing we can to a square layout,
2428 * and we adjust the square layout depending on the number
2429 * of pencil marks in the square.
2430 */
2431 for (pw = 1; pw * pw < npencil; pw++);
2432 if (pw < 3) pw = 3; /* otherwise it just looks _silly_ */
2433 ph = (npencil + pw - 1) / pw;
2434 if (ph < 2) ph = 2; /* likewise */
2435 pmax = max(pw, ph);
2436 fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
c8266e03 2437
2438 for (i = j = 0; i < cr; i++)
2439 if (state->pencil[(y*cr+x)*cr+i]) {
edf63745 2440 int dx = j % pw, dy = j / pw;
2441
c8266e03 2442 str[1] = '\0';
2443 str[0] = i + '1';
2444 if (str[0] > '9')
2445 str[0] += 'a' - ('9'+1);
edf63745 2446 draw_text(fe, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
2447 ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
2448 FONT_VARIABLE, fontsize,
c8266e03 2449 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
2450 j++;
2451 }
1d8e8ad8 2452 }
2453
2454 unclip(fe);
2455
2456 draw_update(fe, cx, cy, cw, ch);
2457
2458 ds->grid[y*cr+x] = state->grid[y*cr+x];
c8266e03 2459 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
1d8e8ad8 2460 ds->hl[y*cr+x] = hl;
2461}
2462
2463static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2464 game_state *state, int dir, game_ui *ui,
2465 float animtime, float flashtime)
2466{
2467 int c = state->c, r = state->r, cr = c*r;
2468 int x, y;
2469
2470 if (!ds->started) {
2471 /*
2472 * The initial contents of the window are not guaranteed
2473 * and can vary with front ends. To be on the safe side,
2474 * all games should start by drawing a big
2475 * background-colour rectangle covering the whole window.
2476 */
1e3e152d 2477 draw_rect(fe, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
1d8e8ad8 2478
2479 /*
2480 * Draw the grid.
2481 */
2482 for (x = 0; x <= cr; x++) {
2483 int thick = (x % r ? 0 : 1);
2484 draw_rect(fe, BORDER + x*TILE_SIZE - thick, BORDER-1,
2485 1+2*thick, cr*TILE_SIZE+3, COL_GRID);
2486 }
2487 for (y = 0; y <= cr; y++) {
2488 int thick = (y % c ? 0 : 1);
2489 draw_rect(fe, BORDER-1, BORDER + y*TILE_SIZE - thick,
2490 cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
2491 }
2492 }
2493
2494 /*
7b14a9ec 2495 * This array is used to keep track of rows, columns and boxes
2496 * which contain a number more than once.
2497 */
2498 for (x = 0; x < cr * cr; x++)
b71dd7fc 2499 ds->entered_items[x] = 0;
7b14a9ec 2500 for (x = 0; x < cr; x++)
2501 for (y = 0; y < cr; y++) {
2502 digit d = state->grid[y*cr+x];
2503 if (d) {
2504 int box = (x/r)+(y/c)*c;
b71dd7fc 2505 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
2506 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
2507 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
7b14a9ec 2508 }
2509 }
2510
2511 /*
1d8e8ad8 2512 * Draw any numbers which need redrawing.
2513 */
2514 for (x = 0; x < cr; x++) {
2515 for (y = 0; y < cr; y++) {
c8266e03 2516 int highlight = 0;
7b14a9ec 2517 digit d = state->grid[y*cr+x];
2518
c8266e03 2519 if (flashtime > 0 &&
2520 (flashtime <= FLASH_TIME/3 ||
2521 flashtime >= FLASH_TIME*2/3))
2522 highlight = 1;
7b14a9ec 2523
2524 /* Highlight active input areas. */
c8266e03 2525 if (x == ui->hx && y == ui->hy)
2526 highlight = ui->hpencil ? 2 : 1;
7b14a9ec 2527
2528 /* Mark obvious errors (ie, numbers which occur more than once
2529 * in a single row, column, or box). */
5d744557 2530 if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
2531 (ds->entered_items[y*cr+d-1] & 8) ||
2532 (ds->entered_items[((x/r)+(y/c)*c)*cr+d-1] & 32)))
7b14a9ec 2533 highlight |= 16;
2534
c8266e03 2535 draw_number(fe, ds, state, x, y, highlight);
1d8e8ad8 2536 }
2537 }
2538
2539 /*
2540 * Update the _entire_ grid if necessary.
2541 */
2542 if (!ds->started) {
1e3e152d 2543 draw_update(fe, 0, 0, SIZE(cr), SIZE(cr));
1d8e8ad8 2544 ds->started = TRUE;
2545 }
2546}
2547
2548static float game_anim_length(game_state *oldstate, game_state *newstate,
e3f21163 2549 int dir, game_ui *ui)
1d8e8ad8 2550{
2551 return 0.0F;
2552}
2553
2554static float game_flash_length(game_state *oldstate, game_state *newstate,
e3f21163 2555 int dir, game_ui *ui)
1d8e8ad8 2556{
2ac6d24e 2557 if (!oldstate->completed && newstate->completed &&
2558 !oldstate->cheated && !newstate->cheated)
1d8e8ad8 2559 return FLASH_TIME;
2560 return 0.0F;
2561}
2562
2563static int game_wants_statusbar(void)
2564{
2565 return FALSE;
2566}
2567
4d08de49 2568static int game_timing_state(game_state *state, game_ui *ui)
48dcdd62 2569{
2570 return TRUE;
2571}
2572
1d8e8ad8 2573#ifdef COMBINED
2574#define thegame solo
2575#endif
2576
2577const struct game thegame = {
1d228b10 2578 "Solo", "games.solo",
1d8e8ad8 2579 default_params,
2580 game_fetch_preset,
2581 decode_params,
2582 encode_params,
2583 free_params,
2584 dup_params,
1d228b10 2585 TRUE, game_configure, custom_params,
1d8e8ad8 2586 validate_params,
1185e3c5 2587 new_game_desc,
1185e3c5 2588 validate_desc,
1d8e8ad8 2589 new_game,
2590 dup_game,
2591 free_game,
2ac6d24e 2592 TRUE, solve_game,
9b4b03d3 2593 TRUE, game_text_format,
1d8e8ad8 2594 new_ui,
2595 free_ui,
ae8290c6 2596 encode_ui,
2597 decode_ui,
07dfb697 2598 game_changed_state,
df11cd4e 2599 interpret_move,
2600 execute_move,
1f3ee4ee 2601 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1d8e8ad8 2602 game_colours,
2603 game_new_drawstate,
2604 game_free_drawstate,
2605 game_redraw,
2606 game_anim_length,
2607 game_flash_length,
2608 game_wants_statusbar,
48dcdd62 2609 FALSE, game_timing_state,
93b1da3d 2610 0, /* mouse_priorities */
1d8e8ad8 2611};
3ddae0ff 2612
2613#ifdef STANDALONE_SOLVER
2614
7c568a48 2615/*
2616 * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2617 */
2618
3ddae0ff 2619void frontend_default_colour(frontend *fe, float *output) {}
2620void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
2621 int align, int colour, char *text) {}
2622void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
2623void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
2624void draw_polygon(frontend *fe, int *coords, int npoints,
28b5987d 2625 int fillcolour, int outlinecolour) {}
3ddae0ff 2626void clip(frontend *fe, int x, int y, int w, int h) {}
2627void unclip(frontend *fe) {}
2628void start_draw(frontend *fe) {}
2629void draw_update(frontend *fe, int x, int y, int w, int h) {}
2630void end_draw(frontend *fe) {}
7c568a48 2631unsigned long random_bits(random_state *state, int bits)
2632{ assert(!"Shouldn't get randomness"); return 0; }
2633unsigned long random_upto(random_state *state, unsigned long limit)
2634{ assert(!"Shouldn't get randomness"); return 0; }
947a07d6 2635void shuffle(void *array, int nelts, int eltsize, random_state *rs)
2636{ assert(!"Shouldn't get randomness"); }
3ddae0ff 2637
2638void fatal(char *fmt, ...)
2639{
2640 va_list ap;
2641
2642 fprintf(stderr, "fatal error: ");
2643
2644 va_start(ap, fmt);
2645 vfprintf(stderr, fmt, ap);
2646 va_end(ap);
2647
2648 fprintf(stderr, "\n");
2649 exit(1);
2650}
2651
2652int main(int argc, char **argv)
2653{
2654 game_params *p;
2655 game_state *s;
1185e3c5 2656 char *id = NULL, *desc, *err;
7c568a48 2657 int grade = FALSE;
ab362080 2658 int ret;
3ddae0ff 2659
2660 while (--argc > 0) {
2661 char *p = *++argv;
ab362080 2662 if (!strcmp(p, "-v")) {
7c568a48 2663 solver_show_working = TRUE;
7c568a48 2664 } else if (!strcmp(p, "-g")) {
2665 grade = TRUE;
3ddae0ff 2666 } else if (*p == '-') {
8317499a 2667 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3ddae0ff 2668 return 1;
2669 } else {
2670 id = p;
2671 }
2672 }
2673
2674 if (!id) {
ab362080 2675 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3ddae0ff 2676 return 1;
2677 }
2678
1185e3c5 2679 desc = strchr(id, ':');
2680 if (!desc) {
3ddae0ff 2681 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2682 return 1;
2683 }
1185e3c5 2684 *desc++ = '\0';
3ddae0ff 2685
1733f4ca 2686 p = default_params();
2687 decode_params(p, id);
1185e3c5 2688 err = validate_desc(p, desc);
3ddae0ff 2689 if (err) {
2690 fprintf(stderr, "%s: %s\n", argv[0], err);
2691 return 1;
2692 }
39d682c9 2693 s = new_game(NULL, p, desc);
3ddae0ff 2694
947a07d6 2695 ret = solver(p->c, p->r, s->grid, DIFF_RECURSIVE);
ab362080 2696 if (grade) {
2697 printf("Difficulty rating: %s\n",
2698 ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
2699 ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
2700 ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
2701 ret==DIFF_SET ? "Advanced (set elimination required)":
2702 ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
2703 ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
2704 ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
2705 "INTERNAL ERROR: unrecognised difficulty code");
3ddae0ff 2706 } else {
ab362080 2707 printf("%s\n", grid_text_format(p->c, p->r, s->grid));
3ddae0ff 2708 }
2709
3ddae0ff 2710 return 0;
2711}
2712
2713#endif