Pedantic tweaks to allow successful compilation on Windows. (gcc
[sgt/puzzles] / solo.c
1 /*
2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3 *
4 * TODO:
5 *
6 * - Jigsaw Sudoku is currently an undocumented feature enabled
7 * by setting r (`Rows of sub-blocks' in the GUI configurer) to
8 * 1. The reason it's undocumented is because they're rather
9 * erratic to generate, because gridgen tends to hang up for
10 * ages. I think this is because some jigsaw block layouts
11 * simply do not admit very many valid filled grids (and
12 * perhaps some have none at all).
13 * + To fix this, I think probably the solution is a change in
14 * grid generation policy: gridgen needs to have less of an
15 * all-or-nothing attitude and instead make only a limited
16 * amount of effort to construct a filled grid before giving
17 * up and trying a new layout. (Come to think of it, this
18 * same change might also make 5x5 standard Sudoku more
19 * practical to generate, if correctly tuned.)
20 * + If I get this fixed, other work needed on jigsaw mode is:
21 * * introduce a GUI config checkbox. game_configure()
22 * ticks this box iff r==1; if it's ticked in a call to
23 * custom_params(), we replace (c, r) with (c*r, 1).
24 * * document it.
25 *
26 * - reports from users are that `Trivial'-mode puzzles are still
27 * rather hard compared to newspapers' easy ones, so some better
28 * low-end difficulty grading would be nice
29 * + it's possible that really easy puzzles always have
30 * _several_ things you can do, so don't make you hunt too
31 * hard for the one deduction you can currently make
32 * + it's also possible that easy puzzles require fewer
33 * cross-eliminations: perhaps there's a higher incidence of
34 * things you can deduce by looking only at (say) rows,
35 * rather than things you have to check both rows and columns
36 * for
37 * + but really, what I need to do is find some really easy
38 * puzzles and _play_ them, to see what's actually easy about
39 * them
40 * + while I'm revamping this area, filling in the _last_
41 * number in a nearly-full row or column should certainly be
42 * permitted even at the lowest difficulty level.
43 * + also Owen noticed that `Basic' grids requiring numeric
44 * elimination are actually very hard, so I wonder if a
45 * difficulty gradation between that and positional-
46 * elimination-only might be in order
47 * + but it's not good to have _too_ many difficulty levels, or
48 * it'll take too long to randomly generate a given level.
49 *
50 * - it might still be nice to do some prioritisation on the
51 * removal of numbers from the grid
52 * + one possibility is to try to minimise the maximum number
53 * of filled squares in any block, which in particular ought
54 * to enforce never leaving a completely filled block in the
55 * puzzle as presented.
56 *
57 * - alternative interface modes
58 * + sudoku.com's Windows program has a palette of possible
59 * entries; you select a palette entry first and then click
60 * on the square you want it to go in, thus enabling
61 * mouse-only play. Useful for PDAs! I don't think it's
62 * actually incompatible with the current highlight-then-type
63 * approach: you _either_ highlight a palette entry and then
64 * click, _or_ you highlight a square and then type. At most
65 * one thing is ever highlighted at a time, so there's no way
66 * to confuse the two.
67 * + then again, I don't actually like sudoku.com's interface;
68 * it's too much like a paint package whereas I prefer to
69 * think of Solo as a text editor.
70 * + another PDA-friendly possibility is a drag interface:
71 * _drag_ numbers from the palette into the grid squares.
72 * Thought experiments suggest I'd prefer that to the
73 * sudoku.com approach, but I haven't actually tried it.
74 */
75
76 /*
77 * Solo puzzles need to be square overall (since each row and each
78 * column must contain one of every digit), but they need not be
79 * subdivided the same way internally. I am going to adopt a
80 * convention whereby I _always_ refer to `r' as the number of rows
81 * of _big_ divisions, and `c' as the number of columns of _big_
82 * divisions. Thus, a 2c by 3r puzzle looks something like this:
83 *
84 * 4 5 1 | 2 6 3
85 * 6 3 2 | 5 4 1
86 * ------+------ (Of course, you can't subdivide it the other way
87 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
88 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
89 * ------+------ box down on the left-hand side.)
90 * 5 1 4 | 3 2 6
91 * 2 6 3 | 1 5 4
92 *
93 * The need for a strong naming convention should now be clear:
94 * each small box is two rows of digits by three columns, while the
95 * overall puzzle has three rows of small boxes by two columns. So
96 * I will (hopefully) consistently use `r' to denote the number of
97 * rows _of small boxes_ (here 3), which is also the number of
98 * columns of digits in each small box; and `c' vice versa (here
99 * 2).
100 *
101 * I'm also going to choose arbitrarily to list c first wherever
102 * possible: the above is a 2x3 puzzle, not a 3x2 one.
103 */
104
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <assert.h>
109 #include <ctype.h>
110 #include <math.h>
111
112 #ifdef STANDALONE_SOLVER
113 #include <stdarg.h>
114 int solver_show_working, solver_recurse_depth;
115 #endif
116
117 #include "puzzles.h"
118
119 /*
120 * To save space, I store digits internally as unsigned char. This
121 * imposes a hard limit of 255 on the order of the puzzle. Since
122 * even a 5x5 takes unacceptably long to generate, I don't see this
123 * as a serious limitation unless something _really_ impressive
124 * happens in computing technology; but here's a typedef anyway for
125 * general good practice.
126 */
127 typedef unsigned char digit;
128 #define ORDER_MAX 255
129
130 #define PREFERRED_TILE_SIZE 32
131 #define TILE_SIZE (ds->tilesize)
132 #define BORDER (TILE_SIZE / 2)
133 #define GRIDEXTRA (TILE_SIZE / 32)
134
135 #define FLASH_TIME 0.4F
136
137 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
138 SYMM_REF4D, SYMM_REF8 };
139
140 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME,
141 DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
142
143 enum {
144 COL_BACKGROUND,
145 COL_XDIAGONALS,
146 COL_GRID,
147 COL_CLUE,
148 COL_USER,
149 COL_HIGHLIGHT,
150 COL_ERROR,
151 COL_PENCIL,
152 NCOLOURS
153 };
154
155 struct game_params {
156 /*
157 * For a square puzzle, `c' and `r' indicate the puzzle
158 * parameters as described above.
159 *
160 * A jigsaw-style puzzle is indicated by r==1, in which case c
161 * can be whatever it likes (there is no constraint on
162 * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
163 */
164 int c, r, symm, diff;
165 int xtype; /* require all digits in X-diagonals */
166 };
167
168 struct block_structure {
169 int refcount;
170
171 /*
172 * For text formatting, we do need c and r here.
173 */
174 int c, r;
175
176 /*
177 * For any square index, whichblock[i] gives its block index.
178 *
179 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
180 * square in block b.
181 *
182 * whichblock and blocks are each dynamically allocated in
183 * their own right, but the subarrays in blocks are appended
184 * to the whichblock array, so shouldn't be freed
185 * individually.
186 */
187 int *whichblock, **blocks;
188
189 #ifdef STANDALONE_SOLVER
190 /*
191 * Textual descriptions of each block. For normal Sudoku these
192 * are of the form "(1,3)"; for jigsaw they are "starting at
193 * (5,7)". So the sensible usage in both cases is to say
194 * "elimination within block %s" with one of these strings.
195 *
196 * Only blocknames itself needs individually freeing; it's all
197 * one block.
198 */
199 char **blocknames;
200 #endif
201 };
202
203 struct game_state {
204 /*
205 * For historical reasons, I use `cr' to denote the overall
206 * width/height of the puzzle. It was a natural notation when
207 * all puzzles were divided into blocks in a grid, but doesn't
208 * really make much sense given jigsaw puzzles. However, the
209 * obvious `n' is heavily used in the solver to describe the
210 * index of a number being placed, so `cr' will have to stay.
211 */
212 int cr;
213 struct block_structure *blocks;
214 int xtype;
215 digit *grid;
216 unsigned char *pencil; /* c*r*c*r elements */
217 unsigned char *immutable; /* marks which digits are clues */
218 int completed, cheated;
219 };
220
221 static game_params *default_params(void)
222 {
223 game_params *ret = snew(game_params);
224
225 ret->c = ret->r = 3;
226 ret->xtype = FALSE;
227 ret->symm = SYMM_ROT2; /* a plausible default */
228 ret->diff = DIFF_BLOCK; /* so is this */
229
230 return ret;
231 }
232
233 static void free_params(game_params *params)
234 {
235 sfree(params);
236 }
237
238 static game_params *dup_params(game_params *params)
239 {
240 game_params *ret = snew(game_params);
241 *ret = *params; /* structure copy */
242 return ret;
243 }
244
245 static int game_fetch_preset(int i, char **name, game_params **params)
246 {
247 static struct {
248 char *title;
249 game_params params;
250 } presets[] = {
251 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, FALSE } },
252 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
253 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, FALSE } },
254 { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
255 { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, TRUE } },
256 { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, FALSE } },
257 { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, FALSE } },
258 { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, TRUE } },
259 { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, FALSE } },
260 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, FALSE } },
261 #ifndef SLOW_SYSTEM
262 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
263 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, FALSE } },
264 #endif
265 };
266
267 if (i < 0 || i >= lenof(presets))
268 return FALSE;
269
270 *name = dupstr(presets[i].title);
271 *params = dup_params(&presets[i].params);
272
273 return TRUE;
274 }
275
276 static void decode_params(game_params *ret, char const *string)
277 {
278 int seen_r = FALSE;
279
280 ret->c = ret->r = atoi(string);
281 ret->xtype = FALSE;
282 while (*string && isdigit((unsigned char)*string)) string++;
283 if (*string == 'x') {
284 string++;
285 ret->r = atoi(string);
286 seen_r = TRUE;
287 while (*string && isdigit((unsigned char)*string)) string++;
288 }
289 while (*string) {
290 if (*string == 'j') {
291 string++;
292 if (seen_r)
293 ret->c *= ret->r;
294 ret->r = 1;
295 } else if (*string == 'x') {
296 string++;
297 ret->xtype = TRUE;
298 } else if (*string == 'r' || *string == 'm' || *string == 'a') {
299 int sn, sc, sd;
300 sc = *string++;
301 if (sc == 'm' && *string == 'd') {
302 sd = TRUE;
303 string++;
304 } else {
305 sd = FALSE;
306 }
307 sn = atoi(string);
308 while (*string && isdigit((unsigned char)*string)) string++;
309 if (sc == 'm' && sn == 8)
310 ret->symm = SYMM_REF8;
311 if (sc == 'm' && sn == 4)
312 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
313 if (sc == 'm' && sn == 2)
314 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
315 if (sc == 'r' && sn == 4)
316 ret->symm = SYMM_ROT4;
317 if (sc == 'r' && sn == 2)
318 ret->symm = SYMM_ROT2;
319 if (sc == 'a')
320 ret->symm = SYMM_NONE;
321 } else if (*string == 'd') {
322 string++;
323 if (*string == 't') /* trivial */
324 string++, ret->diff = DIFF_BLOCK;
325 else if (*string == 'b') /* basic */
326 string++, ret->diff = DIFF_SIMPLE;
327 else if (*string == 'i') /* intermediate */
328 string++, ret->diff = DIFF_INTERSECT;
329 else if (*string == 'a') /* advanced */
330 string++, ret->diff = DIFF_SET;
331 else if (*string == 'e') /* extreme */
332 string++, ret->diff = DIFF_EXTREME;
333 else if (*string == 'u') /* unreasonable */
334 string++, ret->diff = DIFF_RECURSIVE;
335 } else
336 string++; /* eat unknown character */
337 }
338 }
339
340 static char *encode_params(game_params *params, int full)
341 {
342 char str[80];
343
344 if (params->r > 1)
345 sprintf(str, "%dx%d", params->c, params->r);
346 else
347 sprintf(str, "%dj", params->c);
348 if (params->xtype)
349 strcat(str, "x");
350
351 if (full) {
352 switch (params->symm) {
353 case SYMM_REF8: strcat(str, "m8"); break;
354 case SYMM_REF4: strcat(str, "m4"); break;
355 case SYMM_REF4D: strcat(str, "md4"); break;
356 case SYMM_REF2: strcat(str, "m2"); break;
357 case SYMM_REF2D: strcat(str, "md2"); break;
358 case SYMM_ROT4: strcat(str, "r4"); break;
359 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
360 case SYMM_NONE: strcat(str, "a"); break;
361 }
362 switch (params->diff) {
363 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
364 case DIFF_SIMPLE: strcat(str, "db"); break;
365 case DIFF_INTERSECT: strcat(str, "di"); break;
366 case DIFF_SET: strcat(str, "da"); break;
367 case DIFF_EXTREME: strcat(str, "de"); break;
368 case DIFF_RECURSIVE: strcat(str, "du"); break;
369 }
370 }
371 return dupstr(str);
372 }
373
374 static config_item *game_configure(game_params *params)
375 {
376 config_item *ret;
377 char buf[80];
378
379 ret = snewn(6, config_item);
380
381 ret[0].name = "Columns of sub-blocks";
382 ret[0].type = C_STRING;
383 sprintf(buf, "%d", params->c);
384 ret[0].sval = dupstr(buf);
385 ret[0].ival = 0;
386
387 ret[1].name = "Rows of sub-blocks";
388 ret[1].type = C_STRING;
389 sprintf(buf, "%d", params->r);
390 ret[1].sval = dupstr(buf);
391 ret[1].ival = 0;
392
393 ret[2].name = "\"X\" (require every number in each main diagonal)";
394 ret[2].type = C_BOOLEAN;
395 ret[2].sval = NULL;
396 ret[2].ival = params->xtype;
397
398 ret[3].name = "Symmetry";
399 ret[3].type = C_CHOICES;
400 ret[3].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
401 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
402 "8-way mirror";
403 ret[3].ival = params->symm;
404
405 ret[4].name = "Difficulty";
406 ret[4].type = C_CHOICES;
407 ret[4].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
408 ret[4].ival = params->diff;
409
410 ret[5].name = NULL;
411 ret[5].type = C_END;
412 ret[5].sval = NULL;
413 ret[5].ival = 0;
414
415 return ret;
416 }
417
418 static game_params *custom_params(config_item *cfg)
419 {
420 game_params *ret = snew(game_params);
421
422 ret->c = atoi(cfg[0].sval);
423 ret->r = atoi(cfg[1].sval);
424 ret->xtype = cfg[2].ival;
425 ret->symm = cfg[3].ival;
426 ret->diff = cfg[4].ival;
427
428 return ret;
429 }
430
431 static char *validate_params(game_params *params, int full)
432 {
433 if (params->c < 2)
434 return "Both dimensions must be at least 2";
435 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
436 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
437 if ((params->c * params->r) > 35)
438 return "Unable to support more than 35 distinct symbols in a puzzle";
439 return NULL;
440 }
441
442 /* ----------------------------------------------------------------------
443 * Solver.
444 *
445 * This solver is used for two purposes:
446 * + to check solubility of a grid as we gradually remove numbers
447 * from it
448 * + to solve an externally generated puzzle when the user selects
449 * `Solve'.
450 *
451 * It supports a variety of specific modes of reasoning. By
452 * enabling or disabling subsets of these modes we can arrange a
453 * range of difficulty levels.
454 */
455
456 /*
457 * Modes of reasoning currently supported:
458 *
459 * - Positional elimination: a number must go in a particular
460 * square because all the other empty squares in a given
461 * row/col/blk are ruled out.
462 *
463 * - Numeric elimination: a square must have a particular number
464 * in because all the other numbers that could go in it are
465 * ruled out.
466 *
467 * - Intersectional analysis: given two domains which overlap
468 * (hence one must be a block, and the other can be a row or
469 * col), if the possible locations for a particular number in
470 * one of the domains can be narrowed down to the overlap, then
471 * that number can be ruled out everywhere but the overlap in
472 * the other domain too.
473 *
474 * - Set elimination: if there is a subset of the empty squares
475 * within a domain such that the union of the possible numbers
476 * in that subset has the same size as the subset itself, then
477 * those numbers can be ruled out everywhere else in the domain.
478 * (For example, if there are five empty squares and the
479 * possible numbers in each are 12, 23, 13, 134 and 1345, then
480 * the first three empty squares form such a subset: the numbers
481 * 1, 2 and 3 _must_ be in those three squares in some
482 * permutation, and hence we can deduce none of them can be in
483 * the fourth or fifth squares.)
484 * + You can also see this the other way round, concentrating
485 * on numbers rather than squares: if there is a subset of
486 * the unplaced numbers within a domain such that the union
487 * of all their possible positions has the same size as the
488 * subset itself, then all other numbers can be ruled out for
489 * those positions. However, it turns out that this is
490 * exactly equivalent to the first formulation at all times:
491 * there is a 1-1 correspondence between suitable subsets of
492 * the unplaced numbers and suitable subsets of the unfilled
493 * places, found by taking the _complement_ of the union of
494 * the numbers' possible positions (or the spaces' possible
495 * contents).
496 *
497 * - Forcing chains (see comment for solver_forcing().)
498 *
499 * - Recursion. If all else fails, we pick one of the currently
500 * most constrained empty squares and take a random guess at its
501 * contents, then continue solving on that basis and see if we
502 * get any further.
503 */
504
505 struct solver_usage {
506 int cr;
507 struct block_structure *blocks;
508 /*
509 * We set up a cubic array, indexed by x, y and digit; each
510 * element of this array is TRUE or FALSE according to whether
511 * or not that digit _could_ in principle go in that position.
512 *
513 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
514 * are macros below to help with this.
515 */
516 unsigned char *cube;
517 /*
518 * This is the grid in which we write down our final
519 * deductions. y-coordinates in here are _not_ transformed.
520 */
521 digit *grid;
522 /*
523 * Now we keep track, at a slightly higher level, of what we
524 * have yet to work out, to prevent doing the same deduction
525 * many times.
526 */
527 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
528 unsigned char *row;
529 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
530 unsigned char *col;
531 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
532 unsigned char *blk;
533 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
534 unsigned char *diag; /* diag 0 is \, 1 is / */
535 };
536 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
537 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
538 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
539 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
540
541 #define ondiag0(xy) ((xy) % (cr+1) == 0)
542 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
543 #define diag0(i) ((i) * (cr+1))
544 #define diag1(i) ((i+1) * (cr-1))
545
546 /*
547 * Function called when we are certain that a particular square has
548 * a particular number in it. The y-coordinate passed in here is
549 * transformed.
550 */
551 static void solver_place(struct solver_usage *usage, int x, int y, int n)
552 {
553 int cr = usage->cr;
554 int sqindex = y*cr+x;
555 int i, bi;
556
557 assert(cube(x,y,n));
558
559 /*
560 * Rule out all other numbers in this square.
561 */
562 for (i = 1; i <= cr; i++)
563 if (i != n)
564 cube(x,y,i) = FALSE;
565
566 /*
567 * Rule out this number in all other positions in the row.
568 */
569 for (i = 0; i < cr; i++)
570 if (i != y)
571 cube(x,i,n) = FALSE;
572
573 /*
574 * Rule out this number in all other positions in the column.
575 */
576 for (i = 0; i < cr; i++)
577 if (i != x)
578 cube(i,y,n) = FALSE;
579
580 /*
581 * Rule out this number in all other positions in the block.
582 */
583 bi = usage->blocks->whichblock[sqindex];
584 for (i = 0; i < cr; i++) {
585 int bp = usage->blocks->blocks[bi][i];
586 if (bp != sqindex)
587 cube2(bp,n) = FALSE;
588 }
589
590 /*
591 * Enter the number in the result grid.
592 */
593 usage->grid[sqindex] = n;
594
595 /*
596 * Cross out this number from the list of numbers left to place
597 * in its row, its column and its block.
598 */
599 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
600 usage->blk[bi*cr+n-1] = TRUE;
601
602 if (usage->diag) {
603 if (ondiag0(sqindex)) {
604 for (i = 0; i < cr; i++)
605 if (diag0(i) != sqindex)
606 cube2(diag0(i),n) = FALSE;
607 usage->diag[n-1] = TRUE;
608 }
609 if (ondiag1(sqindex)) {
610 for (i = 0; i < cr; i++)
611 if (diag1(i) != sqindex)
612 cube2(diag1(i),n) = FALSE;
613 usage->diag[cr+n-1] = TRUE;
614 }
615 }
616 }
617
618 static int solver_elim(struct solver_usage *usage, int *indices
619 #ifdef STANDALONE_SOLVER
620 , char *fmt, ...
621 #endif
622 )
623 {
624 int cr = usage->cr;
625 int fpos, m, i;
626
627 /*
628 * Count the number of set bits within this section of the
629 * cube.
630 */
631 m = 0;
632 fpos = -1;
633 for (i = 0; i < cr; i++)
634 if (usage->cube[indices[i]]) {
635 fpos = indices[i];
636 m++;
637 }
638
639 if (m == 1) {
640 int x, y, n;
641 assert(fpos >= 0);
642
643 n = 1 + fpos % cr;
644 x = fpos / cr;
645 y = x / cr;
646 x %= cr;
647
648 if (!usage->grid[y*cr+x]) {
649 #ifdef STANDALONE_SOLVER
650 if (solver_show_working) {
651 va_list ap;
652 printf("%*s", solver_recurse_depth*4, "");
653 va_start(ap, fmt);
654 vprintf(fmt, ap);
655 va_end(ap);
656 printf(":\n%*s placing %d at (%d,%d)\n",
657 solver_recurse_depth*4, "", n, 1+x, 1+y);
658 }
659 #endif
660 solver_place(usage, x, y, n);
661 return +1;
662 }
663 } else if (m == 0) {
664 #ifdef STANDALONE_SOLVER
665 if (solver_show_working) {
666 va_list ap;
667 printf("%*s", solver_recurse_depth*4, "");
668 va_start(ap, fmt);
669 vprintf(fmt, ap);
670 va_end(ap);
671 printf(":\n%*s no possibilities available\n",
672 solver_recurse_depth*4, "");
673 }
674 #endif
675 return -1;
676 }
677
678 return 0;
679 }
680
681 static int solver_intersect(struct solver_usage *usage,
682 int *indices1, int *indices2
683 #ifdef STANDALONE_SOLVER
684 , char *fmt, ...
685 #endif
686 )
687 {
688 int cr = usage->cr;
689 int ret, i, j;
690
691 /*
692 * Loop over the first domain and see if there's any set bit
693 * not also in the second.
694 */
695 for (i = j = 0; i < cr; i++) {
696 int p = indices1[i];
697 while (j < cr && indices2[j] < p)
698 j++;
699 if (usage->cube[p]) {
700 if (j < cr && indices2[j] == p)
701 continue; /* both domains contain this index */
702 else
703 return 0; /* there is, so we can't deduce */
704 }
705 }
706
707 /*
708 * We have determined that all set bits in the first domain are
709 * within its overlap with the second. So loop over the second
710 * domain and remove all set bits that aren't also in that
711 * overlap; return +1 iff we actually _did_ anything.
712 */
713 ret = 0;
714 for (i = j = 0; i < cr; i++) {
715 int p = indices2[i];
716 while (j < cr && indices1[j] < p)
717 j++;
718 if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
719 #ifdef STANDALONE_SOLVER
720 if (solver_show_working) {
721 int px, py, pn;
722
723 if (!ret) {
724 va_list ap;
725 printf("%*s", solver_recurse_depth*4, "");
726 va_start(ap, fmt);
727 vprintf(fmt, ap);
728 va_end(ap);
729 printf(":\n");
730 }
731
732 pn = 1 + p % cr;
733 px = p / cr;
734 py = px / cr;
735 px %= cr;
736
737 printf("%*s ruling out %d at (%d,%d)\n",
738 solver_recurse_depth*4, "", pn, 1+px, 1+py);
739 }
740 #endif
741 ret = +1; /* we did something */
742 usage->cube[p] = 0;
743 }
744 }
745
746 return ret;
747 }
748
749 struct solver_scratch {
750 unsigned char *grid, *rowidx, *colidx, *set;
751 int *neighbours, *bfsqueue;
752 int *indexlist, *indexlist2;
753 #ifdef STANDALONE_SOLVER
754 int *bfsprev;
755 #endif
756 };
757
758 static int solver_set(struct solver_usage *usage,
759 struct solver_scratch *scratch,
760 int *indices
761 #ifdef STANDALONE_SOLVER
762 , char *fmt, ...
763 #endif
764 )
765 {
766 int cr = usage->cr;
767 int i, j, n, count;
768 unsigned char *grid = scratch->grid;
769 unsigned char *rowidx = scratch->rowidx;
770 unsigned char *colidx = scratch->colidx;
771 unsigned char *set = scratch->set;
772
773 /*
774 * We are passed a cr-by-cr matrix of booleans. Our first job
775 * is to winnow it by finding any definite placements - i.e.
776 * any row with a solitary 1 - and discarding that row and the
777 * column containing the 1.
778 */
779 memset(rowidx, TRUE, cr);
780 memset(colidx, TRUE, cr);
781 for (i = 0; i < cr; i++) {
782 int count = 0, first = -1;
783 for (j = 0; j < cr; j++)
784 if (usage->cube[indices[i*cr+j]])
785 first = j, count++;
786
787 /*
788 * If count == 0, then there's a row with no 1s at all and
789 * the puzzle is internally inconsistent. However, we ought
790 * to have caught this already during the simpler reasoning
791 * methods, so we can safely fail an assertion if we reach
792 * this point here.
793 */
794 assert(count > 0);
795 if (count == 1)
796 rowidx[i] = colidx[first] = FALSE;
797 }
798
799 /*
800 * Convert each of rowidx/colidx from a list of 0s and 1s to a
801 * list of the indices of the 1s.
802 */
803 for (i = j = 0; i < cr; i++)
804 if (rowidx[i])
805 rowidx[j++] = i;
806 n = j;
807 for (i = j = 0; i < cr; i++)
808 if (colidx[i])
809 colidx[j++] = i;
810 assert(n == j);
811
812 /*
813 * And create the smaller matrix.
814 */
815 for (i = 0; i < n; i++)
816 for (j = 0; j < n; j++)
817 grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
818
819 /*
820 * Having done that, we now have a matrix in which every row
821 * has at least two 1s in. Now we search to see if we can find
822 * a rectangle of zeroes (in the set-theoretic sense of
823 * `rectangle', i.e. a subset of rows crossed with a subset of
824 * columns) whose width and height add up to n.
825 */
826
827 memset(set, 0, n);
828 count = 0;
829 while (1) {
830 /*
831 * We have a candidate set. If its size is <=1 or >=n-1
832 * then we move on immediately.
833 */
834 if (count > 1 && count < n-1) {
835 /*
836 * The number of rows we need is n-count. See if we can
837 * find that many rows which each have a zero in all
838 * the positions listed in `set'.
839 */
840 int rows = 0;
841 for (i = 0; i < n; i++) {
842 int ok = TRUE;
843 for (j = 0; j < n; j++)
844 if (set[j] && grid[i*cr+j]) {
845 ok = FALSE;
846 break;
847 }
848 if (ok)
849 rows++;
850 }
851
852 /*
853 * We expect never to be able to get _more_ than
854 * n-count suitable rows: this would imply that (for
855 * example) there are four numbers which between them
856 * have at most three possible positions, and hence it
857 * indicates a faulty deduction before this point or
858 * even a bogus clue.
859 */
860 if (rows > n - count) {
861 #ifdef STANDALONE_SOLVER
862 if (solver_show_working) {
863 va_list ap;
864 printf("%*s", solver_recurse_depth*4,
865 "");
866 va_start(ap, fmt);
867 vprintf(fmt, ap);
868 va_end(ap);
869 printf(":\n%*s contradiction reached\n",
870 solver_recurse_depth*4, "");
871 }
872 #endif
873 return -1;
874 }
875
876 if (rows >= n - count) {
877 int progress = FALSE;
878
879 /*
880 * We've got one! Now, for each row which _doesn't_
881 * satisfy the criterion, eliminate all its set
882 * bits in the positions _not_ listed in `set'.
883 * Return +1 (meaning progress has been made) if we
884 * successfully eliminated anything at all.
885 *
886 * This involves referring back through
887 * rowidx/colidx in order to work out which actual
888 * positions in the cube to meddle with.
889 */
890 for (i = 0; i < n; i++) {
891 int ok = TRUE;
892 for (j = 0; j < n; j++)
893 if (set[j] && grid[i*cr+j]) {
894 ok = FALSE;
895 break;
896 }
897 if (!ok) {
898 for (j = 0; j < n; j++)
899 if (!set[j] && grid[i*cr+j]) {
900 int fpos = indices[rowidx[i]*cr+colidx[j]];
901 #ifdef STANDALONE_SOLVER
902 if (solver_show_working) {
903 int px, py, pn;
904
905 if (!progress) {
906 va_list ap;
907 printf("%*s", solver_recurse_depth*4,
908 "");
909 va_start(ap, fmt);
910 vprintf(fmt, ap);
911 va_end(ap);
912 printf(":\n");
913 }
914
915 pn = 1 + fpos % cr;
916 px = fpos / cr;
917 py = px / cr;
918 px %= cr;
919
920 printf("%*s ruling out %d at (%d,%d)\n",
921 solver_recurse_depth*4, "",
922 pn, 1+px, 1+py);
923 }
924 #endif
925 progress = TRUE;
926 usage->cube[fpos] = FALSE;
927 }
928 }
929 }
930
931 if (progress) {
932 return +1;
933 }
934 }
935 }
936
937 /*
938 * Binary increment: change the rightmost 0 to a 1, and
939 * change all 1s to the right of it to 0s.
940 */
941 i = n;
942 while (i > 0 && set[i-1])
943 set[--i] = 0, count--;
944 if (i > 0)
945 set[--i] = 1, count++;
946 else
947 break; /* done */
948 }
949
950 return 0;
951 }
952
953 /*
954 * Look for forcing chains. A forcing chain is a path of
955 * pairwise-exclusive squares (i.e. each pair of adjacent squares
956 * in the path are in the same row, column or block) with the
957 * following properties:
958 *
959 * (a) Each square on the path has precisely two possible numbers.
960 *
961 * (b) Each pair of squares which are adjacent on the path share
962 * at least one possible number in common.
963 *
964 * (c) Each square in the middle of the path shares _both_ of its
965 * numbers with at least one of its neighbours (not the same
966 * one with both neighbours).
967 *
968 * These together imply that at least one of the possible number
969 * choices at one end of the path forces _all_ the rest of the
970 * numbers along the path. In order to make real use of this, we
971 * need further properties:
972 *
973 * (c) Ruling out some number N from the square at one end of the
974 * path forces the square at the other end to take the same
975 * number N.
976 *
977 * (d) The two end squares are both in line with some third
978 * square.
979 *
980 * (e) That third square currently has N as a possibility.
981 *
982 * If we can find all of that lot, we can deduce that at least one
983 * of the two ends of the forcing chain has number N, and that
984 * therefore the mutually adjacent third square does not.
985 *
986 * To find forcing chains, we're going to start a bfs at each
987 * suitable square, once for each of its two possible numbers.
988 */
989 static int solver_forcing(struct solver_usage *usage,
990 struct solver_scratch *scratch)
991 {
992 int cr = usage->cr;
993 int *bfsqueue = scratch->bfsqueue;
994 #ifdef STANDALONE_SOLVER
995 int *bfsprev = scratch->bfsprev;
996 #endif
997 unsigned char *number = scratch->grid;
998 int *neighbours = scratch->neighbours;
999 int x, y;
1000
1001 for (y = 0; y < cr; y++)
1002 for (x = 0; x < cr; x++) {
1003 int count, t, n;
1004
1005 /*
1006 * If this square doesn't have exactly two candidate
1007 * numbers, don't try it.
1008 *
1009 * In this loop we also sum the candidate numbers,
1010 * which is a nasty hack to allow us to quickly find
1011 * `the other one' (since we will shortly know there
1012 * are exactly two).
1013 */
1014 for (count = t = 0, n = 1; n <= cr; n++)
1015 if (cube(x, y, n))
1016 count++, t += n;
1017 if (count != 2)
1018 continue;
1019
1020 /*
1021 * Now attempt a bfs for each candidate.
1022 */
1023 for (n = 1; n <= cr; n++)
1024 if (cube(x, y, n)) {
1025 int orign, currn, head, tail;
1026
1027 /*
1028 * Begin a bfs.
1029 */
1030 orign = n;
1031
1032 memset(number, cr+1, cr*cr);
1033 head = tail = 0;
1034 bfsqueue[tail++] = y*cr+x;
1035 #ifdef STANDALONE_SOLVER
1036 bfsprev[y*cr+x] = -1;
1037 #endif
1038 number[y*cr+x] = t - n;
1039
1040 while (head < tail) {
1041 int xx, yy, nneighbours, xt, yt, i;
1042
1043 xx = bfsqueue[head++];
1044 yy = xx / cr;
1045 xx %= cr;
1046
1047 currn = number[yy*cr+xx];
1048
1049 /*
1050 * Find neighbours of yy,xx.
1051 */
1052 nneighbours = 0;
1053 for (yt = 0; yt < cr; yt++)
1054 neighbours[nneighbours++] = yt*cr+xx;
1055 for (xt = 0; xt < cr; xt++)
1056 neighbours[nneighbours++] = yy*cr+xt;
1057 xt = usage->blocks->whichblock[yy*cr+xx];
1058 for (yt = 0; yt < cr; yt++)
1059 neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1060 if (usage->diag) {
1061 int sqindex = yy*cr+xx;
1062 if (ondiag0(sqindex)) {
1063 for (i = 0; i < cr; i++)
1064 neighbours[nneighbours++] = diag0(i);
1065 }
1066 if (ondiag1(sqindex)) {
1067 for (i = 0; i < cr; i++)
1068 neighbours[nneighbours++] = diag1(i);
1069 }
1070 }
1071
1072 /*
1073 * Try visiting each of those neighbours.
1074 */
1075 for (i = 0; i < nneighbours; i++) {
1076 int cc, tt, nn;
1077
1078 xt = neighbours[i] % cr;
1079 yt = neighbours[i] / cr;
1080
1081 /*
1082 * We need this square to not be
1083 * already visited, and to include
1084 * currn as a possible number.
1085 */
1086 if (number[yt*cr+xt] <= cr)
1087 continue;
1088 if (!cube(xt, yt, currn))
1089 continue;
1090
1091 /*
1092 * Don't visit _this_ square a second
1093 * time!
1094 */
1095 if (xt == xx && yt == yy)
1096 continue;
1097
1098 /*
1099 * To continue with the bfs, we need
1100 * this square to have exactly two
1101 * possible numbers.
1102 */
1103 for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1104 if (cube(xt, yt, nn))
1105 cc++, tt += nn;
1106 if (cc == 2) {
1107 bfsqueue[tail++] = yt*cr+xt;
1108 #ifdef STANDALONE_SOLVER
1109 bfsprev[yt*cr+xt] = yy*cr+xx;
1110 #endif
1111 number[yt*cr+xt] = tt - currn;
1112 }
1113
1114 /*
1115 * One other possibility is that this
1116 * might be the square in which we can
1117 * make a real deduction: if it's
1118 * adjacent to x,y, and currn is equal
1119 * to the original number we ruled out.
1120 */
1121 if (currn == orign &&
1122 (xt == x || yt == y ||
1123 (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1124 (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1125 (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1126 #ifdef STANDALONE_SOLVER
1127 if (solver_show_working) {
1128 char *sep = "";
1129 int xl, yl;
1130 printf("%*sforcing chain, %d at ends of ",
1131 solver_recurse_depth*4, "", orign);
1132 xl = xx;
1133 yl = yy;
1134 while (1) {
1135 printf("%s(%d,%d)", sep, 1+xl,
1136 1+yl);
1137 xl = bfsprev[yl*cr+xl];
1138 if (xl < 0)
1139 break;
1140 yl = xl / cr;
1141 xl %= cr;
1142 sep = "-";
1143 }
1144 printf("\n%*s ruling out %d at (%d,%d)\n",
1145 solver_recurse_depth*4, "",
1146 orign, 1+xt, 1+yt);
1147 }
1148 #endif
1149 cube(xt, yt, orign) = FALSE;
1150 return 1;
1151 }
1152 }
1153 }
1154 }
1155 }
1156
1157 return 0;
1158 }
1159
1160 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1161 {
1162 struct solver_scratch *scratch = snew(struct solver_scratch);
1163 int cr = usage->cr;
1164 scratch->grid = snewn(cr*cr, unsigned char);
1165 scratch->rowidx = snewn(cr, unsigned char);
1166 scratch->colidx = snewn(cr, unsigned char);
1167 scratch->set = snewn(cr, unsigned char);
1168 scratch->neighbours = snewn(5*cr, int);
1169 scratch->bfsqueue = snewn(cr*cr, int);
1170 #ifdef STANDALONE_SOLVER
1171 scratch->bfsprev = snewn(cr*cr, int);
1172 #endif
1173 scratch->indexlist = snewn(cr*cr, int); /* used for set elimination */
1174 scratch->indexlist2 = snewn(cr, int); /* only used for intersect() */
1175 return scratch;
1176 }
1177
1178 static void solver_free_scratch(struct solver_scratch *scratch)
1179 {
1180 #ifdef STANDALONE_SOLVER
1181 sfree(scratch->bfsprev);
1182 #endif
1183 sfree(scratch->bfsqueue);
1184 sfree(scratch->neighbours);
1185 sfree(scratch->set);
1186 sfree(scratch->colidx);
1187 sfree(scratch->rowidx);
1188 sfree(scratch->grid);
1189 sfree(scratch->indexlist);
1190 sfree(scratch->indexlist2);
1191 sfree(scratch);
1192 }
1193
1194 static int solver(int cr, struct block_structure *blocks, int xtype,
1195 digit *grid, int maxdiff)
1196 {
1197 struct solver_usage *usage;
1198 struct solver_scratch *scratch;
1199 int x, y, b, i, n, ret;
1200 int diff = DIFF_BLOCK;
1201
1202 /*
1203 * Set up a usage structure as a clean slate (everything
1204 * possible).
1205 */
1206 usage = snew(struct solver_usage);
1207 usage->cr = cr;
1208 usage->blocks = blocks;
1209 usage->cube = snewn(cr*cr*cr, unsigned char);
1210 usage->grid = grid; /* write straight back to the input */
1211 memset(usage->cube, TRUE, cr*cr*cr);
1212
1213 usage->row = snewn(cr * cr, unsigned char);
1214 usage->col = snewn(cr * cr, unsigned char);
1215 usage->blk = snewn(cr * cr, unsigned char);
1216 memset(usage->row, FALSE, cr * cr);
1217 memset(usage->col, FALSE, cr * cr);
1218 memset(usage->blk, FALSE, cr * cr);
1219
1220 if (xtype) {
1221 usage->diag = snewn(cr * 2, unsigned char);
1222 memset(usage->diag, FALSE, cr * 2);
1223 } else
1224 usage->diag = NULL;
1225
1226 scratch = solver_new_scratch(usage);
1227
1228 /*
1229 * Place all the clue numbers we are given.
1230 */
1231 for (x = 0; x < cr; x++)
1232 for (y = 0; y < cr; y++)
1233 if (grid[y*cr+x])
1234 solver_place(usage, x, y, grid[y*cr+x]);
1235
1236 /*
1237 * Now loop over the grid repeatedly trying all permitted modes
1238 * of reasoning. The loop terminates if we complete an
1239 * iteration without making any progress; we then return
1240 * failure or success depending on whether the grid is full or
1241 * not.
1242 */
1243 while (1) {
1244 /*
1245 * I'd like to write `continue;' inside each of the
1246 * following loops, so that the solver returns here after
1247 * making some progress. However, I can't specify that I
1248 * want to continue an outer loop rather than the innermost
1249 * one, so I'm apologetically resorting to a goto.
1250 */
1251 cont:
1252
1253 /*
1254 * Blockwise positional elimination.
1255 */
1256 for (b = 0; b < cr; b++)
1257 for (n = 1; n <= cr; n++)
1258 if (!usage->blk[b*cr+n-1]) {
1259 for (i = 0; i < cr; i++)
1260 scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1261 ret = solver_elim(usage, scratch->indexlist
1262 #ifdef STANDALONE_SOLVER
1263 , "positional elimination,"
1264 " %d in block %s", n,
1265 usage->blocks->blocknames[b]
1266 #endif
1267 );
1268 if (ret < 0) {
1269 diff = DIFF_IMPOSSIBLE;
1270 goto got_result;
1271 } else if (ret > 0) {
1272 diff = max(diff, DIFF_BLOCK);
1273 goto cont;
1274 }
1275 }
1276
1277 if (maxdiff <= DIFF_BLOCK)
1278 break;
1279
1280 /*
1281 * Row-wise positional elimination.
1282 */
1283 for (y = 0; y < cr; y++)
1284 for (n = 1; n <= cr; n++)
1285 if (!usage->row[y*cr+n-1]) {
1286 for (x = 0; x < cr; x++)
1287 scratch->indexlist[x] = cubepos(x, y, n);
1288 ret = solver_elim(usage, scratch->indexlist
1289 #ifdef STANDALONE_SOLVER
1290 , "positional elimination,"
1291 " %d in row %d", n, 1+y
1292 #endif
1293 );
1294 if (ret < 0) {
1295 diff = DIFF_IMPOSSIBLE;
1296 goto got_result;
1297 } else if (ret > 0) {
1298 diff = max(diff, DIFF_SIMPLE);
1299 goto cont;
1300 }
1301 }
1302 /*
1303 * Column-wise positional elimination.
1304 */
1305 for (x = 0; x < cr; x++)
1306 for (n = 1; n <= cr; n++)
1307 if (!usage->col[x*cr+n-1]) {
1308 for (y = 0; y < cr; y++)
1309 scratch->indexlist[y] = cubepos(x, y, n);
1310 ret = solver_elim(usage, scratch->indexlist
1311 #ifdef STANDALONE_SOLVER
1312 , "positional elimination,"
1313 " %d in column %d", n, 1+x
1314 #endif
1315 );
1316 if (ret < 0) {
1317 diff = DIFF_IMPOSSIBLE;
1318 goto got_result;
1319 } else if (ret > 0) {
1320 diff = max(diff, DIFF_SIMPLE);
1321 goto cont;
1322 }
1323 }
1324
1325 /*
1326 * X-diagonal positional elimination.
1327 */
1328 if (usage->diag) {
1329 for (n = 1; n <= cr; n++)
1330 if (!usage->diag[n-1]) {
1331 for (i = 0; i < cr; i++)
1332 scratch->indexlist[i] = cubepos2(diag0(i), n);
1333 ret = solver_elim(usage, scratch->indexlist
1334 #ifdef STANDALONE_SOLVER
1335 , "positional elimination,"
1336 " %d in \\-diagonal", n
1337 #endif
1338 );
1339 if (ret < 0) {
1340 diff = DIFF_IMPOSSIBLE;
1341 goto got_result;
1342 } else if (ret > 0) {
1343 diff = max(diff, DIFF_SIMPLE);
1344 goto cont;
1345 }
1346 }
1347 for (n = 1; n <= cr; n++)
1348 if (!usage->diag[cr+n-1]) {
1349 for (i = 0; i < cr; i++)
1350 scratch->indexlist[i] = cubepos2(diag1(i), n);
1351 ret = solver_elim(usage, scratch->indexlist
1352 #ifdef STANDALONE_SOLVER
1353 , "positional elimination,"
1354 " %d in /-diagonal", n
1355 #endif
1356 );
1357 if (ret < 0) {
1358 diff = DIFF_IMPOSSIBLE;
1359 goto got_result;
1360 } else if (ret > 0) {
1361 diff = max(diff, DIFF_SIMPLE);
1362 goto cont;
1363 }
1364 }
1365 }
1366
1367 /*
1368 * Numeric elimination.
1369 */
1370 for (x = 0; x < cr; x++)
1371 for (y = 0; y < cr; y++)
1372 if (!usage->grid[y*cr+x]) {
1373 for (n = 1; n <= cr; n++)
1374 scratch->indexlist[n-1] = cubepos(x, y, n);
1375 ret = solver_elim(usage, scratch->indexlist
1376 #ifdef STANDALONE_SOLVER
1377 , "numeric elimination at (%d,%d)",
1378 1+x, 1+y
1379 #endif
1380 );
1381 if (ret < 0) {
1382 diff = DIFF_IMPOSSIBLE;
1383 goto got_result;
1384 } else if (ret > 0) {
1385 diff = max(diff, DIFF_SIMPLE);
1386 goto cont;
1387 }
1388 }
1389
1390 if (maxdiff <= DIFF_SIMPLE)
1391 break;
1392
1393 /*
1394 * Intersectional analysis, rows vs blocks.
1395 */
1396 for (y = 0; y < cr; y++)
1397 for (b = 0; b < cr; b++)
1398 for (n = 1; n <= cr; n++) {
1399 if (usage->row[y*cr+n-1] ||
1400 usage->blk[b*cr+n-1])
1401 continue;
1402 for (i = 0; i < cr; i++) {
1403 scratch->indexlist[i] = cubepos(i, y, n);
1404 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1405 }
1406 /*
1407 * solver_intersect() never returns -1.
1408 */
1409 if (solver_intersect(usage, scratch->indexlist,
1410 scratch->indexlist2
1411 #ifdef STANDALONE_SOLVER
1412 , "intersectional analysis,"
1413 " %d in row %d vs block %s",
1414 n, 1+y, usage->blocks->blocknames[b]
1415 #endif
1416 ) ||
1417 solver_intersect(usage, scratch->indexlist2,
1418 scratch->indexlist
1419 #ifdef STANDALONE_SOLVER
1420 , "intersectional analysis,"
1421 " %d in block %s vs row %d",
1422 n, usage->blocks->blocknames[b], 1+y
1423 #endif
1424 )) {
1425 diff = max(diff, DIFF_INTERSECT);
1426 goto cont;
1427 }
1428 }
1429
1430 /*
1431 * Intersectional analysis, columns vs blocks.
1432 */
1433 for (x = 0; x < cr; x++)
1434 for (b = 0; b < cr; b++)
1435 for (n = 1; n <= cr; n++) {
1436 if (usage->col[x*cr+n-1] ||
1437 usage->blk[b*cr+n-1])
1438 continue;
1439 for (i = 0; i < cr; i++) {
1440 scratch->indexlist[i] = cubepos(x, i, n);
1441 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1442 }
1443 if (solver_intersect(usage, scratch->indexlist,
1444 scratch->indexlist2
1445 #ifdef STANDALONE_SOLVER
1446 , "intersectional analysis,"
1447 " %d in column %d vs block %s",
1448 n, 1+x, usage->blocks->blocknames[b]
1449 #endif
1450 ) ||
1451 solver_intersect(usage, scratch->indexlist2,
1452 scratch->indexlist
1453 #ifdef STANDALONE_SOLVER
1454 , "intersectional analysis,"
1455 " %d in block %s vs column %d",
1456 n, usage->blocks->blocknames[b], 1+x
1457 #endif
1458 )) {
1459 diff = max(diff, DIFF_INTERSECT);
1460 goto cont;
1461 }
1462 }
1463
1464 if (usage->diag) {
1465 /*
1466 * Intersectional analysis, \-diagonal vs blocks.
1467 */
1468 for (b = 0; b < cr; b++)
1469 for (n = 1; n <= cr; n++) {
1470 if (usage->diag[n-1] ||
1471 usage->blk[b*cr+n-1])
1472 continue;
1473 for (i = 0; i < cr; i++) {
1474 scratch->indexlist[i] = cubepos2(diag0(i), n);
1475 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1476 }
1477 if (solver_intersect(usage, scratch->indexlist,
1478 scratch->indexlist2
1479 #ifdef STANDALONE_SOLVER
1480 , "intersectional analysis,"
1481 " %d in \\-diagonal vs block %s",
1482 n, 1+x, usage->blocks->blocknames[b]
1483 #endif
1484 ) ||
1485 solver_intersect(usage, scratch->indexlist2,
1486 scratch->indexlist
1487 #ifdef STANDALONE_SOLVER
1488 , "intersectional analysis,"
1489 " %d in block %s vs \\-diagonal",
1490 n, usage->blocks->blocknames[b], 1+x
1491 #endif
1492 )) {
1493 diff = max(diff, DIFF_INTERSECT);
1494 goto cont;
1495 }
1496 }
1497
1498 /*
1499 * Intersectional analysis, /-diagonal vs blocks.
1500 */
1501 for (b = 0; b < cr; b++)
1502 for (n = 1; n <= cr; n++) {
1503 if (usage->diag[cr+n-1] ||
1504 usage->blk[b*cr+n-1])
1505 continue;
1506 for (i = 0; i < cr; i++) {
1507 scratch->indexlist[i] = cubepos2(diag1(i), n);
1508 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
1509 }
1510 if (solver_intersect(usage, scratch->indexlist,
1511 scratch->indexlist2
1512 #ifdef STANDALONE_SOLVER
1513 , "intersectional analysis,"
1514 " %d in /-diagonal vs block %s",
1515 n, 1+x, usage->blocks->blocknames[b]
1516 #endif
1517 ) ||
1518 solver_intersect(usage, scratch->indexlist2,
1519 scratch->indexlist
1520 #ifdef STANDALONE_SOLVER
1521 , "intersectional analysis,"
1522 " %d in block %s vs /-diagonal",
1523 n, usage->blocks->blocknames[b], 1+x
1524 #endif
1525 )) {
1526 diff = max(diff, DIFF_INTERSECT);
1527 goto cont;
1528 }
1529 }
1530 }
1531
1532 if (maxdiff <= DIFF_INTERSECT)
1533 break;
1534
1535 /*
1536 * Blockwise set elimination.
1537 */
1538 for (b = 0; b < cr; b++) {
1539 for (i = 0; i < cr; i++)
1540 for (n = 1; n <= cr; n++)
1541 scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
1542 ret = solver_set(usage, scratch, scratch->indexlist
1543 #ifdef STANDALONE_SOLVER
1544 , "set elimination, block %s",
1545 usage->blocks->blocknames[b]
1546 #endif
1547 );
1548 if (ret < 0) {
1549 diff = DIFF_IMPOSSIBLE;
1550 goto got_result;
1551 } else if (ret > 0) {
1552 diff = max(diff, DIFF_SET);
1553 goto cont;
1554 }
1555 }
1556
1557 /*
1558 * Row-wise set elimination.
1559 */
1560 for (y = 0; y < cr; y++) {
1561 for (x = 0; x < cr; x++)
1562 for (n = 1; n <= cr; n++)
1563 scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
1564 ret = solver_set(usage, scratch, scratch->indexlist
1565 #ifdef STANDALONE_SOLVER
1566 , "set elimination, row %d", 1+y
1567 #endif
1568 );
1569 if (ret < 0) {
1570 diff = DIFF_IMPOSSIBLE;
1571 goto got_result;
1572 } else if (ret > 0) {
1573 diff = max(diff, DIFF_SET);
1574 goto cont;
1575 }
1576 }
1577
1578 /*
1579 * Column-wise set elimination.
1580 */
1581 for (x = 0; x < cr; x++) {
1582 for (y = 0; y < cr; y++)
1583 for (n = 1; n <= cr; n++)
1584 scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
1585 ret = solver_set(usage, scratch, scratch->indexlist
1586 #ifdef STANDALONE_SOLVER
1587 , "set elimination, column %d", 1+x
1588 #endif
1589 );
1590 if (ret < 0) {
1591 diff = DIFF_IMPOSSIBLE;
1592 goto got_result;
1593 } else if (ret > 0) {
1594 diff = max(diff, DIFF_SET);
1595 goto cont;
1596 }
1597 }
1598
1599 if (usage->diag) {
1600 /*
1601 * \-diagonal set elimination.
1602 */
1603 for (i = 0; i < cr; i++)
1604 for (n = 1; n <= cr; n++)
1605 scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
1606 ret = solver_set(usage, scratch, scratch->indexlist
1607 #ifdef STANDALONE_SOLVER
1608 , "set elimination, \\-diagonal"
1609 #endif
1610 );
1611 if (ret < 0) {
1612 diff = DIFF_IMPOSSIBLE;
1613 goto got_result;
1614 } else if (ret > 0) {
1615 diff = max(diff, DIFF_SET);
1616 goto cont;
1617 }
1618
1619 /*
1620 * /-diagonal set elimination.
1621 */
1622 for (i = 0; i < cr; i++)
1623 for (n = 1; n <= cr; n++)
1624 scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
1625 ret = solver_set(usage, scratch, scratch->indexlist
1626 #ifdef STANDALONE_SOLVER
1627 , "set elimination, \\-diagonal"
1628 #endif
1629 );
1630 if (ret < 0) {
1631 diff = DIFF_IMPOSSIBLE;
1632 goto got_result;
1633 } else if (ret > 0) {
1634 diff = max(diff, DIFF_SET);
1635 goto cont;
1636 }
1637 }
1638
1639 if (maxdiff <= DIFF_SET)
1640 break;
1641
1642 /*
1643 * Row-vs-column set elimination on a single number.
1644 */
1645 for (n = 1; n <= cr; n++) {
1646 for (y = 0; y < cr; y++)
1647 for (x = 0; x < cr; x++)
1648 scratch->indexlist[y*cr+x] = cubepos(x, y, n);
1649 ret = solver_set(usage, scratch, scratch->indexlist
1650 #ifdef STANDALONE_SOLVER
1651 , "positional set elimination, number %d", n
1652 #endif
1653 );
1654 if (ret < 0) {
1655 diff = DIFF_IMPOSSIBLE;
1656 goto got_result;
1657 } else if (ret > 0) {
1658 diff = max(diff, DIFF_EXTREME);
1659 goto cont;
1660 }
1661 }
1662
1663 /*
1664 * Forcing chains.
1665 */
1666 if (solver_forcing(usage, scratch)) {
1667 diff = max(diff, DIFF_EXTREME);
1668 goto cont;
1669 }
1670
1671 /*
1672 * If we reach here, we have made no deductions in this
1673 * iteration, so the algorithm terminates.
1674 */
1675 break;
1676 }
1677
1678 /*
1679 * Last chance: if we haven't fully solved the puzzle yet, try
1680 * recursing based on guesses for a particular square. We pick
1681 * one of the most constrained empty squares we can find, which
1682 * has the effect of pruning the search tree as much as
1683 * possible.
1684 */
1685 if (maxdiff >= DIFF_RECURSIVE) {
1686 int best, bestcount;
1687
1688 best = -1;
1689 bestcount = cr+1;
1690
1691 for (y = 0; y < cr; y++)
1692 for (x = 0; x < cr; x++)
1693 if (!grid[y*cr+x]) {
1694 int count;
1695
1696 /*
1697 * An unfilled square. Count the number of
1698 * possible digits in it.
1699 */
1700 count = 0;
1701 for (n = 1; n <= cr; n++)
1702 if (cube(x,y,n))
1703 count++;
1704
1705 /*
1706 * We should have found any impossibilities
1707 * already, so this can safely be an assert.
1708 */
1709 assert(count > 1);
1710
1711 if (count < bestcount) {
1712 bestcount = count;
1713 best = y*cr+x;
1714 }
1715 }
1716
1717 if (best != -1) {
1718 int i, j;
1719 digit *list, *ingrid, *outgrid;
1720
1721 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
1722
1723 /*
1724 * Attempt recursion.
1725 */
1726 y = best / cr;
1727 x = best % cr;
1728
1729 list = snewn(cr, digit);
1730 ingrid = snewn(cr * cr, digit);
1731 outgrid = snewn(cr * cr, digit);
1732 memcpy(ingrid, grid, cr * cr);
1733
1734 /* Make a list of the possible digits. */
1735 for (j = 0, n = 1; n <= cr; n++)
1736 if (cube(x,y,n))
1737 list[j++] = n;
1738
1739 #ifdef STANDALONE_SOLVER
1740 if (solver_show_working) {
1741 char *sep = "";
1742 printf("%*srecursing on (%d,%d) [",
1743 solver_recurse_depth*4, "", x + 1, y + 1);
1744 for (i = 0; i < j; i++) {
1745 printf("%s%d", sep, list[i]);
1746 sep = " or ";
1747 }
1748 printf("]\n");
1749 }
1750 #endif
1751
1752 /*
1753 * And step along the list, recursing back into the
1754 * main solver at every stage.
1755 */
1756 for (i = 0; i < j; i++) {
1757 int ret;
1758
1759 memcpy(outgrid, ingrid, cr * cr);
1760 outgrid[y*cr+x] = list[i];
1761
1762 #ifdef STANDALONE_SOLVER
1763 if (solver_show_working)
1764 printf("%*sguessing %d at (%d,%d)\n",
1765 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1766 solver_recurse_depth++;
1767 #endif
1768
1769 ret = solver(cr, blocks, xtype, outgrid, maxdiff);
1770
1771 #ifdef STANDALONE_SOLVER
1772 solver_recurse_depth--;
1773 if (solver_show_working) {
1774 printf("%*sretracting %d at (%d,%d)\n",
1775 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
1776 }
1777 #endif
1778
1779 /*
1780 * If we have our first solution, copy it into the
1781 * grid we will return.
1782 */
1783 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1784 memcpy(grid, outgrid, cr*cr);
1785
1786 if (ret == DIFF_AMBIGUOUS)
1787 diff = DIFF_AMBIGUOUS;
1788 else if (ret == DIFF_IMPOSSIBLE)
1789 /* do not change our return value */;
1790 else {
1791 /* the recursion turned up exactly one solution */
1792 if (diff == DIFF_IMPOSSIBLE)
1793 diff = DIFF_RECURSIVE;
1794 else
1795 diff = DIFF_AMBIGUOUS;
1796 }
1797
1798 /*
1799 * As soon as we've found more than one solution,
1800 * give up immediately.
1801 */
1802 if (diff == DIFF_AMBIGUOUS)
1803 break;
1804 }
1805
1806 sfree(outgrid);
1807 sfree(ingrid);
1808 sfree(list);
1809 }
1810
1811 } else {
1812 /*
1813 * We're forbidden to use recursion, so we just see whether
1814 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1815 * otherwise.
1816 */
1817 for (y = 0; y < cr; y++)
1818 for (x = 0; x < cr; x++)
1819 if (!grid[y*cr+x])
1820 diff = DIFF_IMPOSSIBLE;
1821 }
1822
1823 got_result:;
1824
1825 #ifdef STANDALONE_SOLVER
1826 if (solver_show_working)
1827 printf("%*s%s found\n",
1828 solver_recurse_depth*4, "",
1829 diff == DIFF_IMPOSSIBLE ? "no solution" :
1830 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1831 "one solution");
1832 #endif
1833
1834 sfree(usage->cube);
1835 sfree(usage->row);
1836 sfree(usage->col);
1837 sfree(usage->blk);
1838 sfree(usage);
1839
1840 solver_free_scratch(scratch);
1841
1842 return diff;
1843 }
1844
1845 /* ----------------------------------------------------------------------
1846 * End of solver code.
1847 */
1848
1849 /* ----------------------------------------------------------------------
1850 * Solo filled-grid generator.
1851 *
1852 * This grid generator works by essentially trying to solve a grid
1853 * starting from no clues, and not worrying that there's more than
1854 * one possible solution. Unfortunately, it isn't computationally
1855 * feasible to do this by calling the above solver with an empty
1856 * grid, because that one needs to allocate a lot of scratch space
1857 * at every recursion level. Instead, I have a much simpler
1858 * algorithm which I shamelessly copied from a Python solver
1859 * written by Andrew Wilkinson (which is GPLed, but I've reused
1860 * only ideas and no code). It mostly just does the obvious
1861 * recursive thing: pick an empty square, put one of the possible
1862 * digits in it, recurse until all squares are filled, backtrack
1863 * and change some choices if necessary.
1864 *
1865 * The clever bit is that every time it chooses which square to
1866 * fill in next, it does so by counting the number of _possible_
1867 * numbers that can go in each square, and it prioritises so that
1868 * it picks a square with the _lowest_ number of possibilities. The
1869 * idea is that filling in lots of the obvious bits (particularly
1870 * any squares with only one possibility) will cut down on the list
1871 * of possibilities for other squares and hence reduce the enormous
1872 * search space as much as possible as early as possible.
1873 */
1874
1875 /*
1876 * Internal data structure used in gridgen to keep track of
1877 * progress.
1878 */
1879 struct gridgen_coord { int x, y, r; };
1880 struct gridgen_usage {
1881 int cr;
1882 struct block_structure *blocks;
1883 /* grid is a copy of the input grid, modified as we go along */
1884 digit *grid;
1885 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1886 unsigned char *row;
1887 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1888 unsigned char *col;
1889 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1890 unsigned char *blk;
1891 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
1892 unsigned char *diag;
1893 /* This lists all the empty spaces remaining in the grid. */
1894 struct gridgen_coord *spaces;
1895 int nspaces;
1896 /* If we need randomisation in the solve, this is our random state. */
1897 random_state *rs;
1898 };
1899
1900 /*
1901 * The real recursive step in the generating function.
1902 *
1903 * Return values: 1 means solution found, 0 means no solution
1904 * found on this branch.
1905 */
1906 static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1907 {
1908 int cr = usage->cr;
1909 int i, j, n, sx, sy, bestm, bestr, ret;
1910 int *digits;
1911
1912 /*
1913 * Firstly, check for completion! If there are no spaces left
1914 * in the grid, we have a solution.
1915 */
1916 if (usage->nspaces == 0) {
1917 memcpy(grid, usage->grid, cr * cr);
1918 return TRUE;
1919 }
1920
1921 /*
1922 * Otherwise, there must be at least one space. Find the most
1923 * constrained space, using the `r' field as a tie-breaker.
1924 */
1925 bestm = cr+1; /* so that any space will beat it */
1926 bestr = 0;
1927 i = sx = sy = -1;
1928 for (j = 0; j < usage->nspaces; j++) {
1929 int x = usage->spaces[j].x, y = usage->spaces[j].y;
1930 int m;
1931
1932 /*
1933 * Find the number of digits that could go in this space.
1934 */
1935 m = 0;
1936 for (n = 0; n < cr; n++)
1937 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1938 !usage->blk[usage->blocks->whichblock[y*cr+x]*cr+n] &&
1939 (!usage->diag || ((!ondiag0(y*cr+x) || !usage->diag[n]) &&
1940 (!ondiag1(y*cr+x) || !usage->diag[cr+n]))))
1941 m++;
1942
1943 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1944 bestm = m;
1945 bestr = usage->spaces[j].r;
1946 sx = x;
1947 sy = y;
1948 i = j;
1949 }
1950 }
1951
1952 /*
1953 * Swap that square into the final place in the spaces array,
1954 * so that decrementing nspaces will remove it from the list.
1955 */
1956 if (i != usage->nspaces-1) {
1957 struct gridgen_coord t;
1958 t = usage->spaces[usage->nspaces-1];
1959 usage->spaces[usage->nspaces-1] = usage->spaces[i];
1960 usage->spaces[i] = t;
1961 }
1962
1963 /*
1964 * Now we've decided which square to start our recursion at,
1965 * simply go through all possible values, shuffling them
1966 * randomly first if necessary.
1967 */
1968 digits = snewn(bestm, int);
1969 j = 0;
1970 for (n = 0; n < cr; n++)
1971 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1972 !usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n] &&
1973 (!usage->diag || ((!ondiag0(sy*cr+sx) || !usage->diag[n]) &&
1974 (!ondiag1(sy*cr+sx) || !usage->diag[cr+n])))) {
1975 digits[j++] = n+1;
1976 }
1977
1978 if (usage->rs)
1979 shuffle(digits, j, sizeof(*digits), usage->rs);
1980
1981 /* And finally, go through the digit list and actually recurse. */
1982 ret = FALSE;
1983 for (i = 0; i < j; i++) {
1984 n = digits[i];
1985
1986 /* Update the usage structure to reflect the placing of this digit. */
1987 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1988 usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n-1] = TRUE;
1989 if (usage->diag) {
1990 if (ondiag0(sy*cr+sx))
1991 usage->diag[n-1] = TRUE;
1992 if (ondiag1(sy*cr+sx))
1993 usage->diag[cr+n-1] = TRUE;
1994 }
1995 usage->grid[sy*cr+sx] = n;
1996 usage->nspaces--;
1997
1998 /* Call the solver recursively. Stop when we find a solution. */
1999 if (gridgen_real(usage, grid))
2000 ret = TRUE;
2001
2002 /* Revert the usage structure. */
2003 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
2004 usage->blk[usage->blocks->whichblock[sy*cr+sx]*cr+n-1] = FALSE;
2005 if (usage->diag) {
2006 if (ondiag0(sy*cr+sx))
2007 usage->diag[n-1] = FALSE;
2008 if (ondiag1(sy*cr+sx))
2009 usage->diag[cr+n-1] = FALSE;
2010 }
2011 usage->grid[sy*cr+sx] = 0;
2012 usage->nspaces++;
2013
2014 if (ret)
2015 break;
2016 }
2017
2018 sfree(digits);
2019 return ret;
2020 }
2021
2022 /*
2023 * Entry point to generator. You give it parameters and a starting
2024 * grid, which is simply an array of cr*cr digits.
2025 */
2026 static int gridgen(int cr, struct block_structure *blocks, int xtype,
2027 digit *grid, random_state *rs)
2028 {
2029 struct gridgen_usage *usage;
2030 int x, y, ret;
2031
2032 /*
2033 * Clear the grid to start with.
2034 */
2035 memset(grid, 0, cr*cr);
2036
2037 /*
2038 * Create a gridgen_usage structure.
2039 */
2040 usage = snew(struct gridgen_usage);
2041
2042 usage->cr = cr;
2043 usage->blocks = blocks;
2044
2045 usage->grid = snewn(cr * cr, digit);
2046 memcpy(usage->grid, grid, cr * cr);
2047
2048 usage->row = snewn(cr * cr, unsigned char);
2049 usage->col = snewn(cr * cr, unsigned char);
2050 usage->blk = snewn(cr * cr, unsigned char);
2051 memset(usage->row, FALSE, cr * cr);
2052 memset(usage->col, FALSE, cr * cr);
2053 memset(usage->blk, FALSE, cr * cr);
2054
2055 if (xtype) {
2056 usage->diag = snewn(2 * cr, unsigned char);
2057 memset(usage->diag, FALSE, 2 * cr);
2058 } else {
2059 usage->diag = NULL;
2060 }
2061
2062 usage->spaces = snewn(cr * cr, struct gridgen_coord);
2063 usage->nspaces = 0;
2064
2065 usage->rs = rs;
2066
2067 /*
2068 * Initialise the list of grid spaces.
2069 */
2070 for (y = 0; y < cr; y++) {
2071 for (x = 0; x < cr; x++) {
2072 usage->spaces[usage->nspaces].x = x;
2073 usage->spaces[usage->nspaces].y = y;
2074 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2075 usage->nspaces++;
2076 }
2077 }
2078
2079 /*
2080 * Run the real generator function.
2081 */
2082 ret = gridgen_real(usage, grid);
2083
2084 /*
2085 * Clean up the usage structure now we have our answer.
2086 */
2087 sfree(usage->spaces);
2088 sfree(usage->blk);
2089 sfree(usage->col);
2090 sfree(usage->row);
2091 sfree(usage->grid);
2092 sfree(usage);
2093
2094 return ret;
2095 }
2096
2097 /* ----------------------------------------------------------------------
2098 * End of grid generator code.
2099 */
2100
2101 /*
2102 * Check whether a grid contains a valid complete puzzle.
2103 */
2104 static int check_valid(int cr, struct block_structure *blocks, int xtype,
2105 digit *grid)
2106 {
2107 unsigned char *used;
2108 int x, y, i, j, n;
2109
2110 used = snewn(cr, unsigned char);
2111
2112 /*
2113 * Check that each row contains precisely one of everything.
2114 */
2115 for (y = 0; y < cr; y++) {
2116 memset(used, FALSE, cr);
2117 for (x = 0; x < cr; x++)
2118 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2119 used[grid[y*cr+x]-1] = TRUE;
2120 for (n = 0; n < cr; n++)
2121 if (!used[n]) {
2122 sfree(used);
2123 return FALSE;
2124 }
2125 }
2126
2127 /*
2128 * Check that each column contains precisely one of everything.
2129 */
2130 for (x = 0; x < cr; x++) {
2131 memset(used, FALSE, cr);
2132 for (y = 0; y < cr; y++)
2133 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2134 used[grid[y*cr+x]-1] = TRUE;
2135 for (n = 0; n < cr; n++)
2136 if (!used[n]) {
2137 sfree(used);
2138 return FALSE;
2139 }
2140 }
2141
2142 /*
2143 * Check that each block contains precisely one of everything.
2144 */
2145 for (i = 0; i < cr; i++) {
2146 memset(used, FALSE, cr);
2147 for (j = 0; j < cr; j++)
2148 if (grid[blocks->blocks[i][j]] > 0 &&
2149 grid[blocks->blocks[i][j]] <= cr)
2150 used[grid[blocks->blocks[i][j]]-1] = TRUE;
2151 for (n = 0; n < cr; n++)
2152 if (!used[n]) {
2153 sfree(used);
2154 return FALSE;
2155 }
2156 }
2157
2158 /*
2159 * Check that each diagonal contains precisely one of everything.
2160 */
2161 if (xtype) {
2162 memset(used, FALSE, cr);
2163 for (i = 0; i < cr; i++)
2164 if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
2165 used[grid[diag0(i)]-1] = TRUE;
2166 for (n = 0; n < cr; n++)
2167 if (!used[n]) {
2168 sfree(used);
2169 return FALSE;
2170 }
2171 for (i = 0; i < cr; i++)
2172 if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
2173 used[grid[diag1(i)]-1] = TRUE;
2174 for (n = 0; n < cr; n++)
2175 if (!used[n]) {
2176 sfree(used);
2177 return FALSE;
2178 }
2179 }
2180
2181 sfree(used);
2182 return TRUE;
2183 }
2184
2185 static int symmetries(game_params *params, int x, int y, int *output, int s)
2186 {
2187 int c = params->c, r = params->r, cr = c*r;
2188 int i = 0;
2189
2190 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2191
2192 ADD(x, y);
2193
2194 switch (s) {
2195 case SYMM_NONE:
2196 break; /* just x,y is all we need */
2197 case SYMM_ROT2:
2198 ADD(cr - 1 - x, cr - 1 - y);
2199 break;
2200 case SYMM_ROT4:
2201 ADD(cr - 1 - y, x);
2202 ADD(y, cr - 1 - x);
2203 ADD(cr - 1 - x, cr - 1 - y);
2204 break;
2205 case SYMM_REF2:
2206 ADD(cr - 1 - x, y);
2207 break;
2208 case SYMM_REF2D:
2209 ADD(y, x);
2210 break;
2211 case SYMM_REF4:
2212 ADD(cr - 1 - x, y);
2213 ADD(x, cr - 1 - y);
2214 ADD(cr - 1 - x, cr - 1 - y);
2215 break;
2216 case SYMM_REF4D:
2217 ADD(y, x);
2218 ADD(cr - 1 - x, cr - 1 - y);
2219 ADD(cr - 1 - y, cr - 1 - x);
2220 break;
2221 case SYMM_REF8:
2222 ADD(cr - 1 - x, y);
2223 ADD(x, cr - 1 - y);
2224 ADD(cr - 1 - x, cr - 1 - y);
2225 ADD(y, x);
2226 ADD(y, cr - 1 - x);
2227 ADD(cr - 1 - y, x);
2228 ADD(cr - 1 - y, cr - 1 - x);
2229 break;
2230 }
2231
2232 #undef ADD
2233
2234 return i;
2235 }
2236
2237 static char *encode_solve_move(int cr, digit *grid)
2238 {
2239 int i, len;
2240 char *ret, *p, *sep;
2241
2242 /*
2243 * It's surprisingly easy to work out _exactly_ how long this
2244 * string needs to be. To decimal-encode all the numbers from 1
2245 * to n:
2246 *
2247 * - every number has a units digit; total is n.
2248 * - all numbers above 9 have a tens digit; total is max(n-9,0).
2249 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2250 * - and so on.
2251 */
2252 len = 0;
2253 for (i = 1; i <= cr; i *= 10)
2254 len += max(cr - i + 1, 0);
2255 len += cr; /* don't forget the commas */
2256 len *= cr; /* there are cr rows of these */
2257
2258 /*
2259 * Now len is one bigger than the total size of the
2260 * comma-separated numbers (because we counted an
2261 * additional leading comma). We need to have a leading S
2262 * and a trailing NUL, so we're off by one in total.
2263 */
2264 len++;
2265
2266 ret = snewn(len, char);
2267 p = ret;
2268 *p++ = 'S';
2269 sep = "";
2270 for (i = 0; i < cr*cr; i++) {
2271 p += sprintf(p, "%s%d", sep, grid[i]);
2272 sep = ",";
2273 }
2274 *p++ = '\0';
2275 assert(p - ret == len);
2276
2277 return ret;
2278 }
2279
2280 static char *new_game_desc(game_params *params, random_state *rs,
2281 char **aux, int interactive)
2282 {
2283 int c = params->c, r = params->r, cr = c*r;
2284 int area = cr*cr;
2285 struct block_structure *blocks;
2286 digit *grid, *grid2;
2287 struct xy { int x, y; } *locs;
2288 int nlocs;
2289 char *desc;
2290 int coords[16], ncoords;
2291 int maxdiff;
2292 int x, y, i, j;
2293
2294 /*
2295 * Adjust the maximum difficulty level to be consistent with
2296 * the puzzle size: all 2x2 puzzles appear to be Trivial
2297 * (DIFF_BLOCK) so we cannot hold out for even a Basic
2298 * (DIFF_SIMPLE) one.
2299 */
2300 maxdiff = params->diff;
2301 if (c == 2 && r == 2)
2302 maxdiff = DIFF_BLOCK;
2303
2304 grid = snewn(area, digit);
2305 locs = snewn(area, struct xy);
2306 grid2 = snewn(area, digit);
2307
2308 blocks = snew(struct block_structure);
2309 blocks->c = params->c; blocks->r = params->r;
2310 blocks->whichblock = snewn(area*2, int);
2311 blocks->blocks = snewn(cr, int *);
2312 for (i = 0; i < cr; i++)
2313 blocks->blocks[i] = blocks->whichblock + area + i*cr;
2314 #ifdef STANDALONE_SOLVER
2315 assert(!"This should never happen, so we don't need to create blocknames");
2316 #endif
2317
2318 /*
2319 * Loop until we get a grid of the required difficulty. This is
2320 * nasty, but it seems to be unpleasantly hard to generate
2321 * difficult grids otherwise.
2322 */
2323 while (1) {
2324 /*
2325 * Generate a random solved state, starting by
2326 * constructing the block structure.
2327 */
2328 if (r == 1) { /* jigsaw mode */
2329 int *dsf = divvy_rectangle(cr, cr, cr, rs);
2330 int nb = 0;
2331
2332 for (i = 0; i < area; i++)
2333 blocks->whichblock[i] = -1;
2334 for (i = 0; i < area; i++) {
2335 int j = dsf_canonify(dsf, i);
2336 if (blocks->whichblock[j] < 0)
2337 blocks->whichblock[j] = nb++;
2338 blocks->whichblock[i] = blocks->whichblock[j];
2339 }
2340 assert(nb == cr);
2341
2342 sfree(dsf);
2343 } else { /* basic Sudoku mode */
2344 for (y = 0; y < cr; y++)
2345 for (x = 0; x < cr; x++)
2346 blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2347 }
2348 for (i = 0; i < cr; i++)
2349 blocks->blocks[i][cr-1] = 0;
2350 for (i = 0; i < area; i++) {
2351 int b = blocks->whichblock[i];
2352 j = blocks->blocks[b][cr-1]++;
2353 assert(j < cr);
2354 blocks->blocks[b][j] = i;
2355 }
2356
2357 if (!gridgen(cr, blocks, params->xtype, grid, rs))
2358 continue; /* this might happen if the jigsaw is unsuitable */
2359 assert(check_valid(cr, blocks, params->xtype, grid));
2360
2361 /*
2362 * Save the solved grid in aux.
2363 */
2364 {
2365 /*
2366 * We might already have written *aux the last time we
2367 * went round this loop, in which case we should free
2368 * the old aux before overwriting it with the new one.
2369 */
2370 if (*aux) {
2371 sfree(*aux);
2372 }
2373
2374 *aux = encode_solve_move(cr, grid);
2375 }
2376
2377 /*
2378 * Now we have a solved grid, start removing things from it
2379 * while preserving solubility.
2380 */
2381
2382 /*
2383 * Find the set of equivalence classes of squares permitted
2384 * by the selected symmetry. We do this by enumerating all
2385 * the grid squares which have no symmetric companion
2386 * sorting lower than themselves.
2387 */
2388 nlocs = 0;
2389 for (y = 0; y < cr; y++)
2390 for (x = 0; x < cr; x++) {
2391 int i = y*cr+x;
2392 int j;
2393
2394 ncoords = symmetries(params, x, y, coords, params->symm);
2395 for (j = 0; j < ncoords; j++)
2396 if (coords[2*j+1]*cr+coords[2*j] < i)
2397 break;
2398 if (j == ncoords) {
2399 locs[nlocs].x = x;
2400 locs[nlocs].y = y;
2401 nlocs++;
2402 }
2403 }
2404
2405 /*
2406 * Now shuffle that list.
2407 */
2408 shuffle(locs, nlocs, sizeof(*locs), rs);
2409
2410 /*
2411 * Now loop over the shuffled list and, for each element,
2412 * see whether removing that element (and its reflections)
2413 * from the grid will still leave the grid soluble.
2414 */
2415 for (i = 0; i < nlocs; i++) {
2416 int ret;
2417
2418 x = locs[i].x;
2419 y = locs[i].y;
2420
2421 memcpy(grid2, grid, area);
2422 ncoords = symmetries(params, x, y, coords, params->symm);
2423 for (j = 0; j < ncoords; j++)
2424 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
2425
2426 ret = solver(cr, blocks, params->xtype, grid2, maxdiff);
2427 if (ret <= maxdiff) {
2428 for (j = 0; j < ncoords; j++)
2429 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
2430 }
2431 }
2432
2433 memcpy(grid2, grid, area);
2434
2435 if (solver(cr, blocks, params->xtype, grid2, maxdiff) == maxdiff)
2436 break; /* found one! */
2437 }
2438
2439 sfree(grid2);
2440 sfree(locs);
2441
2442 /*
2443 * Now we have the grid as it will be presented to the user.
2444 * Encode it in a game desc.
2445 */
2446 {
2447 char *p;
2448 int run, i;
2449
2450 desc = snewn(7 * area, char);
2451 p = desc;
2452 run = 0;
2453 for (i = 0; i <= area; i++) {
2454 int n = (i < area ? grid[i] : -1);
2455
2456 if (!n)
2457 run++;
2458 else {
2459 if (run) {
2460 while (run > 0) {
2461 int c = 'a' - 1 + run;
2462 if (run > 26)
2463 c = 'z';
2464 *p++ = c;
2465 run -= c - ('a' - 1);
2466 }
2467 } else {
2468 /*
2469 * If there's a number in the very top left or
2470 * bottom right, there's no point putting an
2471 * unnecessary _ before or after it.
2472 */
2473 if (p > desc && n > 0)
2474 *p++ = '_';
2475 }
2476 if (n > 0)
2477 p += sprintf(p, "%d", n);
2478 run = 0;
2479 }
2480 }
2481
2482 if (r == 1) {
2483 int currrun = 0;
2484
2485 *p++ = ',';
2486
2487 /*
2488 * Encode the block structure. We do this by encoding
2489 * the pattern of dividing lines: first we iterate
2490 * over the cr*(cr-1) internal vertical grid lines in
2491 * ordinary reading order, then over the cr*(cr-1)
2492 * internal horizontal ones in transposed reading
2493 * order.
2494 *
2495 * We encode the number of non-lines between the
2496 * lines; _ means zero (two adjacent divisions), a
2497 * means 1, ..., y means 25, and z means 25 non-lines
2498 * _and no following line_ (so that za means 26, zb 27
2499 * etc).
2500 */
2501 for (i = 0; i <= 2*cr*(cr-1); i++) {
2502 int p0, p1, edge;
2503
2504 if (i == 2*cr*(cr-1)) {
2505 edge = TRUE; /* terminating virtual edge */
2506 } else {
2507 if (i < cr*(cr-1)) {
2508 y = i/(cr-1);
2509 x = i%(cr-1);
2510 p0 = y*cr+x;
2511 p1 = y*cr+x+1;
2512 } else {
2513 x = i/(cr-1) - cr;
2514 y = i%(cr-1);
2515 p0 = y*cr+x;
2516 p1 = (y+1)*cr+x;
2517 }
2518 edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
2519 }
2520
2521 if (edge) {
2522 while (currrun > 25)
2523 *p++ = 'z', currrun -= 25;
2524 if (currrun)
2525 *p++ = 'a'-1 + currrun;
2526 else
2527 *p++ = '_';
2528 currrun = 0;
2529 } else
2530 currrun++;
2531 }
2532 }
2533
2534 assert(p - desc < 7 * area);
2535 *p++ = '\0';
2536 desc = sresize(desc, p - desc, char);
2537 }
2538
2539 sfree(grid);
2540
2541 return desc;
2542 }
2543
2544 static char *validate_desc(game_params *params, char *desc)
2545 {
2546 int cr = params->c * params->r, area = cr*cr;
2547 int squares = 0;
2548 int *dsf;
2549
2550 while (*desc && *desc != ',') {
2551 int n = *desc++;
2552 if (n >= 'a' && n <= 'z') {
2553 squares += n - 'a' + 1;
2554 } else if (n == '_') {
2555 /* do nothing */;
2556 } else if (n > '0' && n <= '9') {
2557 int val = atoi(desc-1);
2558 if (val < 1 || val > params->c * params->r)
2559 return "Out-of-range number in game description";
2560 squares++;
2561 while (*desc >= '0' && *desc <= '9')
2562 desc++;
2563 } else
2564 return "Invalid character in game description";
2565 }
2566
2567 if (squares < area)
2568 return "Not enough data to fill grid";
2569
2570 if (squares > area)
2571 return "Too much data to fit in grid";
2572
2573 if (params->r == 1) {
2574 int pos;
2575
2576 /*
2577 * Now we expect a suffix giving the jigsaw block
2578 * structure. Parse it and validate that it divides the
2579 * grid into the right number of regions which are the
2580 * right size.
2581 */
2582 if (*desc != ',')
2583 return "Expected jigsaw block structure in game description";
2584 pos = 0;
2585
2586 dsf = snew_dsf(area);
2587 desc++;
2588
2589 while (*desc) {
2590 int c, adv;
2591
2592 if (*desc == '_')
2593 c = 0;
2594 else if (*desc >= 'a' && *desc <= 'z')
2595 c = *desc - 'a' + 1;
2596 else {
2597 sfree(dsf);
2598 return "Invalid character in game description";
2599 }
2600 desc++;
2601
2602 adv = (c != 25); /* 'z' is a special case */
2603
2604 while (c-- > 0) {
2605 int p0, p1;
2606
2607 /*
2608 * Non-edge; merge the two dsf classes on either
2609 * side of it.
2610 */
2611 if (pos >= 2*cr*(cr-1)) {
2612 sfree(dsf);
2613 return "Too much data in block structure specification";
2614 } else if (pos < cr*(cr-1)) {
2615 int y = pos/(cr-1);
2616 int x = pos%(cr-1);
2617 p0 = y*cr+x;
2618 p1 = y*cr+x+1;
2619 } else {
2620 int x = pos/(cr-1) - cr;
2621 int y = pos%(cr-1);
2622 p0 = y*cr+x;
2623 p1 = (y+1)*cr+x;
2624 }
2625 dsf_merge(dsf, p0, p1);
2626
2627 pos++;
2628 }
2629 if (adv)
2630 pos++;
2631 }
2632
2633 /*
2634 * When desc is exhausted, we expect to have gone exactly
2635 * one space _past_ the end of the grid, due to the dummy
2636 * edge at the end.
2637 */
2638 if (pos != 2*cr*(cr-1)+1) {
2639 sfree(dsf);
2640 return "Not enough data in block structure specification";
2641 }
2642
2643 /*
2644 * Now we've got our dsf. Verify that it matches
2645 * expectations.
2646 */
2647 {
2648 int *canons, *counts;
2649 int i, j, c, ncanons = 0;
2650
2651 canons = snewn(cr, int);
2652 counts = snewn(cr, int);
2653
2654 for (i = 0; i < area; i++) {
2655 j = dsf_canonify(dsf, i);
2656
2657 for (c = 0; c < ncanons; c++)
2658 if (canons[c] == j) {
2659 counts[c]++;
2660 if (counts[c] > cr) {
2661 sfree(dsf);
2662 sfree(canons);
2663 sfree(counts);
2664 return "A jigsaw block is too big";
2665 }
2666 break;
2667 }
2668
2669 if (c == ncanons) {
2670 if (ncanons >= cr) {
2671 sfree(dsf);
2672 sfree(canons);
2673 sfree(counts);
2674 return "Too many distinct jigsaw blocks";
2675 }
2676 canons[ncanons] = j;
2677 counts[ncanons] = 1;
2678 ncanons++;
2679 }
2680 }
2681
2682 /*
2683 * If we've managed to get through that loop without
2684 * tripping either of the error conditions, then we
2685 * must have partitioned the entire grid into at most
2686 * cr blocks of at most cr squares each; therefore we
2687 * must have _exactly_ cr blocks of _exactly_ cr
2688 * squares each. I'll verify that by assertion just in
2689 * case something has gone horribly wrong, but it
2690 * shouldn't have been able to happen by duff input,
2691 * only by a bug in the above code.
2692 */
2693 assert(ncanons == cr);
2694 for (c = 0; c < ncanons; c++)
2695 assert(counts[c] == cr);
2696
2697 sfree(canons);
2698 sfree(counts);
2699 }
2700
2701 sfree(dsf);
2702 } else {
2703 if (*desc)
2704 return "Unexpected jigsaw block structure in game description";
2705 }
2706
2707 return NULL;
2708 }
2709
2710 static game_state *new_game(midend *me, game_params *params, char *desc)
2711 {
2712 game_state *state = snew(game_state);
2713 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2714 int i;
2715
2716 state->cr = cr;
2717 state->xtype = params->xtype;
2718
2719 state->grid = snewn(area, digit);
2720 state->pencil = snewn(area * cr, unsigned char);
2721 memset(state->pencil, 0, area * cr);
2722 state->immutable = snewn(area, unsigned char);
2723 memset(state->immutable, FALSE, area);
2724
2725 state->blocks = snew(struct block_structure);
2726 state->blocks->c = c; state->blocks->r = r;
2727 state->blocks->refcount = 1;
2728 state->blocks->whichblock = snewn(area*2, int);
2729 state->blocks->blocks = snewn(cr, int *);
2730 for (i = 0; i < cr; i++)
2731 state->blocks->blocks[i] = state->blocks->whichblock + area + i*cr;
2732 #ifdef STANDALONE_SOLVER
2733 state->blocks->blocknames = (char **)smalloc(cr*(sizeof(char *)+80));
2734 #endif
2735
2736 state->completed = state->cheated = FALSE;
2737
2738 i = 0;
2739 while (*desc && *desc != ',') {
2740 int n = *desc++;
2741 if (n >= 'a' && n <= 'z') {
2742 int run = n - 'a' + 1;
2743 assert(i + run <= area);
2744 while (run-- > 0)
2745 state->grid[i++] = 0;
2746 } else if (n == '_') {
2747 /* do nothing */;
2748 } else if (n > '0' && n <= '9') {
2749 assert(i < area);
2750 state->immutable[i] = TRUE;
2751 state->grid[i++] = atoi(desc-1);
2752 while (*desc >= '0' && *desc <= '9')
2753 desc++;
2754 } else {
2755 assert(!"We can't get here");
2756 }
2757 }
2758 assert(i == area);
2759
2760 if (r == 1) {
2761 int pos = 0;
2762 int *dsf;
2763 int nb;
2764
2765 assert(*desc == ',');
2766
2767 dsf = snew_dsf(area);
2768 desc++;
2769
2770 while (*desc) {
2771 int c, adv;
2772
2773 if (*desc == '_')
2774 c = 0;
2775 else if (*desc >= 'a' && *desc <= 'z')
2776 c = *desc - 'a' + 1;
2777 else
2778 assert(!"Shouldn't get here");
2779 desc++;
2780
2781 adv = (c != 25); /* 'z' is a special case */
2782
2783 while (c-- > 0) {
2784 int p0, p1;
2785
2786 /*
2787 * Non-edge; merge the two dsf classes on either
2788 * side of it.
2789 */
2790 assert(pos < 2*cr*(cr-1));
2791 if (pos < cr*(cr-1)) {
2792 int y = pos/(cr-1);
2793 int x = pos%(cr-1);
2794 p0 = y*cr+x;
2795 p1 = y*cr+x+1;
2796 } else {
2797 int x = pos/(cr-1) - cr;
2798 int y = pos%(cr-1);
2799 p0 = y*cr+x;
2800 p1 = (y+1)*cr+x;
2801 }
2802 dsf_merge(dsf, p0, p1);
2803
2804 pos++;
2805 }
2806 if (adv)
2807 pos++;
2808 }
2809
2810 /*
2811 * When desc is exhausted, we expect to have gone exactly
2812 * one space _past_ the end of the grid, due to the dummy
2813 * edge at the end.
2814 */
2815 assert(pos == 2*cr*(cr-1)+1);
2816
2817 /*
2818 * Now we've got our dsf. Translate it into a block
2819 * structure.
2820 */
2821 nb = 0;
2822 for (i = 0; i < area; i++)
2823 state->blocks->whichblock[i] = -1;
2824 for (i = 0; i < area; i++) {
2825 int j = dsf_canonify(dsf, i);
2826 if (state->blocks->whichblock[j] < 0)
2827 state->blocks->whichblock[j] = nb++;
2828 state->blocks->whichblock[i] = state->blocks->whichblock[j];
2829 }
2830 assert(nb == cr);
2831
2832 sfree(dsf);
2833 } else {
2834 int x, y;
2835
2836 assert(!*desc);
2837
2838 for (y = 0; y < cr; y++)
2839 for (x = 0; x < cr; x++)
2840 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
2841 }
2842
2843 /*
2844 * Having sorted out whichblock[], set up the block index arrays.
2845 */
2846 for (i = 0; i < cr; i++)
2847 state->blocks->blocks[i][cr-1] = 0;
2848 for (i = 0; i < area; i++) {
2849 int b = state->blocks->whichblock[i];
2850 int j = state->blocks->blocks[b][cr-1]++;
2851 assert(j < cr);
2852 state->blocks->blocks[b][j] = i;
2853 }
2854
2855 #ifdef STANDALONE_SOLVER
2856 /*
2857 * Set up the block names for solver diagnostic output.
2858 */
2859 {
2860 char *p = (char *)(state->blocks->blocknames + cr);
2861
2862 if (r == 1) {
2863 for (i = 0; i < cr; i++)
2864 state->blocks->blocknames[i] = NULL;
2865
2866 for (i = 0; i < area; i++) {
2867 int j = state->blocks->whichblock[i];
2868 if (!state->blocks->blocknames[j]) {
2869 state->blocks->blocknames[j] = p;
2870 p += 1 + sprintf(p, "starting at (%d,%d)",
2871 1 + i%cr, 1 + i/cr);
2872 }
2873 }
2874 } else {
2875 int bx, by;
2876 for (by = 0; by < r; by++)
2877 for (bx = 0; bx < c; bx++) {
2878 state->blocks->blocknames[by*c+bx] = p;
2879 p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
2880 }
2881 }
2882 assert(p - (char *)state->blocks->blocknames < cr*(sizeof(char *)+80));
2883 for (i = 0; i < cr; i++)
2884 assert(state->blocks->blocknames[i]);
2885 }
2886 #endif
2887
2888 return state;
2889 }
2890
2891 static game_state *dup_game(game_state *state)
2892 {
2893 game_state *ret = snew(game_state);
2894 int cr = state->cr, area = cr * cr;
2895
2896 ret->cr = state->cr;
2897 ret->xtype = state->xtype;
2898
2899 ret->blocks = state->blocks;
2900 ret->blocks->refcount++;
2901
2902 ret->grid = snewn(area, digit);
2903 memcpy(ret->grid, state->grid, area);
2904
2905 ret->pencil = snewn(area * cr, unsigned char);
2906 memcpy(ret->pencil, state->pencil, area * cr);
2907
2908 ret->immutable = snewn(area, unsigned char);
2909 memcpy(ret->immutable, state->immutable, area);
2910
2911 ret->completed = state->completed;
2912 ret->cheated = state->cheated;
2913
2914 return ret;
2915 }
2916
2917 static void free_game(game_state *state)
2918 {
2919 if (--state->blocks->refcount == 0) {
2920 sfree(state->blocks->whichblock);
2921 sfree(state->blocks->blocks);
2922 #ifdef STANDALONE_SOLVER
2923 sfree(state->blocks->blocknames);
2924 #endif
2925 sfree(state->blocks);
2926 }
2927 sfree(state->immutable);
2928 sfree(state->pencil);
2929 sfree(state->grid);
2930 sfree(state);
2931 }
2932
2933 static char *solve_game(game_state *state, game_state *currstate,
2934 char *ai, char **error)
2935 {
2936 int cr = state->cr;
2937 char *ret;
2938 digit *grid;
2939 int solve_ret;
2940
2941 /*
2942 * If we already have the solution in ai, save ourselves some
2943 * time.
2944 */
2945 if (ai)
2946 return dupstr(ai);
2947
2948 grid = snewn(cr*cr, digit);
2949 memcpy(grid, state->grid, cr*cr);
2950 solve_ret = solver(cr, state->blocks, state->xtype, grid, DIFF_RECURSIVE);
2951
2952 *error = NULL;
2953
2954 if (solve_ret == DIFF_IMPOSSIBLE)
2955 *error = "No solution exists for this puzzle";
2956 else if (solve_ret == DIFF_AMBIGUOUS)
2957 *error = "Multiple solutions exist for this puzzle";
2958
2959 if (*error) {
2960 sfree(grid);
2961 return NULL;
2962 }
2963
2964 ret = encode_solve_move(cr, grid);
2965
2966 sfree(grid);
2967
2968 return ret;
2969 }
2970
2971 static char *grid_text_format(int cr, struct block_structure *blocks,
2972 int xtype, digit *grid)
2973 {
2974 int vmod, hmod;
2975 int x, y;
2976 int totallen, linelen, nlines;
2977 char *ret, *p, ch;
2978
2979 /*
2980 * For non-jigsaw Sudoku, we format in the way we always have,
2981 * by having the digits unevenly spaced so that the dividing
2982 * lines can fit in:
2983 *
2984 * . . | . .
2985 * . . | . .
2986 * ----+----
2987 * . . | . .
2988 * . . | . .
2989 *
2990 * For jigsaw puzzles, however, we must leave space between
2991 * _all_ pairs of digits for an optional dividing line, so we
2992 * have to move to the rather ugly
2993 *
2994 * . . . .
2995 * ------+------
2996 * . . | . .
2997 * +---+
2998 * . . | . | .
2999 * ------+ |
3000 * . . . | .
3001 *
3002 * We deal with both cases using the same formatting code; we
3003 * simply invent a vmod value such that there's a vertical
3004 * dividing line before column i iff i is divisible by vmod
3005 * (so it's r in the first case and 1 in the second), and hmod
3006 * likewise for horizontal dividing lines.
3007 */
3008
3009 if (blocks->r != 1) {
3010 vmod = blocks->r;
3011 hmod = blocks->c;
3012 } else {
3013 vmod = hmod = 1;
3014 }
3015
3016 /*
3017 * Line length: we have cr digits, each with a space after it,
3018 * and (cr-1)/vmod dividing lines, each with a space after it.
3019 * The final space is replaced by a newline, but that doesn't
3020 * affect the length.
3021 */
3022 linelen = 2*(cr + (cr-1)/vmod);
3023
3024 /*
3025 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3026 * dividing rows.
3027 */
3028 nlines = cr + (cr-1)/hmod;
3029
3030 /*
3031 * Allocate the space.
3032 */
3033 totallen = linelen * nlines;
3034 ret = snewn(totallen+1, char); /* leave room for terminating NUL */
3035
3036 /*
3037 * Write the text.
3038 */
3039 p = ret;
3040 for (y = 0; y < cr; y++) {
3041 /*
3042 * Row of digits.
3043 */
3044 for (x = 0; x < cr; x++) {
3045 /*
3046 * Digit.
3047 */
3048 digit d = grid[y*cr+x];
3049
3050 if (d == 0) {
3051 /*
3052 * Empty space: we usually write a dot, but we'll
3053 * highlight spaces on the X-diagonals (in X mode)
3054 * by using underscores instead.
3055 */
3056 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
3057 ch = '_';
3058 else
3059 ch = '.';
3060 } else if (d <= 9) {
3061 ch = '0' + d;
3062 } else {
3063 ch = 'a' + d-10;
3064 }
3065
3066 *p++ = ch;
3067 if (x == cr-1) {
3068 *p++ = '\n';
3069 continue;
3070 }
3071 *p++ = ' ';
3072
3073 if ((x+1) % vmod)
3074 continue;
3075
3076 /*
3077 * Optional dividing line.
3078 */
3079 if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
3080 ch = '|';
3081 else
3082 ch = ' ';
3083 *p++ = ch;
3084 *p++ = ' ';
3085 }
3086 if (y == cr-1 || (y+1) % hmod)
3087 continue;
3088
3089 /*
3090 * Dividing row.
3091 */
3092 for (x = 0; x < cr; x++) {
3093 int dwid;
3094 int tl, tr, bl, br;
3095
3096 /*
3097 * Division between two squares. This varies
3098 * complicatedly in length.
3099 */
3100 dwid = 2; /* digit and its following space */
3101 if (x == cr-1)
3102 dwid--; /* no following space at end of line */
3103 if (x > 0 && x % vmod == 0)
3104 dwid++; /* preceding space after a divider */
3105
3106 if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
3107 ch = '-';
3108 else
3109 ch = ' ';
3110
3111 while (dwid-- > 0)
3112 *p++ = ch;
3113
3114 if (x == cr-1) {
3115 *p++ = '\n';
3116 break;
3117 }
3118
3119 if ((x+1) % vmod)
3120 continue;
3121
3122 /*
3123 * Corner square. This is:
3124 * - a space if all four surrounding squares are in
3125 * the same block
3126 * - a vertical line if the two left ones are in one
3127 * block and the two right in another
3128 * - a horizontal line if the two top ones are in one
3129 * block and the two bottom in another
3130 * - a plus sign in all other cases. (If we had a
3131 * richer character set available we could break
3132 * this case up further by doing fun things with
3133 * line-drawing T-pieces.)
3134 */
3135 tl = blocks->whichblock[y*cr+x];
3136 tr = blocks->whichblock[y*cr+x+1];
3137 bl = blocks->whichblock[(y+1)*cr+x];
3138 br = blocks->whichblock[(y+1)*cr+x+1];
3139
3140 if (tl == tr && tr == bl && bl == br)
3141 ch = ' ';
3142 else if (tl == bl && tr == br)
3143 ch = '|';
3144 else if (tl == tr && bl == br)
3145 ch = '-';
3146 else
3147 ch = '+';
3148
3149 *p++ = ch;
3150 }
3151 }
3152
3153 assert(p - ret == totallen);
3154 *p = '\0';
3155 return ret;
3156 }
3157
3158 static char *game_text_format(game_state *state)
3159 {
3160 return grid_text_format(state->cr, state->blocks, state->xtype,
3161 state->grid);
3162 }
3163
3164 struct game_ui {
3165 /*
3166 * These are the coordinates of the currently highlighted
3167 * square on the grid, or -1,-1 if there isn't one. When there
3168 * is, pressing a valid number or letter key or Space will
3169 * enter that number or letter in the grid.
3170 */
3171 int hx, hy;
3172 /*
3173 * This indicates whether the current highlight is a
3174 * pencil-mark one or a real one.
3175 */
3176 int hpencil;
3177 };
3178
3179 static game_ui *new_ui(game_state *state)
3180 {
3181 game_ui *ui = snew(game_ui);
3182
3183 ui->hx = ui->hy = -1;
3184 ui->hpencil = 0;
3185
3186 return ui;
3187 }
3188
3189 static void free_ui(game_ui *ui)
3190 {
3191 sfree(ui);
3192 }
3193
3194 static char *encode_ui(game_ui *ui)
3195 {
3196 return NULL;
3197 }
3198
3199 static void decode_ui(game_ui *ui, char *encoding)
3200 {
3201 }
3202
3203 static void game_changed_state(game_ui *ui, game_state *oldstate,
3204 game_state *newstate)
3205 {
3206 int cr = newstate->cr;
3207 /*
3208 * We prevent pencil-mode highlighting of a filled square. So
3209 * if the user has just filled in a square which we had a
3210 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3211 * then we cancel the highlight.
3212 */
3213 if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
3214 newstate->grid[ui->hy * cr + ui->hx] != 0) {
3215 ui->hx = ui->hy = -1;
3216 }
3217 }
3218
3219 struct game_drawstate {
3220 int started;
3221 int cr, xtype;
3222 int tilesize;
3223 digit *grid;
3224 unsigned char *pencil;
3225 unsigned char *hl;
3226 /* This is scratch space used within a single call to game_redraw. */
3227 int *entered_items;
3228 };
3229
3230 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3231 int x, int y, int button)
3232 {
3233 int cr = state->cr;
3234 int tx, ty;
3235 char buf[80];
3236
3237 button &= ~MOD_MASK;
3238
3239 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3240 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
3241
3242 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
3243 if (button == LEFT_BUTTON) {
3244 if (state->immutable[ty*cr+tx]) {
3245 ui->hx = ui->hy = -1;
3246 } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
3247 ui->hx = ui->hy = -1;
3248 } else {
3249 ui->hx = tx;
3250 ui->hy = ty;
3251 ui->hpencil = 0;
3252 }
3253 return ""; /* UI activity occurred */
3254 }
3255 if (button == RIGHT_BUTTON) {
3256 /*
3257 * Pencil-mode highlighting for non filled squares.
3258 */
3259 if (state->grid[ty*cr+tx] == 0) {
3260 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
3261 ui->hx = ui->hy = -1;
3262 } else {
3263 ui->hpencil = 1;
3264 ui->hx = tx;
3265 ui->hy = ty;
3266 }
3267 } else {
3268 ui->hx = ui->hy = -1;
3269 }
3270 return ""; /* UI activity occurred */
3271 }
3272 }
3273
3274 if (ui->hx != -1 && ui->hy != -1 &&
3275 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
3276 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
3277 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
3278 button == ' ' || button == '\010' || button == '\177')) {
3279 int n = button - '0';
3280 if (button >= 'A' && button <= 'Z')
3281 n = button - 'A' + 10;
3282 if (button >= 'a' && button <= 'z')
3283 n = button - 'a' + 10;
3284 if (button == ' ' || button == '\010' || button == '\177')
3285 n = 0;
3286
3287 /*
3288 * Can't overwrite this square. In principle this shouldn't
3289 * happen anyway because we should never have even been
3290 * able to highlight the square, but it never hurts to be
3291 * careful.
3292 */
3293 if (state->immutable[ui->hy*cr+ui->hx])
3294 return NULL;
3295
3296 /*
3297 * Can't make pencil marks in a filled square. In principle
3298 * this shouldn't happen anyway because we should never
3299 * have even been able to pencil-highlight the square, but
3300 * it never hurts to be careful.
3301 */
3302 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
3303 return NULL;
3304
3305 sprintf(buf, "%c%d,%d,%d",
3306 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
3307
3308 ui->hx = ui->hy = -1;
3309
3310 return dupstr(buf);
3311 }
3312
3313 return NULL;
3314 }
3315
3316 static game_state *execute_move(game_state *from, char *move)
3317 {
3318 int cr = from->cr;
3319 game_state *ret;
3320 int x, y, n;
3321
3322 if (move[0] == 'S') {
3323 char *p;
3324
3325 ret = dup_game(from);
3326 ret->completed = ret->cheated = TRUE;
3327
3328 p = move+1;
3329 for (n = 0; n < cr*cr; n++) {
3330 ret->grid[n] = atoi(p);
3331
3332 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
3333 free_game(ret);
3334 return NULL;
3335 }
3336
3337 while (*p && isdigit((unsigned char)*p)) p++;
3338 if (*p == ',') p++;
3339 }
3340
3341 return ret;
3342 } else if ((move[0] == 'P' || move[0] == 'R') &&
3343 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
3344 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
3345
3346 ret = dup_game(from);
3347 if (move[0] == 'P' && n > 0) {
3348 int index = (y*cr+x) * cr + (n-1);
3349 ret->pencil[index] = !ret->pencil[index];
3350 } else {
3351 ret->grid[y*cr+x] = n;
3352 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
3353
3354 /*
3355 * We've made a real change to the grid. Check to see
3356 * if the game has been completed.
3357 */
3358 if (!ret->completed && check_valid(cr, ret->blocks, ret->xtype,
3359 ret->grid)) {
3360 ret->completed = TRUE;
3361 }
3362 }
3363 return ret;
3364 } else
3365 return NULL; /* couldn't parse move string */
3366 }
3367
3368 /* ----------------------------------------------------------------------
3369 * Drawing routines.
3370 */
3371
3372 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3373 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3374
3375 static void game_compute_size(game_params *params, int tilesize,
3376 int *x, int *y)
3377 {
3378 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3379 struct { int tilesize; } ads, *ds = &ads;
3380 ads.tilesize = tilesize;
3381
3382 *x = SIZE(params->c * params->r);
3383 *y = SIZE(params->c * params->r);
3384 }
3385
3386 static void game_set_size(drawing *dr, game_drawstate *ds,
3387 game_params *params, int tilesize)
3388 {
3389 ds->tilesize = tilesize;
3390 }
3391
3392 static float *game_colours(frontend *fe, int *ncolours)
3393 {
3394 float *ret = snewn(3 * NCOLOURS, float);
3395
3396 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
3397
3398 ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
3399 ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
3400 ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
3401
3402 ret[COL_GRID * 3 + 0] = 0.0F;
3403 ret[COL_GRID * 3 + 1] = 0.0F;
3404 ret[COL_GRID * 3 + 2] = 0.0F;
3405
3406 ret[COL_CLUE * 3 + 0] = 0.0F;
3407 ret[COL_CLUE * 3 + 1] = 0.0F;
3408 ret[COL_CLUE * 3 + 2] = 0.0F;
3409
3410 ret[COL_USER * 3 + 0] = 0.0F;
3411 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
3412 ret[COL_USER * 3 + 2] = 0.0F;
3413
3414 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
3415 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
3416 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
3417
3418 ret[COL_ERROR * 3 + 0] = 1.0F;
3419 ret[COL_ERROR * 3 + 1] = 0.0F;
3420 ret[COL_ERROR * 3 + 2] = 0.0F;
3421
3422 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
3423 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
3424 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
3425
3426 *ncolours = NCOLOURS;
3427 return ret;
3428 }
3429
3430 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
3431 {
3432 struct game_drawstate *ds = snew(struct game_drawstate);
3433 int cr = state->cr;
3434
3435 ds->started = FALSE;
3436 ds->cr = cr;
3437 ds->xtype = state->xtype;
3438 ds->grid = snewn(cr*cr, digit);
3439 memset(ds->grid, cr+2, cr*cr);
3440 ds->pencil = snewn(cr*cr*cr, digit);
3441 memset(ds->pencil, 0, cr*cr*cr);
3442 ds->hl = snewn(cr*cr, unsigned char);
3443 memset(ds->hl, 0, cr*cr);
3444 ds->entered_items = snewn(cr*cr, int);
3445 ds->tilesize = 0; /* not decided yet */
3446 return ds;
3447 }
3448
3449 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3450 {
3451 sfree(ds->hl);
3452 sfree(ds->pencil);
3453 sfree(ds->grid);
3454 sfree(ds->entered_items);
3455 sfree(ds);
3456 }
3457
3458 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
3459 int x, int y, int hl)
3460 {
3461 int cr = state->cr;
3462 int tx, ty;
3463 int cx, cy, cw, ch;
3464 char str[2];
3465
3466 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
3467 ds->hl[y*cr+x] == hl &&
3468 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
3469 return; /* no change required */
3470
3471 tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
3472 ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
3473
3474 cx = tx;
3475 cy = ty;
3476 cw = TILE_SIZE-1-2*GRIDEXTRA;
3477 ch = TILE_SIZE-1-2*GRIDEXTRA;
3478
3479 if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
3480 cx -= GRIDEXTRA, cw += GRIDEXTRA;
3481 if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
3482 cw += GRIDEXTRA;
3483 if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
3484 cy -= GRIDEXTRA, ch += GRIDEXTRA;
3485 if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
3486 ch += GRIDEXTRA;
3487
3488 clip(dr, cx, cy, cw, ch);
3489
3490 /* background needs erasing */
3491 draw_rect(dr, cx, cy, cw, ch,
3492 ((hl & 15) == 1 ? COL_HIGHLIGHT :
3493 (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
3494 COL_BACKGROUND));
3495
3496 /*
3497 * Draw the corners of thick lines in corner-adjacent squares,
3498 * which jut into this square by one pixel.
3499 */
3500 if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
3501 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3502 if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
3503 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3504 if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
3505 draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3506 if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
3507 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
3508
3509 /* pencil-mode highlight */
3510 if ((hl & 15) == 2) {
3511 int coords[6];
3512 coords[0] = cx;
3513 coords[1] = cy;
3514 coords[2] = cx+cw/2;
3515 coords[3] = cy;
3516 coords[4] = cx;
3517 coords[5] = cy+ch/2;
3518 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
3519 }
3520
3521 /* new number needs drawing? */
3522 if (state->grid[y*cr+x]) {
3523 str[1] = '\0';
3524 str[0] = state->grid[y*cr+x] + '0';
3525 if (str[0] > '9')
3526 str[0] += 'a' - ('9'+1);
3527 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
3528 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
3529 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
3530 } else {
3531 int i, j, npencil;
3532 int pw, ph, pmax, fontsize;
3533
3534 /* count the pencil marks required */
3535 for (i = npencil = 0; i < cr; i++)
3536 if (state->pencil[(y*cr+x)*cr+i])
3537 npencil++;
3538
3539 /*
3540 * It's not sensible to arrange pencil marks in the same
3541 * layout as the squares within a block, because this leads
3542 * to the font being too small. Instead, we arrange pencil
3543 * marks in the nearest thing we can to a square layout,
3544 * and we adjust the square layout depending on the number
3545 * of pencil marks in the square.
3546 */
3547 for (pw = 1; pw * pw < npencil; pw++);
3548 if (pw < 3) pw = 3; /* otherwise it just looks _silly_ */
3549 ph = (npencil + pw - 1) / pw;
3550 if (ph < 2) ph = 2; /* likewise */
3551 pmax = max(pw, ph);
3552 fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
3553
3554 for (i = j = 0; i < cr; i++)
3555 if (state->pencil[(y*cr+x)*cr+i]) {
3556 int dx = j % pw, dy = j / pw;
3557
3558 str[1] = '\0';
3559 str[0] = i + '1';
3560 if (str[0] > '9')
3561 str[0] += 'a' - ('9'+1);
3562 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
3563 ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
3564 FONT_VARIABLE, fontsize,
3565 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
3566 j++;
3567 }
3568 }
3569
3570 unclip(dr);
3571
3572 draw_update(dr, cx, cy, cw, ch);
3573
3574 ds->grid[y*cr+x] = state->grid[y*cr+x];
3575 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
3576 ds->hl[y*cr+x] = hl;
3577 }
3578
3579 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3580 game_state *state, int dir, game_ui *ui,
3581 float animtime, float flashtime)
3582 {
3583 int cr = state->cr;
3584 int x, y;
3585
3586 if (!ds->started) {
3587 /*
3588 * The initial contents of the window are not guaranteed
3589 * and can vary with front ends. To be on the safe side,
3590 * all games should start by drawing a big
3591 * background-colour rectangle covering the whole window.
3592 */
3593 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
3594
3595 /*
3596 * Draw the grid. We draw it as a big thick rectangle of
3597 * COL_GRID initially; individual calls to draw_number()
3598 * will poke the right-shaped holes in it.
3599 */
3600 draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
3601 cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
3602 COL_GRID);
3603 }
3604
3605 /*
3606 * This array is used to keep track of rows, columns and boxes
3607 * which contain a number more than once.
3608 */
3609 for (x = 0; x < cr * cr; x++)
3610 ds->entered_items[x] = 0;
3611 for (x = 0; x < cr; x++)
3612 for (y = 0; y < cr; y++) {
3613 digit d = state->grid[y*cr+x];
3614 if (d) {
3615 int box = state->blocks->whichblock[y*cr+x];
3616 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
3617 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
3618 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
3619 if (ds->xtype) {
3620 if (ondiag0(y*cr+x))
3621 ds->entered_items[d-1] |= ((ds->entered_items[d-1] & 64) << 1) | 64;
3622 if (ondiag1(y*cr+x))
3623 ds->entered_items[cr+d-1] |= ((ds->entered_items[cr+d-1] & 64) << 1) | 64;
3624 }
3625 }
3626 }
3627
3628 /*
3629 * Draw any numbers which need redrawing.
3630 */
3631 for (x = 0; x < cr; x++) {
3632 for (y = 0; y < cr; y++) {
3633 int highlight = 0;
3634 digit d = state->grid[y*cr+x];
3635
3636 if (flashtime > 0 &&
3637 (flashtime <= FLASH_TIME/3 ||
3638 flashtime >= FLASH_TIME*2/3))
3639 highlight = 1;
3640
3641 /* Highlight active input areas. */
3642 if (x == ui->hx && y == ui->hy)
3643 highlight = ui->hpencil ? 2 : 1;
3644
3645 /* Mark obvious errors (ie, numbers which occur more than once
3646 * in a single row, column, or box). */
3647 if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
3648 (ds->entered_items[y*cr+d-1] & 8) ||
3649 (ds->entered_items[state->blocks->whichblock[y*cr+x]*cr+d-1] & 32) ||
3650 (ds->xtype && ((ondiag0(y*cr+x) && (ds->entered_items[d-1] & 128)) ||
3651 (ondiag1(y*cr+x) && (ds->entered_items[cr+d-1] & 128))))))
3652 highlight |= 16;
3653
3654 draw_number(dr, ds, state, x, y, highlight);
3655 }
3656 }
3657
3658 /*
3659 * Update the _entire_ grid if necessary.
3660 */
3661 if (!ds->started) {
3662 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
3663 ds->started = TRUE;
3664 }
3665 }
3666
3667 static float game_anim_length(game_state *oldstate, game_state *newstate,
3668 int dir, game_ui *ui)
3669 {
3670 return 0.0F;
3671 }
3672
3673 static float game_flash_length(game_state *oldstate, game_state *newstate,
3674 int dir, game_ui *ui)
3675 {
3676 if (!oldstate->completed && newstate->completed &&
3677 !oldstate->cheated && !newstate->cheated)
3678 return FLASH_TIME;
3679 return 0.0F;
3680 }
3681
3682 static int game_timing_state(game_state *state, game_ui *ui)
3683 {
3684 return TRUE;
3685 }
3686
3687 static void game_print_size(game_params *params, float *x, float *y)
3688 {
3689 int pw, ph;
3690
3691 /*
3692 * I'll use 9mm squares by default. They should be quite big
3693 * for this game, because players will want to jot down no end
3694 * of pencil marks in the squares.
3695 */
3696 game_compute_size(params, 900, &pw, &ph);
3697 *x = pw / 100.0;
3698 *y = ph / 100.0;
3699 }
3700
3701 static void game_print(drawing *dr, game_state *state, int tilesize)
3702 {
3703 int cr = state->cr;
3704 int ink = print_mono_colour(dr, 0);
3705 int x, y;
3706
3707 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3708 game_drawstate ads, *ds = &ads;
3709 game_set_size(dr, ds, NULL, tilesize);
3710
3711 /*
3712 * Border.
3713 */
3714 print_line_width(dr, 3 * TILE_SIZE / 40);
3715 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
3716
3717 /*
3718 * Highlight X-diagonal squares.
3719 */
3720 if (state->xtype) {
3721 int i;
3722 int xhighlight = print_grey_colour(dr, HATCH_SLASH, 0.90F);
3723
3724 for (i = 0; i < cr; i++)
3725 draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
3726 TILE_SIZE, TILE_SIZE, xhighlight);
3727 for (i = 0; i < cr; i++)
3728 if (i*2 != cr-1) /* avoid redoing centre square, just for fun */
3729 draw_rect(dr, BORDER + i*TILE_SIZE,
3730 BORDER + (cr-1-i)*TILE_SIZE,
3731 TILE_SIZE, TILE_SIZE, xhighlight);
3732 }
3733
3734 /*
3735 * Main grid.
3736 */
3737 for (x = 1; x < cr; x++) {
3738 print_line_width(dr, TILE_SIZE / 40);
3739 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
3740 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
3741 }
3742 for (y = 1; y < cr; y++) {
3743 print_line_width(dr, TILE_SIZE / 40);
3744 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
3745 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
3746 }
3747
3748 /*
3749 * Thick lines between cells. In order to do this using the
3750 * line-drawing rather than rectangle-drawing API (so as to
3751 * get line thicknesses to scale correctly) and yet have
3752 * correctly mitred joins between lines, we must do this by
3753 * tracing the boundary of each sub-block and drawing it in
3754 * one go as a single polygon.
3755 */
3756 {
3757 int *coords;
3758 int bi, i, n;
3759 int x, y, dx, dy, sx, sy, sdx, sdy;
3760
3761 print_line_width(dr, 3 * TILE_SIZE / 40);
3762
3763 /*
3764 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3765 * with k unconnected squares, with total perimeter 4k.
3766 * Now repeatedly join two disconnected components
3767 * together into a larger one; every time you do so you
3768 * remove at least two unit edges, and you require k-1 of
3769 * these operations to create a single connected piece, so
3770 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3771 * afterwards.)
3772 */
3773 coords = snewn(4*cr+4, int); /* 2k+2 points, 2 coords per point */
3774
3775 /*
3776 * Iterate over all the blocks.
3777 */
3778 for (bi = 0; bi < cr; bi++) {
3779
3780 /*
3781 * For each block, find a starting square within it
3782 * which has a boundary at the left.
3783 */
3784 for (i = 0; i < cr; i++) {
3785 int j = state->blocks->blocks[bi][i];
3786 if (j % cr == 0 || state->blocks->whichblock[j-1] != bi)
3787 break;
3788 }
3789 assert(i < cr); /* every block must have _some_ leftmost square */
3790 x = state->blocks->blocks[bi][i] % cr;
3791 y = state->blocks->blocks[bi][i] / cr;
3792 dx = -1;
3793 dy = 0;
3794
3795 /*
3796 * Now begin tracing round the perimeter. At all
3797 * times, (x,y) describes some square within the
3798 * block, and (x+dx,y+dy) is some adjacent square
3799 * outside it; so the edge between those two squares
3800 * is always an edge of the block.
3801 */
3802 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
3803 n = 0;
3804 do {
3805 int cx, cy, tx, ty, nin;
3806
3807 /*
3808 * To begin with, record the point at one end of
3809 * the edge. To do this, we translate (x,y) down
3810 * and right by half a unit (so they're describing
3811 * a point in the _centre_ of the square) and then
3812 * translate back again in a manner rotated by dy
3813 * and dx.
3814 */
3815 assert(n < 2*cr+2);
3816 cx = ((2*x+1) + dy + dx) / 2;
3817 cy = ((2*y+1) - dx + dy) / 2;
3818 coords[2*n+0] = BORDER + cx * TILE_SIZE;
3819 coords[2*n+1] = BORDER + cy * TILE_SIZE;
3820 n++;
3821
3822 /*
3823 * Now advance to the next edge, by looking at the
3824 * two squares beyond it. If they're both outside
3825 * the block, we turn right (by leaving x,y the
3826 * same and rotating dx,dy clockwise); if they're
3827 * both inside, we turn left (by rotating dx,dy
3828 * anticlockwise and contriving to leave x+dx,y+dy
3829 * unchanged); if one of each, we go straight on
3830 * (and may enforce by assertion that they're one
3831 * of each the _right_ way round).
3832 */
3833 nin = 0;
3834 tx = x - dy + dx;
3835 ty = y + dx + dy;
3836 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3837 state->blocks->whichblock[ty*cr+tx] == bi);
3838 tx = x - dy;
3839 ty = y + dx;
3840 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
3841 state->blocks->whichblock[ty*cr+tx] == bi);
3842 if (nin == 0) {
3843 /*
3844 * Turn right.
3845 */
3846 int tmp;
3847 tmp = dx;
3848 dx = -dy;
3849 dy = tmp;
3850 } else if (nin == 2) {
3851 /*
3852 * Turn left.
3853 */
3854 int tmp;
3855
3856 x += dx;
3857 y += dy;
3858
3859 tmp = dx;
3860 dx = dy;
3861 dy = -tmp;
3862
3863 x -= dx;
3864 y -= dy;
3865 } else {
3866 /*
3867 * Go straight on.
3868 */
3869 x -= dy;
3870 y += dx;
3871 }
3872
3873 /*
3874 * Now enforce by assertion that we ended up
3875 * somewhere sensible.
3876 */
3877 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
3878 state->blocks->whichblock[y*cr+x] == bi);
3879 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
3880 state->blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
3881
3882 } while (x != sx || y != sy || dx != sdx || dy != sdy);
3883
3884 /*
3885 * That's our polygon; now draw it.
3886 */
3887 draw_polygon(dr, coords, n, -1, ink);
3888 }
3889
3890 sfree(coords);
3891 }
3892
3893 /*
3894 * Numbers.
3895 */
3896 for (y = 0; y < cr; y++)
3897 for (x = 0; x < cr; x++)
3898 if (state->grid[y*cr+x]) {
3899 char str[2];
3900 str[1] = '\0';
3901 str[0] = state->grid[y*cr+x] + '0';
3902 if (str[0] > '9')
3903 str[0] += 'a' - ('9'+1);
3904 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
3905 BORDER + y*TILE_SIZE + TILE_SIZE/2,
3906 FONT_VARIABLE, TILE_SIZE/2,
3907 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
3908 }
3909 }
3910
3911 #ifdef COMBINED
3912 #define thegame solo
3913 #endif
3914
3915 const struct game thegame = {
3916 "Solo", "games.solo", "solo",
3917 default_params,
3918 game_fetch_preset,
3919 decode_params,
3920 encode_params,
3921 free_params,
3922 dup_params,
3923 TRUE, game_configure, custom_params,
3924 validate_params,
3925 new_game_desc,
3926 validate_desc,
3927 new_game,
3928 dup_game,
3929 free_game,
3930 TRUE, solve_game,
3931 TRUE, game_text_format,
3932 new_ui,
3933 free_ui,
3934 encode_ui,
3935 decode_ui,
3936 game_changed_state,
3937 interpret_move,
3938 execute_move,
3939 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3940 game_colours,
3941 game_new_drawstate,
3942 game_free_drawstate,
3943 game_redraw,
3944 game_anim_length,
3945 game_flash_length,
3946 TRUE, FALSE, game_print_size, game_print,
3947 FALSE, /* wants_statusbar */
3948 FALSE, game_timing_state,
3949 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
3950 };
3951
3952 #ifdef STANDALONE_SOLVER
3953
3954 int main(int argc, char **argv)
3955 {
3956 game_params *p;
3957 game_state *s;
3958 char *id = NULL, *desc, *err;
3959 int grade = FALSE;
3960 int ret;
3961
3962 while (--argc > 0) {
3963 char *p = *++argv;
3964 if (!strcmp(p, "-v")) {
3965 solver_show_working = TRUE;
3966 } else if (!strcmp(p, "-g")) {
3967 grade = TRUE;
3968 } else if (*p == '-') {
3969 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3970 return 1;
3971 } else {
3972 id = p;
3973 }
3974 }
3975
3976 if (!id) {
3977 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3978 return 1;
3979 }
3980
3981 desc = strchr(id, ':');
3982 if (!desc) {
3983 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3984 return 1;
3985 }
3986 *desc++ = '\0';
3987
3988 p = default_params();
3989 decode_params(p, id);
3990 err = validate_desc(p, desc);
3991 if (err) {
3992 fprintf(stderr, "%s: %s\n", argv[0], err);
3993 return 1;
3994 }
3995 s = new_game(NULL, p, desc);
3996
3997 ret = solver(s->cr, s->blocks, s->xtype, s->grid, DIFF_RECURSIVE);
3998 if (grade) {
3999 printf("Difficulty rating: %s\n",
4000 ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
4001 ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
4002 ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
4003 ret==DIFF_SET ? "Advanced (set elimination required)":
4004 ret==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
4005 ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
4006 ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
4007 ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
4008 "INTERNAL ERROR: unrecognised difficulty code");
4009 } else {
4010 printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
4011 }
4012
4013 return 0;
4014 }
4015
4016 #endif