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