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