1 /* -*- tab-width: 8; indent-tabs-mode: t -*-
2 * filling.c: An implementation of the Nikoli game fillomino.
3 * Copyright (C) 2007 Jonas Kölker. See LICENSE for the license.
8 * - use a typedef instead of int for numbers on the board
9 * + replace int with something else (signed short?)
10 * - the type should be signed (for -board[i] and -SENTINEL)
11 * - the type should be somewhat big: board[i] = i
12 * - Using shorts gives us 181x181 puzzles as upper bound.
14 * - in board generation, after having merged regions such that no
15 * more merges are necessary, try splitting (big) regions.
16 * + it seems that smaller regions make for better puzzles; see
17 * for instance the 7x7 puzzle in this file (grep for 7x7:).
19 * - symmetric hints (solo-style)
20 * + right now that means including _many_ hints, and the puzzles
21 * won't look any nicer. Not worth it (at the moment).
23 * - make the solver do recursion/backtracking.
24 * + This is for user-submitted puzzles, not for puzzle
25 * generation (on the other hand, never say never).
27 * - prove that only w=h=2 needs a special case
29 * - solo-like pencil marks?
31 * - a user says that the difficulty is unevenly distributed.
32 * + partition into levels? Will they be non-crap?
34 * - Allow square contents > 9?
35 * + I could use letters for digits (solo does this), but
36 * letters don't have numeric significance (normal people hate
37 * base36), which is relevant here (much more than in solo).
38 * + [click, 1, 0, enter] => [10 in clicked square]?
39 * + How much information is needed to solve? Does one need to
40 * know the algorithm by which the largest number is set?
42 * - eliminate puzzle instances with done chunks (1's in particular)?
43 * + that's what the qsort call is all about.
44 * + the 1's don't bother me that much.
45 * + but this takes a LONG time (not always possible)?
46 * - this may be affected by solver (lack of) quality.
47 * - weed them out by construction instead of post-cons check
48 * + but that interleaves make_board and new_game_desc: you
49 * have to alternate between changing the board and
50 * changing the hint set (instead of just creating the
51 * board once, then changing the hint set once -> done).
53 * - use binary search when discovering the minimal sovable point
54 * + profile to show a need (but when the solver gets slower...)
55 * + 7x9 @ .011s, 9x13 @ .075s, 17x13 @ .661s (all avg with n=100)
56 * + but the hints are independent, not linear, so... what?
69 static unsigned char verbose;
71 static void printv(char *fmt, ...) {
82 /*****************************************************************************
83 * GAME CONFIGURATION AND PARAMETERS *
84 *****************************************************************************/
91 struct game_params params;
98 struct shared_state *shared;
99 int completed, cheated;
102 static const struct game_params filling_defaults[3] = {
103 {9, 7}, {13, 9}, {17, 13}
106 static game_params *default_params(void)
108 game_params *ret = snew(game_params);
110 *ret = filling_defaults[1]; /* struct copy */
115 static int game_fetch_preset(int i, char **name, game_params **params)
119 if (i < 0 || i >= lenof(filling_defaults)) return FALSE;
120 *params = snew(game_params);
121 **params = filling_defaults[i]; /* struct copy */
122 sprintf(buf, "%dx%d", filling_defaults[i].w, filling_defaults[i].h);
128 static void free_params(game_params *params)
133 static game_params *dup_params(const game_params *params)
135 game_params *ret = snew(game_params);
136 *ret = *params; /* struct copy */
140 static void decode_params(game_params *ret, char const *string)
142 ret->w = ret->h = atoi(string);
143 while (*string && isdigit((unsigned char) *string)) ++string;
144 if (*string == 'x') ret->h = atoi(++string);
147 static char *encode_params(const game_params *params, int full)
150 sprintf(buf, "%dx%d", params->w, params->h);
154 static config_item *game_configure(const game_params *params)
159 ret = snewn(3, config_item);
161 ret[0].name = "Width";
162 ret[0].type = C_STRING;
163 sprintf(buf, "%d", params->w);
164 ret[0].sval = dupstr(buf);
167 ret[1].name = "Height";
168 ret[1].type = C_STRING;
169 sprintf(buf, "%d", params->h);
170 ret[1].sval = dupstr(buf);
181 static game_params *custom_params(const config_item *cfg)
183 game_params *ret = snew(game_params);
185 ret->w = atoi(cfg[0].sval);
186 ret->h = atoi(cfg[1].sval);
191 static char *validate_params(const game_params *params, int full)
193 if (params->w < 1) return "Width must be at least one";
194 if (params->h < 1) return "Height must be at least one";
199 /*****************************************************************************
200 * STRINGIFICATION OF GAME STATE *
201 *****************************************************************************/
205 /* Example of plaintext rendering:
206 * +---+---+---+---+---+---+---+
207 * | 6 | | | 2 | | | 2 |
208 * +---+---+---+---+---+---+---+
209 * | | 3 | | 6 | | 3 | |
210 * +---+---+---+---+---+---+---+
211 * | 3 | | | | | | 1 |
212 * +---+---+---+---+---+---+---+
213 * | | 2 | 3 | | 4 | 2 | |
214 * +---+---+---+---+---+---+---+
215 * | 2 | | | | | | 3 |
216 * +---+---+---+---+---+---+---+
217 * | | 5 | | 1 | | 4 | |
218 * +---+---+---+---+---+---+---+
219 * | 4 | | | 3 | | | 3 |
220 * +---+---+---+---+---+---+---+
222 * This puzzle instance is taken from the nikoli website
223 * Encoded (unsolved and solved), the strings are these:
224 * 7x7:6002002030603030000010230420200000305010404003003
225 * 7x7:6662232336663232331311235422255544325413434443313
227 static char *board_to_string(int *board, int w, int h) {
228 const int sz = w * h;
229 const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
230 const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
231 const int chlen = chw * chh;
232 char *repr = snewn(chlen + 1, char);
237 /* build the first line ("^(\+---){n}\+$") */
238 for (i = 0; i < w; ++i) {
245 repr[4*i + 1] = '\n';
247 /* ... and copy it onto the odd-numbered lines */
248 for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
250 /* build the second line ("^(\|\t){n}\|$") */
251 for (i = 0; i < w; ++i) {
252 repr[chw + 4*i + 0] = '|';
253 repr[chw + 4*i + 1] = ' ';
254 repr[chw + 4*i + 2] = ' ';
255 repr[chw + 4*i + 3] = ' ';
257 repr[chw + 4*i + 0] = '|';
258 repr[chw + 4*i + 1] = '\n';
260 /* ... and copy it onto the even-numbered lines */
261 for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
263 /* fill in the numbers */
264 for (i = 0; i < sz; ++i) {
267 if (board[i] == EMPTY) continue;
268 repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
275 static int game_can_format_as_text_now(const game_params *params)
280 static char *game_text_format(const game_state *state)
282 const int w = state->shared->params.w;
283 const int h = state->shared->params.h;
284 return board_to_string(state->board, w, h);
287 /*****************************************************************************
288 * GAME GENERATION AND SOLVER *
289 *****************************************************************************/
291 static const int dx[4] = {-1, 1, 0, 0};
292 static const int dy[4] = {0, 0, -1, 1};
301 /* Used internally by learn_bitmap_deductions; kept here to avoid
302 * mallocing/freeing them every time that function is called. */
303 int *bm, *bmdsf, *bmminsize;
306 static void print_board(int *board, int w, int h) {
308 char *repr = board_to_string(board, w, h);
309 printv("%s\n", repr);
314 static game_state *new_game(midend *, const game_params *, const char *);
315 static void free_game(game_state *);
319 static int mark_region(int *board, int w, int h, int i, int n, int m) {
324 for (j = 0; j < 4; ++j) {
325 const int x = (i % w) + dx[j], y = (i / w) + dy[j], ii = w*y + x;
326 if (x < 0 || x >= w || y < 0 || y >= h) continue;
327 if (board[ii] == m) return FALSE;
328 if (board[ii] != n) continue;
329 if (!mark_region(board, w, h, ii, n, m)) return FALSE;
334 static int region_size(int *board, int w, int h, int i) {
335 const int sz = w * h;
337 if (board[i] == 0) return 0;
339 mark_region(board, w, h, i, board[i], SENTINEL);
340 for (size = j = 0; j < sz; ++j) {
341 if (board[j] != -1) continue;
348 static void merge_ones(int *board, int w, int h)
350 const int sz = w * h;
351 const int maxsize = min(max(max(w, h), 3), 9);
355 for (i = 0; i < sz; ++i) {
356 if (board[i] != 1) continue;
358 for (j = 0; j < 4; ++j, board[i] = 1) {
359 const int x = (i % w) + dx[j], y = (i / w) + dy[j];
360 int oldsize, newsize, ok, ii = w*y + x;
361 if (x < 0 || x >= w || y < 0 || y >= h) continue;
362 if (board[ii] == maxsize) continue;
366 newsize = region_size(board, w, h, i);
368 if (newsize > maxsize) continue;
370 ok = mark_region(board, w, h, i, oldsize, newsize);
372 for (k = 0; k < sz; ++k)
374 board[k] = ok ? newsize : oldsize;
378 if (j < 4) change = TRUE;
383 /* generate a random valid board; uses validate_board. */
384 static void make_board(int *board, int w, int h, random_state *rs) {
385 const int sz = w * h;
387 /* w=h=2 is a special case which requires a number > max(w, h) */
388 /* TODO prove that this is the case ONLY for w=h=2. */
389 const int maxsize = min(max(max(w, h), 3), 9);
391 /* Note that if 1 in {w, h} then it's impossible to have a region
392 * of size > w*h, so the special case only affects w=h=2. */
400 /* I abuse the board variable: when generating the puzzle, it
401 * contains a shuffled list of numbers {0, ..., sz-1}. */
402 for (i = 0; i < sz; ++i) board[i] = i;
404 dsf = snewn(sz, int);
407 shuffle(board, sz, sizeof (int), rs);
410 change = FALSE; /* as long as the board potentially has errors */
411 for (i = 0; i < sz; ++i) {
412 const int square = dsf_canonify(dsf, board[i]);
413 const int size = dsf_size(dsf, square);
414 int merge = SENTINEL, min = maxsize - size + 1, error = FALSE;
415 int neighbour, neighbour_size, j;
417 for (j = 0; j < 4; ++j) {
418 const int x = (board[i] % w) + dx[j];
419 const int y = (board[i] / w) + dy[j];
420 if (x < 0 || x >= w || y < 0 || y >= h) continue;
422 neighbour = dsf_canonify(dsf, w*y + x);
423 if (square == neighbour) continue;
425 neighbour_size = dsf_size(dsf, neighbour);
426 if (size == neighbour_size) error = TRUE;
428 /* find the smallest neighbour to merge with, which
429 * wouldn't make the region too large. (This is
430 * guaranteed by the initial value of `min'.) */
431 if (neighbour_size < min) {
432 min = neighbour_size;
437 /* if this square is not in error, leave it be */
438 if (!error) continue;
440 /* if it is, but we can't fix it, retry the whole board.
441 * Maybe we could fix it by merging the conflicting
442 * neighbouring region(s) into some of their neighbours,
443 * but just restarting works out fine. */
444 if (merge == SENTINEL) goto retry;
446 /* merge with the smallest neighbouring workable region. */
447 dsf_merge(dsf, square, merge);
452 for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
453 merge_ones(board, w, h);
458 static void merge(int *dsf, int *connected, int a, int b) {
462 a = dsf_canonify(dsf, a);
463 b = dsf_canonify(dsf, b);
465 dsf_merge(dsf, a, b);
467 connected[a] = connected[b];
471 static void *memdup(const void *ptr, size_t len, size_t esz) {
472 void *dup = smalloc(len * esz);
474 memcpy(dup, ptr, len * esz);
478 static void expand(struct solver_state *s, int w, int h, int t, int f) {
481 assert(s->board[t] == EMPTY); /* expand to empty square */
482 assert(s->board[f] != EMPTY); /* expand from non-empty square */
484 "learn: expanding %d from (%d, %d) into (%d, %d)\n",
485 s->board[f], f % w, f / w, t % w, t / w);
486 s->board[t] = s->board[f];
487 for (j = 0; j < 4; ++j) {
488 const int x = (t % w) + dx[j];
489 const int y = (t / w) + dy[j];
490 const int idx = w*y + x;
491 if (x < 0 || x >= w || y < 0 || y >= h) continue;
492 if (s->board[idx] != s->board[t]) continue;
493 merge(s->dsf, s->connected, t, idx);
498 static void clear_count(int *board, int sz) {
500 for (i = 0; i < sz; ++i) {
501 if (board[i] >= 0) continue;
502 else if (board[i] == -SENTINEL) board[i] = EMPTY;
503 else board[i] = -board[i];
507 static void flood_count(int *board, int w, int h, int i, int n, int *c) {
508 const int sz = w * h;
511 if (board[i] == EMPTY) board[i] = -SENTINEL;
512 else if (board[i] == n) board[i] = -board[i];
515 if (--*c == 0) return;
517 for (k = 0; k < 4; ++k) {
518 const int x = (i % w) + dx[k];
519 const int y = (i / w) + dy[k];
520 const int idx = w*y + x;
521 if (x < 0 || x >= w || y < 0 || y >= h) continue;
522 flood_count(board, w, h, idx, n, c);
527 static int check_capacity(int *board, int w, int h, int i) {
529 flood_count(board, w, h, i, board[i], &n);
530 clear_count(board, w * h);
534 static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
539 for (j = 0; j < 4; ++j) {
540 const int x = (i % w) + dx[j];
541 const int y = (i / w) + dy[j];
542 const int idx = w*y + x;
545 if (x < 0 || x >= w || y < 0 || y >= h) continue;
546 if (board[idx] != n) continue;
547 root = dsf_canonify(dsf, idx);
548 for (m = 0; m < nhits && root != hits[m]; ++m);
549 if (m < nhits) continue;
550 printv("\t (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
551 size += dsf_size(dsf, root);
552 assert(dsf_size(dsf, root) >= 1);
553 hits[nhits++] = root;
559 * +---+---+---+---+---+---+---+
560 * | 6 | | | 2 | | | 2 |
561 * +---+---+---+---+---+---+---+
562 * | | 3 | | 6 | | 3 | |
563 * +---+---+---+---+---+---+---+
564 * | 3 | | | | | | 1 |
565 * +---+---+---+---+---+---+---+
566 * | | 2 | 3 | | 4 | 2 | |
567 * +---+---+---+---+---+---+---+
568 * | 2 | | | | | | 3 |
569 * +---+---+---+---+---+---+---+
570 * | | 5 | | 1 | | 4 | |
571 * +---+---+---+---+---+---+---+
572 * | 4 | | | 3 | | | 3 |
573 * +---+---+---+---+---+---+---+
576 /* Solving techniques:
578 * CONNECTED COMPONENT FORCED EXPANSION (too big):
579 * When a CC can only be expanded in one direction, because all the
580 * other ones would make the CC too big.
581 * +---+---+---+---+---+
582 * | 2 | 2 | | 2 | _ |
583 * +---+---+---+---+---+
585 * CONNECTED COMPONENT FORCED EXPANSION (too small):
586 * When a CC must include a particular square, because otherwise there
587 * would not be enough room to complete it. This includes squares not
588 * adjacent to the CC through learn_critical_square.
594 * When an empty square has no neighbouring empty squares and only a 1
595 * will go into the square (or other CCs would be too big).
600 * TODO: generalise DROPPING IN A ONE: find the size of the CC of
601 * empty squares and a list of all adjacent numbers. See if only one
602 * number in {1, ..., size} u {all adjacent numbers} is possible.
603 * Probably this is only effective for a CC size < n for some n (4?)
605 * TODO: backtracking.
608 static void filled_square(struct solver_state *s, int w, int h, int i) {
610 for (j = 0; j < 4; ++j) {
611 const int x = (i % w) + dx[j];
612 const int y = (i / w) + dy[j];
613 const int idx = w*y + x;
614 if (x < 0 || x >= w || y < 0 || y >= h) continue;
615 if (s->board[i] == s->board[idx])
616 merge(s->dsf, s->connected, i, idx);
620 static void init_solver_state(struct solver_state *s, int w, int h) {
621 const int sz = w * h;
626 for (i = 0; i < sz; ++i) s->connected[i] = i;
627 for (i = 0; i < sz; ++i)
628 if (s->board[i] == EMPTY) ++s->nempty;
629 else filled_square(s, w, h, i);
632 static int learn_expand_or_one(struct solver_state *s, int w, int h) {
633 const int sz = w * h;
639 for (i = 0; i < sz; ++i) {
643 if (s->board[i] != EMPTY) continue;
645 for (j = 0; j < 4; ++j) {
646 const int x = (i % w) + dx[j];
647 const int y = (i / w) + dy[j];
648 const int idx = w*y + x;
649 if (x < 0 || x >= w || y < 0 || y >= h) continue;
650 if (s->board[idx] == EMPTY) {
655 (s->board[idx] == 1 ||
656 (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
659 if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
660 assert(s->board[i] == EMPTY);
661 s->board[i] = -SENTINEL;
662 if (check_capacity(s->board, w, h, idx)) continue;
663 assert(s->board[i] == EMPTY);
664 printv("learn: expanding in one\n");
665 expand(s, w, h, i, idx);
671 printv("learn: one at (%d, %d)\n", i % w, i / w);
672 assert(s->board[i] == EMPTY);
682 static int learn_blocked_expansion(struct solver_state *s, int w, int h) {
683 const int sz = w * h;
688 /* for every connected component */
689 for (i = 0; i < sz; ++i) {
693 if (s->board[i] == EMPTY) continue;
694 j = dsf_canonify(s->dsf, i);
696 /* (but only for each connected component) */
697 if (i != j) continue;
699 /* (and not if it's already complete) */
700 if (dsf_size(s->dsf, j) == s->board[j]) continue;
702 /* for each square j _in_ the connected component */
705 printv(" looking at (%d, %d)\n", j % w, j / w);
707 /* for each neighbouring square (idx) */
708 for (k = 0; k < 4; ++k) {
709 const int x = (j % w) + dx[k];
710 const int y = (j / w) + dy[k];
711 const int idx = w*y + x;
716 if (x < 0 || x >= w || y < 0 || y >= h) continue;
717 if (s->board[idx] != EMPTY) continue;
718 if (exp == idx) continue;
719 printv("\ttrying to expand onto (%d, %d)\n", x, y);
721 /* find out the would-be size of the new connected
722 * component if we actually expanded into idx */
725 for (l = 0; l < 4; ++l) {
726 const int lx = x + dx[l];
727 const int ly = y + dy[l];
728 const int idxl = w*ly + lx;
731 if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
732 if (board[idxl] != board[j]) continue;
733 root = dsf_canonify(dsf, idxl);
734 for (m = 0; m < nhits && root != hits[m]; ++m);
735 if (m != nhits) continue;
736 // printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
737 size += dsf_size(dsf, root);
738 assert(dsf_size(dsf, root) >= 1);
739 hits[nhits++] = root;
743 size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
745 /* ... and see if that size is too big, or if we
746 * have other expansion candidates. Otherwise
747 * remember the (so far) only candidate. */
749 printv("\tthat would give a size of %d\n", size);
750 if (size > s->board[j]) continue;
751 /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
752 if (exp != SENTINEL) goto next_i;
757 j = s->connected[j]; /* next square in the same CC */
758 assert(s->board[i] == s->board[j]);
760 /* end: for each square j _in_ the connected component */
762 if (exp == SENTINEL) continue;
763 printv("learning to expand\n");
764 expand(s, w, h, exp, i);
770 /* end: for each connected component */
774 static int learn_critical_square(struct solver_state *s, int w, int h) {
775 const int sz = w * h;
780 /* for each connected component */
781 for (i = 0; i < sz; ++i) {
783 if (s->board[i] == EMPTY) continue;
784 if (i != dsf_canonify(s->dsf, i)) continue;
785 slack = s->board[i] - dsf_size(s->dsf, i);
786 if (slack == 0) continue;
787 assert(s->board[i] != 1);
788 /* for each empty square */
789 for (j = 0; j < sz; ++j) {
790 if (s->board[j] == EMPTY) {
791 /* if it's too far away from the CC, don't bother */
792 int k = i, jx = j % w, jy = j / w;
794 int kx = k % w, ky = k / w;
795 if (abs(kx - jx) + abs(ky - jy) <= slack) break;
798 if (i == k) continue; /* not within range */
800 s->board[j] = -SENTINEL;
801 if (check_capacity(s->board, w, h, i)) continue;
802 /* if not expanding s->board[i] to s->board[j] implies
803 * that s->board[i] can't reach its full size, ... */
806 "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
807 s->board[i], j % w, j / w, i % w, i / w);
809 s->board[j] = s->board[i];
810 filled_square(s, w, h, j);
818 static void print_bitmap(int *bitmap, int w, int h) {
821 for (y = 0; y < h; y++) {
822 for (x = 0; x < w; x++) {
823 printv(" %03x", bm[y*w+x]);
831 static int learn_bitmap_deductions(struct solver_state *s, int w, int h)
833 const int sz = w * h;
836 int *minsize = s->bmminsize;
841 * This function does deductions based on building up a bitmap
842 * which indicates the possible numbers that can appear in each
843 * grid square. If we can rule out all but one possibility for a
844 * particular square, then we've found out the value of that
845 * square. In particular, this is one of the few forms of
846 * deduction capable of inferring the existence of a 'ghost
847 * region', i.e. a region which has none of its squares filled in
850 * The reasoning goes like this. A currently unfilled square S can
851 * turn out to contain digit n in exactly two ways: either S is
852 * part of an n-region which also includes some currently known
853 * connected component of squares with n in, or S is part of an
854 * n-region separate from _all_ currently known connected
855 * components. If we can rule out both possibilities, then square
856 * S can't contain digit n at all.
858 * The former possibility: if there's a region of size n
859 * containing both S and some existing component C, then that
860 * means the distance from S to C must be small enough that C
861 * could be extended to include S without becoming too big. So we
862 * can do a breadth-first search out from all existing components
863 * with n in them, to identify all the squares which could be
864 * joined to any of them.
866 * The latter possibility: if there's a region of size n that
867 * doesn't contain _any_ existing component, then it also can't
868 * contain any square adjacent to an existing component either. So
869 * we can identify all the EMPTY squares not adjacent to any
870 * existing square with n in, and group them into connected
871 * components; then any component of size less than n is ruled
872 * out, because there wouldn't be room to create a completely new
875 * In fact we process these possibilities in the other order.
876 * First we find all the squares not adjacent to an existing
877 * square with n in; then we winnow those by removing too-small
878 * connected components, to get the set of squares which could
879 * possibly be part of a brand new n-region; and finally we do the
880 * breadth-first search to add in the set of squares which could
881 * possibly be added to some existing n-region.
885 * Start by initialising our bitmap to 'all numbers possible in
888 for (y = 0; y < h; y++)
889 for (x = 0; x < w; x++)
890 bm[y*w+x] = (1 << 10) - (1 << 1); /* bits 1,2,...,9 now set */
892 printv("initial bitmap:\n");
893 print_bitmap(bm, w, h);
897 * Now completely zero out the bitmap for squares that are already
898 * filled in (we aren't interested in those anyway). Also, for any
899 * filled square, eliminate its number from all its neighbours
900 * (because, as discussed above, the neighbours couldn't be part
901 * of a _new_ region with that number in it, and that's the case
902 * we consider first).
904 for (y = 0; y < h; y++) {
905 for (x = 0; x < w; x++) {
913 bm[i-1] &= ~(1 << n);
915 bm[i+1] &= ~(1 << n);
917 bm[i-w] &= ~(1 << n);
919 bm[i+w] &= ~(1 << n);
924 printv("bitmap after filled squares:\n");
925 print_bitmap(bm, w, h);
929 * Now, for each n, we separately find the connected components of
930 * squares for which n is still a possibility. Then discard any
931 * component of size < n, because that component is too small to
932 * have a completely new n-region in it.
934 for (n = 1; n <= 9; n++) {
938 for (y = 0; y < h; y++)
939 for (x = 0; x+1 < w; x++)
940 if (bm[y*w+x] & bm[y*w+(x+1)] & (1 << n))
941 dsf_merge(dsf, y*w+x, y*w+(x+1));
942 for (y = 0; y+1 < h; y++)
943 for (x = 0; x < w; x++)
944 if (bm[y*w+x] & bm[(y+1)*w+x] & (1 << n))
945 dsf_merge(dsf, y*w+x, (y+1)*w+x);
948 for (i = 0; i < sz; i++)
949 if ((bm[i] & (1 << n)) && dsf_size(dsf, i) < n)
953 printv("bitmap after winnowing small components:\n");
954 print_bitmap(bm, w, h);
958 * Now our bitmap includes every square which could be part of a
959 * completely new region, of any size. Extend it to include
960 * squares which could be part of an existing region.
962 for (n = 1; n <= 9; n++) {
964 * We're going to do a breadth-first search starting from
965 * existing connected components with cell value n, to find
966 * all cells they might possibly extend into.
968 * The quantity we compute, for each square, is 'minimum size
969 * that any existing CC would have to have if extended to
970 * include this square'. So squares already _in_ an existing
971 * CC are initialised to the size of that CC; then we search
972 * outwards using the rule that if a square's score is j, then
973 * its neighbours can't score more than j+1.
975 * Scores are capped at n+1, because if a square scores more
976 * than n then that's enough to know it can't possibly be
977 * reached by extending an existing region - we don't need to
978 * know exactly _how far_ out of reach it is.
980 for (i = 0; i < sz; i++) {
981 if (s->board[i] == n) {
982 /* Square is part of an existing CC. */
983 minsize[i] = dsf_size(s->dsf, i);
985 /* Otherwise, initialise to the maximum score n+1;
986 * we'll reduce this later if we find a neighbouring
987 * square with a lower score. */
992 for (j = 1; j < n; j++) {
994 * Find neighbours of cells scoring j, and set their score
997 * Doing the BFS this way means we need n passes over the
998 * grid, which isn't entirely optimal but it seems to be
999 * fast enough for the moment. This could probably be
1000 * improved by keeping a linked-list queue of cells in
1001 * some way, but I think you'd have to be a bit careful to
1002 * insert things into the right place in the queue; this
1003 * way is easier not to get wrong.
1005 for (y = 0; y < h; y++) {
1006 for (x = 0; x < w; x++) {
1008 if (minsize[i] == j) {
1009 if (x > 0 && minsize[i-1] > j+1)
1011 if (x+1 < w && minsize[i+1] > j+1)
1013 if (y > 0 && minsize[i-w] > j+1)
1015 if (y+1 < h && minsize[i+w] > j+1)
1023 * Now, every cell scoring at most n should have its 1<<n bit
1024 * in the bitmap reinstated, because we've found that it's
1025 * potentially reachable by extending an existing CC.
1027 for (i = 0; i < sz; i++)
1028 if (minsize[i] <= n)
1032 printv("bitmap after bfs:\n");
1033 print_bitmap(bm, w, h);
1037 * Now our bitmap is complete. Look for entries with only one bit
1038 * set; those are squares with only one possible number, in which
1039 * case we can fill that number in.
1041 for (i = 0; i < sz; i++) {
1042 if (bm[i] && !(bm[i] & (bm[i]-1))) { /* is bm[i] a power of two? */
1045 /* Integer log2, by simple binary search. */
1047 if (val >> 8) { val >>= 8; n += 8; }
1048 if (val >> 4) { val >>= 4; n += 4; }
1049 if (val >> 2) { val >>= 2; n += 2; }
1050 if (val >> 1) { val >>= 1; n += 1; }
1052 /* Double-check that we ended up with a sensible
1056 assert(bm[i] == (1 << n));
1058 if (s->board[i] == EMPTY) {
1059 printv("learn: %d is only possibility at (%d, %d)\n",
1062 filled_square(s, w, h, i);
1073 static int solver(const int *orig, int w, int h, char **solution) {
1074 const int sz = w * h;
1076 struct solver_state ss;
1077 ss.board = memdup(orig, sz, sizeof (int));
1078 ss.dsf = snew_dsf(sz); /* eqv classes: connected components */
1079 ss.connected = snewn(sz, int); /* connected[n] := n.next; */
1080 /* cyclic disjoint singly linked lists, same partitioning as dsf.
1081 * The lists lets you iterate over a partition given any member */
1082 ss.bm = snewn(sz, int);
1083 ss.bmdsf = snew_dsf(sz);
1084 ss.bmminsize = snewn(sz, int);
1086 printv("trying to solve this:\n");
1087 print_board(ss.board, w, h);
1089 init_solver_state(&ss, w, h);
1091 if (learn_blocked_expansion(&ss, w, h)) continue;
1092 if (learn_expand_or_one(&ss, w, h)) continue;
1093 if (learn_critical_square(&ss, w, h)) continue;
1094 if (learn_bitmap_deductions(&ss, w, h)) continue;
1096 } while (ss.nempty);
1098 printv("best guess:\n");
1099 print_board(ss.board, w, h);
1103 *solution = snewn(sz + 2, char);
1105 for (i = 0; i < sz; ++i) (*solution)[i + 1] = ss.board[i] + '0';
1106 (*solution)[sz + 1] = '\0';
1107 /* We don't need the \0 for execute_move (the only user)
1108 * I'm just being printf-friendly in case I wanna print */
1113 sfree(ss.connected);
1116 sfree(ss.bmminsize);
1121 static int *make_dsf(int *dsf, int *board, const int w, const int h) {
1122 const int sz = w * h;
1126 dsf = snew_dsf(w * h);
1128 dsf_init(dsf, w * h);
1130 for (i = 0; i < sz; ++i) {
1132 for (j = 0; j < 4; ++j) {
1133 const int x = (i % w) + dx[j];
1134 const int y = (i / w) + dy[j];
1135 const int k = w*y + x;
1136 if (x < 0 || x >= w || y < 0 || y >= h) continue;
1137 if (board[i] == board[k]) dsf_merge(dsf, i, k);
1143 static void minimize_clue_set(int *board, int w, int h, random_state *rs)
1145 const int sz = w * h;
1146 int *shuf = snewn(sz, int), i;
1149 for (i = 0; i < sz; ++i) shuf[i] = i;
1150 shuffle(shuf, sz, sizeof (int), rs);
1153 * First, try to eliminate an entire region at a time if possible,
1154 * because inferring the existence of a completely unclued region
1155 * is a particularly good aspect of this puzzle type and we want
1156 * to encourage it to happen.
1158 * Begin by identifying the regions as linked lists of cells using
1161 dsf = make_dsf(NULL, board, w, h);
1162 next = snewn(sz, int);
1163 for (i = 0; i < sz; ++i) {
1164 int j = dsf_canonify(dsf, i);
1166 /* First cell of a region; set next[i] = -1 to indicate
1170 /* Add this cell to a region which already has a
1171 * linked-list head, by pointing the canonical element j
1172 * at this one, and pointing this one in turn at wherever
1173 * j previously pointed. (This should end up with the
1174 * elements linked in the order 1,n,n-1,n-2,...,2, which
1175 * is a bit weird-looking, but any order is fine.)
1184 * Now loop over the grid cells in our shuffled order, and each
1185 * time we encounter a region for the first time, try to remove it
1186 * all. Then we set next[canonical index] to -2 rather than -1, to
1187 * mark it as already tried.
1189 * Doing this in a loop over _cells_, rather than extracting and
1190 * shuffling a list of _regions_, is intended to skew the
1191 * probabilities towards trying to remove larger regions first
1192 * (but without anything as crudely predictable as enforcing that
1193 * we _always_ process regions in descending size order). Region
1194 * removals might well be mutually exclusive, and larger ghost
1195 * regions are more interesting, so we want to bias towards them
1198 for (i = 0; i < sz; ++i) {
1199 int j = dsf_canonify(dsf, shuf[i]);
1200 if (next[j] != -2) {
1204 /* Blank out the whole thing. */
1205 for (k = j; k >= 0; k = next[k])
1208 if (!solver(board, w, h, NULL)) {
1209 /* Wasn't still solvable; reinstate it all */
1210 for (k = j; k >= 0; k = next[k])
1214 /* Either way, don't try this region again. */
1222 * Now go through individual cells, in the same shuffled order,
1223 * and try to remove each one by itself.
1225 for (i = 0; i < sz; ++i) {
1226 int tmp = board[shuf[i]];
1227 board[shuf[i]] = EMPTY;
1228 if (!solver(board, w, h, NULL)) board[shuf[i]] = tmp;
1234 static int encode_run(char *buffer, int run)
1237 for (; run > 26; run -= 26)
1240 buffer[i++] = 'a' - 1 + run;
1244 static char *new_game_desc(const game_params *params, random_state *rs,
1245 char **aux, int interactive)
1247 const int w = params->w, h = params->h, sz = w * h;
1248 int *board = snewn(sz, int), i, j, run;
1249 char *description = snewn(sz + 1, char);
1251 make_board(board, w, h, rs);
1252 minimize_clue_set(board, w, h, rs);
1254 for (run = j = i = 0; i < sz; ++i) {
1255 assert(board[i] >= 0);
1256 assert(board[i] < 10);
1257 if (board[i] == 0) {
1260 j += encode_run(description + j, run);
1262 description[j++] = board[i] + '0';
1265 j += encode_run(description + j, run);
1266 description[j++] = '\0';
1270 return sresize(description, j, char);
1273 static char *validate_desc(const game_params *params, const char *desc)
1275 const int sz = params->w * params->h;
1276 const char m = '0' + max(max(params->w, params->h), 3);
1279 for (area = 0; *desc; ++desc) {
1280 if (*desc >= 'a' && *desc <= 'z') area += *desc - 'a' + 1;
1281 else if (*desc >= '0' && *desc <= m) ++area;
1283 static char s[] = "Invalid character '%""' in game description";
1284 int n = sprintf(s, "Invalid character '%1c' in game description",
1286 assert(n + 1 <= lenof(s)); /* +1 for the terminating NUL */
1289 if (area > sz) return "Too much data to fit in grid";
1291 return (area < sz) ? "Not enough data to fill grid" : NULL;
1294 static game_state *new_game(midend *me, const game_params *params,
1297 game_state *state = snew(game_state);
1298 int sz = params->w * params->h;
1301 state->cheated = state->completed = FALSE;
1302 state->shared = snew(struct shared_state);
1303 state->shared->refcnt = 1;
1304 state->shared->params = *params; /* struct copy */
1305 state->shared->clues = snewn(sz, int);
1307 for (i = 0; *desc; ++desc) {
1308 if (*desc >= 'a' && *desc <= 'z') {
1309 int j = *desc - 'a' + 1;
1310 assert(i + j <= sz);
1311 for (; j; --j) state->shared->clues[i++] = 0;
1312 } else state->shared->clues[i++] = *desc - '0';
1314 state->board = memdup(state->shared->clues, sz, sizeof (int));
1319 static game_state *dup_game(const game_state *state)
1321 const int sz = state->shared->params.w * state->shared->params.h;
1322 game_state *ret = snew(game_state);
1324 ret->board = memdup(state->board, sz, sizeof (int));
1325 ret->shared = state->shared;
1326 ret->cheated = state->cheated;
1327 ret->completed = state->completed;
1328 ++ret->shared->refcnt;
1333 static void free_game(game_state *state)
1336 sfree(state->board);
1337 if (--state->shared->refcnt == 0) {
1338 sfree(state->shared->clues);
1339 sfree(state->shared);
1344 static char *solve_game(const game_state *state, const game_state *currstate,
1345 const char *aux, char **error)
1348 const int w = state->shared->params.w;
1349 const int h = state->shared->params.h;
1351 if (!solver(state->board, w, h, &new_aux))
1352 *error = "Sorry, I couldn't find a solution";
1358 /*****************************************************************************
1359 * USER INTERFACE STATE AND ACTION *
1360 *****************************************************************************/
1363 int *sel; /* w*h highlighted squares, or NULL */
1364 int cur_x, cur_y, cur_visible, keydragging;
1367 static game_ui *new_ui(const game_state *state)
1369 game_ui *ui = snew(game_ui);
1372 ui->cur_x = ui->cur_y = ui->cur_visible = ui->keydragging = 0;
1377 static void free_ui(game_ui *ui)
1384 static char *encode_ui(const game_ui *ui)
1389 static void decode_ui(game_ui *ui, const char *encoding)
1393 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1394 const game_state *newstate)
1396 /* Clear any selection */
1401 ui->keydragging = FALSE;
1404 #define PREFERRED_TILE_SIZE 32
1405 #define TILE_SIZE (ds->tilesize)
1406 #define BORDER (TILE_SIZE / 2)
1407 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1409 struct game_drawstate {
1410 struct game_params params;
1414 int *dsf_scratch, *border_scratch;
1417 static char *interpret_move(const game_state *state, game_ui *ui,
1418 const game_drawstate *ds,
1419 int x, int y, int button)
1421 const int w = state->shared->params.w;
1422 const int h = state->shared->params.h;
1424 const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1425 const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1433 button &= ~MOD_MASK;
1435 if (button == LEFT_BUTTON || button == LEFT_DRAG) {
1436 /* A left-click anywhere will clear the current selection. */
1437 if (button == LEFT_BUTTON) {
1443 if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
1445 ui->sel = snewn(w*h, int);
1446 memset(ui->sel, 0, w*h*sizeof(int));
1448 if (!state->shared->clues[w*ty+tx])
1449 ui->sel[w*ty+tx] = 1;
1451 ui->cur_visible = 0;
1452 return ""; /* redraw */
1455 if (IS_CURSOR_MOVE(button)) {
1456 ui->cur_visible = 1;
1457 move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, 0);
1458 if (ui->keydragging) goto select_square;
1461 if (button == CURSOR_SELECT) {
1462 if (!ui->cur_visible) {
1463 ui->cur_visible = 1;
1466 ui->keydragging = !ui->keydragging;
1467 if (!ui->keydragging) return "";
1471 ui->sel = snewn(w*h, int);
1472 memset(ui->sel, 0, w*h*sizeof(int));
1474 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1475 ui->sel[w*ui->cur_y + ui->cur_x] = 1;
1478 if (button == CURSOR_SELECT2) {
1479 if (!ui->cur_visible) {
1480 ui->cur_visible = 1;
1484 ui->sel = snewn(w*h, int);
1485 memset(ui->sel, 0, w*h*sizeof(int));
1487 ui->keydragging = FALSE;
1488 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1489 ui->sel[w*ui->cur_y + ui->cur_x] ^= 1;
1490 for (i = 0; i < w*h && !ui->sel[i]; i++);
1498 if (button == '\b' || button == 27) {
1501 ui->keydragging = FALSE;
1505 if (button < '0' || button > '9') return NULL;
1507 if (button > (w == 2 && h == 2 ? 3 : max(w, h))) return NULL;
1508 ui->keydragging = FALSE;
1510 for (i = 0; i < w*h; i++) {
1512 if ((ui->sel && ui->sel[i]) ||
1513 (!ui->sel && ui->cur_visible && (w*ui->cur_y+ui->cur_x) == i)) {
1514 if (state->shared->clues[i] != 0) continue; /* in case cursor is on clue */
1515 if (state->board[i] != button) {
1516 sprintf(buf, "%s%d", move ? "," : "", i);
1518 move = srealloc(move, strlen(move)+strlen(buf)+1);
1521 move = smalloc(strlen(buf)+1);
1529 sprintf(buf, "_%d", button);
1530 move = srealloc(move, strlen(move)+strlen(buf)+1);
1533 if (!ui->sel) return move ? move : NULL;
1536 /* Need to update UI at least, as we cleared the selection */
1537 return move ? move : "";
1540 static game_state *execute_move(const game_state *state, const char *move)
1542 game_state *new_state = NULL;
1543 const int sz = state->shared->params.w * state->shared->params.h;
1547 new_state = dup_game(state);
1548 for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
1549 new_state->cheated = TRUE;
1552 char *endptr, *delim = strchr(move, '_');
1553 if (!delim) goto err;
1554 value = strtol(delim+1, &endptr, 0);
1555 if (*endptr || endptr == delim+1) goto err;
1556 if (value < 0 || value > 9) goto err;
1557 new_state = dup_game(state);
1559 const int i = strtol(move, &endptr, 0);
1560 if (endptr == move) goto err;
1561 if (i < 0 || i >= sz) goto err;
1562 new_state->board[i] = value;
1563 if (*endptr == '_') break;
1564 if (*endptr != ',') goto err;
1570 * Check for completion.
1572 if (!new_state->completed) {
1573 const int w = new_state->shared->params.w;
1574 const int h = new_state->shared->params.h;
1575 const int sz = w * h;
1576 int *dsf = make_dsf(NULL, new_state->board, w, h);
1578 for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
1581 new_state->completed = TRUE;
1587 if (new_state) free_game(new_state);
1591 /* ----------------------------------------------------------------------
1595 #define FLASH_TIME 0.4F
1597 #define COL_CLUE COL_GRID
1609 static void game_compute_size(const game_params *params, int tilesize,
1612 *x = (params->w + 1) * tilesize;
1613 *y = (params->h + 1) * tilesize;
1616 static void game_set_size(drawing *dr, game_drawstate *ds,
1617 const game_params *params, int tilesize)
1619 ds->tilesize = tilesize;
1622 static float *game_colours(frontend *fe, int *ncolours)
1624 float *ret = snewn(3 * NCOLOURS, float);
1626 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1628 ret[COL_GRID * 3 + 0] = 0.0F;
1629 ret[COL_GRID * 3 + 1] = 0.0F;
1630 ret[COL_GRID * 3 + 2] = 0.0F;
1632 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1633 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1634 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1636 ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
1637 ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
1638 ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
1640 ret[COL_CURSOR * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1641 ret[COL_CURSOR * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1642 ret[COL_CURSOR * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1644 ret[COL_ERROR * 3 + 0] = 1.0F;
1645 ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1646 ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1648 ret[COL_USER * 3 + 0] = 0.0F;
1649 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1650 ret[COL_USER * 3 + 2] = 0.0F;
1652 *ncolours = NCOLOURS;
1656 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1658 struct game_drawstate *ds = snew(struct game_drawstate);
1661 ds->tilesize = PREFERRED_TILE_SIZE;
1663 ds->params = state->shared->params;
1664 ds->v = snewn(ds->params.w * ds->params.h, int);
1665 ds->flags = snewn(ds->params.w * ds->params.h, int);
1666 for (i = 0; i < ds->params.w * ds->params.h; i++)
1667 ds->v[i] = ds->flags[i] = -1;
1668 ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
1669 ds->dsf_scratch = NULL;
1674 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1678 sfree(ds->border_scratch);
1679 sfree(ds->dsf_scratch);
1683 #define BORDER_U 0x001
1684 #define BORDER_D 0x002
1685 #define BORDER_L 0x004
1686 #define BORDER_R 0x008
1687 #define BORDER_UR 0x010
1688 #define BORDER_DR 0x020
1689 #define BORDER_UL 0x040
1690 #define BORDER_DL 0x080
1691 #define HIGH_BG 0x100
1692 #define CORRECT_BG 0x200
1693 #define ERROR_BG 0x400
1694 #define USER_COL 0x800
1695 #define CURSOR_SQ 0x1000
1697 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
1704 * Clip to the grid square.
1706 clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1707 TILE_SIZE, TILE_SIZE);
1713 BORDER + x*TILE_SIZE,
1714 BORDER + y*TILE_SIZE,
1717 (flags & HIGH_BG ? COL_HIGHLIGHT :
1718 flags & ERROR_BG ? COL_ERROR :
1719 flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
1722 * Draw the grid lines.
1724 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1725 BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
1726 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1727 BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
1737 (x + 1) * TILE_SIZE,
1738 (y + 1) * TILE_SIZE,
1741 ALIGN_VCENTRE | ALIGN_HCENTRE,
1742 flags & USER_COL ? COL_USER : COL_CLUE,
1747 * Draw bold lines around the borders.
1749 if (flags & BORDER_L)
1751 BORDER + x*TILE_SIZE + 1,
1752 BORDER + y*TILE_SIZE + 1,
1756 if (flags & BORDER_U)
1758 BORDER + x*TILE_SIZE + 1,
1759 BORDER + y*TILE_SIZE + 1,
1763 if (flags & BORDER_R)
1765 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1766 BORDER + y*TILE_SIZE + 1,
1770 if (flags & BORDER_D)
1772 BORDER + x*TILE_SIZE + 1,
1773 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1777 if (flags & BORDER_UL)
1779 BORDER + x*TILE_SIZE + 1,
1780 BORDER + y*TILE_SIZE + 1,
1784 if (flags & BORDER_UR)
1786 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1787 BORDER + y*TILE_SIZE + 1,
1791 if (flags & BORDER_DL)
1793 BORDER + x*TILE_SIZE + 1,
1794 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1798 if (flags & BORDER_DR)
1800 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1801 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1806 if (flags & CURSOR_SQ) {
1807 int coff = TILE_SIZE/8;
1808 draw_rect_outline(dr,
1809 BORDER + x*TILE_SIZE + coff,
1810 BORDER + y*TILE_SIZE + coff,
1819 BORDER + x*TILE_SIZE,
1820 BORDER + y*TILE_SIZE,
1825 static void draw_grid(drawing *dr, game_drawstate *ds, const game_state *state,
1826 const game_ui *ui, int flashy, int borders, int shading)
1828 const int w = state->shared->params.w;
1829 const int h = state->shared->params.h;
1834 * Build a dsf for the board in its current state, to use for
1835 * highlights and hints.
1837 ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
1840 * Work out where we're putting borders between the cells.
1842 for (y = 0; y < w*h; y++)
1843 ds->border_scratch[y] = 0;
1845 for (y = 0; y < h; y++)
1846 for (x = 0; x < w; x++) {
1850 for (dx = 0; dx <= 1; dx++) {
1855 if (x+dx >= w || y+dy >= h)
1858 v1 = state->board[y*w+x];
1859 v2 = state->board[(y+dy)*w+(x+dx)];
1860 s1 = dsf_size(ds->dsf_scratch, y*w+x);
1861 s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
1864 * We only ever draw a border between two cells if
1865 * they don't have the same contents.
1869 * But in that situation, we don't always draw
1870 * a border. We do if the two cells both
1871 * contain actual numbers...
1877 * ... or if at least one of them is a
1878 * completed or overfull omino.
1887 ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
1892 * Actually do the drawing.
1894 for (y = 0; y < h; ++y)
1895 for (x = 0; x < w; ++x) {
1897 * Determine what we need to draw in this square.
1899 int i = y*w+x, v = state->board[i];
1902 if (flashy || !shading) {
1903 /* clear all background flags */
1904 } else if (ui && ui->sel && ui->sel[i]) {
1907 int size = dsf_size(ds->dsf_scratch, i);
1909 flags |= CORRECT_BG;
1913 int rt = dsf_canonify(ds->dsf_scratch, i), j;
1914 for (j = 0; j < w*h; ++j) {
1916 if (dsf_canonify(ds->dsf_scratch, j) != rt) continue;
1917 for (k = 0; k < 4; ++k) {
1918 const int xx = j % w + dx[k], yy = j / w + dy[k];
1919 if (xx >= 0 && xx < w && yy >= 0 && yy < h &&
1920 state->board[yy*w + xx] == EMPTY)
1929 if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
1933 * Borders at the very edges of the grid are
1934 * independent of the `borders' flag.
1946 if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
1948 if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
1950 if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
1952 if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
1955 if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
1957 if (y > 0 && x < w-1 &&
1958 ((ds->border_scratch[(y-1)*w+x] & 1) ||
1959 (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
1961 if (y < h-1 && x > 0 &&
1962 ((ds->border_scratch[y*w+(x-1)] & 2) ||
1963 (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
1965 if (y < h-1 && x < w-1 &&
1966 ((ds->border_scratch[y*w+(x+1)] & 2) ||
1967 (ds->border_scratch[(y+1)*w+x] & 1)))
1971 if (!state->shared->clues[y*w+x])
1974 if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
1975 draw_square(dr, ds, x, y, v, flags);
1977 ds->flags[y*w+x] = flags;
1982 static void game_redraw(drawing *dr, game_drawstate *ds,
1983 const game_state *oldstate, const game_state *state,
1984 int dir, const game_ui *ui,
1985 float animtime, float flashtime)
1987 const int w = state->shared->params.w;
1988 const int h = state->shared->params.h;
1992 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
1996 * The initial contents of the window are not guaranteed and
1997 * can vary with front ends. To be on the safe side, all games
1998 * should start by drawing a big background-colour rectangle
1999 * covering the whole window.
2001 draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
2005 * Smaller black rectangle which is the main grid.
2007 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
2008 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
2009 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
2012 draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
2017 draw_grid(dr, ds, state, ui, flashy, TRUE, TRUE);
2020 static float game_anim_length(const game_state *oldstate,
2021 const game_state *newstate, int dir, game_ui *ui)
2026 static float game_flash_length(const game_state *oldstate,
2027 const game_state *newstate, int dir, game_ui *ui)
2031 assert(newstate->shared);
2032 assert(oldstate->shared == newstate->shared);
2033 if (!oldstate->completed && newstate->completed &&
2034 !oldstate->cheated && !newstate->cheated)
2039 static int game_status(const game_state *state)
2041 return state->completed ? +1 : 0;
2044 static int game_timing_state(const game_state *state, game_ui *ui)
2049 static void game_print_size(const game_params *params, float *x, float *y)
2054 * I'll use 6mm squares by default.
2056 game_compute_size(params, 600, &pw, &ph);
2061 static void game_print(drawing *dr, const game_state *state, int tilesize)
2063 const int w = state->shared->params.w;
2064 const int h = state->shared->params.h;
2067 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2068 game_drawstate *ds = game_new_drawstate(dr, state);
2069 game_set_size(dr, ds, NULL, tilesize);
2071 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
2072 c = print_mono_colour(dr, 0); assert(c == COL_GRID);
2073 c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
2074 c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
2075 c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
2076 c = print_mono_colour(dr, 0); assert(c == COL_USER);
2081 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
2082 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
2083 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
2087 * We'll draw borders between the ominoes iff the grid is not
2088 * pristine. So scan it to see if it is.
2091 for (i = 0; i < w*h; i++)
2092 if (state->board[i] && !state->shared->clues[i])
2098 print_line_width(dr, TILE_SIZE / 64);
2099 draw_grid(dr, ds, state, NULL, FALSE, borders, FALSE);
2104 game_free_drawstate(dr, ds);
2108 #define thegame filling
2111 const struct game thegame = {
2112 "Filling", "games.filling", "filling",
2114 game_fetch_preset, NULL,
2119 TRUE, game_configure, custom_params,
2127 TRUE, game_can_format_as_text_now, game_text_format,
2135 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2138 game_free_drawstate,
2143 TRUE, FALSE, game_print_size, game_print,
2144 FALSE, /* wants_statusbar */
2145 FALSE, game_timing_state,
2146 REQUIRE_NUMPAD, /* flags */
2149 #ifdef STANDALONE_SOLVER /* solver? hah! */
2151 int main(int argc, char **argv) {
2153 game_params *params;
2158 for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
2159 if (*desc == '\0') {
2160 fprintf(stderr, "bad puzzle id: %s", par);
2166 params = snew(game_params);
2167 decode_params(params, par);
2168 state = new_game(NULL, params, desc);
2169 if (solver(state->board, params->w, params->h, NULL))
2170 printf("%s:%s: solvable\n", par, desc);
2172 printf("%s:%s: not solvable\n", par, desc);
2179 /* vim: set shiftwidth=4 tabstop=8: */