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 * - make a somewhat more clever solver
15 * + enable "ghost regions" of size > 1
16 * - one can put an upper bound on the size of a ghost region
17 * by considering the board size and summing present hints.
18 * + for each square, for i=1..n, what is the distance to a region
19 * containing i? How full is the region? How is this useful?
21 * - in board generation, after having merged regions such that no
22 * more merges are necessary, try splitting (big) regions.
23 * + it seems that smaller regions make for better puzzles; see
24 * for instance the 7x7 puzzle in this file (grep for 7x7:).
26 * - symmetric hints (solo-style)
27 * + right now that means including _many_ hints, and the puzzles
28 * won't look any nicer. Not worth it (at the moment).
30 * - make the solver do recursion/backtracking.
31 * + This is for user-submitted puzzles, not for puzzle
32 * generation (on the other hand, never say never).
34 * - prove that only w=h=2 needs a special case
36 * - solo-like pencil marks?
38 * - a user says that the difficulty is unevenly distributed.
39 * + partition into levels? Will they be non-crap?
41 * - Allow square contents > 9?
42 * + I could use letters for digits (solo does this), but
43 * letters don't have numeric significance (normal people hate
44 * base36), which is relevant here (much more than in solo).
45 * + [click, 1, 0, enter] => [10 in clicked square]?
46 * + How much information is needed to solve? Does one need to
47 * know the algorithm by which the largest number is set?
49 * - eliminate puzzle instances with done chunks (1's in particular)?
50 * + that's what the qsort call is all about.
51 * + the 1's don't bother me that much.
52 * + but this takes a LONG time (not always possible)?
53 * - this may be affected by solver (lack of) quality.
54 * - weed them out by construction instead of post-cons check
55 * + but that interleaves make_board and new_game_desc: you
56 * have to alternate between changing the board and
57 * changing the hint set (instead of just creating the
58 * board once, then changing the hint set once -> done).
60 * - use binary search when discovering the minimal sovable point
61 * + profile to show a need (but when the solver gets slower...)
62 * + 7x9 @ .011s, 9x13 @ .075s, 17x13 @ .661s (all avg with n=100)
63 * + but the hints are independent, not linear, so... what?
76 static unsigned char verbose;
78 static void printv(char *fmt, ...) {
89 /*****************************************************************************
90 * GAME CONFIGURATION AND PARAMETERS *
91 *****************************************************************************/
98 struct game_params params;
105 struct shared_state *shared;
106 int completed, cheated;
109 static const struct game_params filling_defaults[3] = {{7, 9}, {9, 13}, {13, 17}};
111 static game_params *default_params(void)
113 game_params *ret = snew(game_params);
115 *ret = filling_defaults[1]; /* struct copy */
120 static int game_fetch_preset(int i, char **name, game_params **params)
124 if (i < 0 || i >= lenof(filling_defaults)) return FALSE;
125 *params = snew(game_params);
126 **params = filling_defaults[i]; /* struct copy */
127 sprintf(buf, "%dx%d", filling_defaults[i].h, filling_defaults[i].w);
133 static void free_params(game_params *params)
138 static game_params *dup_params(const game_params *params)
140 game_params *ret = snew(game_params);
141 *ret = *params; /* struct copy */
145 static void decode_params(game_params *ret, char const *string)
147 ret->w = ret->h = atoi(string);
148 while (*string && isdigit((unsigned char) *string)) ++string;
149 if (*string == 'x') ret->h = atoi(++string);
152 static char *encode_params(const game_params *params, int full)
155 sprintf(buf, "%dx%d", params->w, params->h);
159 static config_item *game_configure(const game_params *params)
164 ret = snewn(3, config_item);
166 ret[0].name = "Width";
167 ret[0].type = C_STRING;
168 sprintf(buf, "%d", params->w);
169 ret[0].sval = dupstr(buf);
172 ret[1].name = "Height";
173 ret[1].type = C_STRING;
174 sprintf(buf, "%d", params->h);
175 ret[1].sval = dupstr(buf);
186 static game_params *custom_params(const config_item *cfg)
188 game_params *ret = snew(game_params);
190 ret->w = atoi(cfg[0].sval);
191 ret->h = atoi(cfg[1].sval);
196 static char *validate_params(const game_params *params, int full)
198 if (params->w < 1) return "Width must be at least one";
199 if (params->h < 1) return "Height must be at least one";
204 /*****************************************************************************
205 * STRINGIFICATION OF GAME STATE *
206 *****************************************************************************/
210 /* Example of plaintext rendering:
211 * +---+---+---+---+---+---+---+
212 * | 6 | | | 2 | | | 2 |
213 * +---+---+---+---+---+---+---+
214 * | | 3 | | 6 | | 3 | |
215 * +---+---+---+---+---+---+---+
216 * | 3 | | | | | | 1 |
217 * +---+---+---+---+---+---+---+
218 * | | 2 | 3 | | 4 | 2 | |
219 * +---+---+---+---+---+---+---+
220 * | 2 | | | | | | 3 |
221 * +---+---+---+---+---+---+---+
222 * | | 5 | | 1 | | 4 | |
223 * +---+---+---+---+---+---+---+
224 * | 4 | | | 3 | | | 3 |
225 * +---+---+---+---+---+---+---+
227 * This puzzle instance is taken from the nikoli website
228 * Encoded (unsolved and solved), the strings are these:
229 * 7x7:6002002030603030000010230420200000305010404003003
230 * 7x7:6662232336663232331311235422255544325413434443313
232 static char *board_to_string(int *board, int w, int h) {
233 const int sz = w * h;
234 const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
235 const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
236 const int chlen = chw * chh;
237 char *repr = snewn(chlen + 1, char);
242 /* build the first line ("^(\+---){n}\+$") */
243 for (i = 0; i < w; ++i) {
250 repr[4*i + 1] = '\n';
252 /* ... and copy it onto the odd-numbered lines */
253 for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
255 /* build the second line ("^(\|\t){n}\|$") */
256 for (i = 0; i < w; ++i) {
257 repr[chw + 4*i + 0] = '|';
258 repr[chw + 4*i + 1] = ' ';
259 repr[chw + 4*i + 2] = ' ';
260 repr[chw + 4*i + 3] = ' ';
262 repr[chw + 4*i + 0] = '|';
263 repr[chw + 4*i + 1] = '\n';
265 /* ... and copy it onto the even-numbered lines */
266 for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
268 /* fill in the numbers */
269 for (i = 0; i < sz; ++i) {
272 if (board[i] == EMPTY) continue;
273 repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
280 static int game_can_format_as_text_now(const game_params *params)
285 static char *game_text_format(const game_state *state)
287 const int w = state->shared->params.w;
288 const int h = state->shared->params.h;
289 return board_to_string(state->board, w, h);
292 /*****************************************************************************
293 * GAME GENERATION AND SOLVER *
294 *****************************************************************************/
296 static const int dx[4] = {-1, 1, 0, 0};
297 static const int dy[4] = {0, 0, -1, 1};
307 static void print_board(int *board, int w, int h) {
309 char *repr = board_to_string(board, w, h);
310 printv("%s\n", repr);
315 static game_state *new_game(midend *, const game_params *, const char *);
316 static void free_game(game_state *);
320 static int mark_region(int *board, int w, int h, int i, int n, int m) {
325 for (j = 0; j < 4; ++j) {
326 const int x = (i % w) + dx[j], y = (i / w) + dy[j], ii = w*y + x;
327 if (x < 0 || x >= w || y < 0 || y >= h) continue;
328 if (board[ii] == m) return FALSE;
329 if (board[ii] != n) continue;
330 if (!mark_region(board, w, h, ii, n, m)) return FALSE;
335 static int region_size(int *board, int w, int h, int i) {
336 const int sz = w * h;
338 if (board[i] == 0) return 0;
340 mark_region(board, w, h, i, board[i], SENTINEL);
341 for (size = j = 0; j < sz; ++j) {
342 if (board[j] != -1) continue;
349 static void merge_ones(int *board, int w, int h)
351 const int sz = w * h;
352 const int maxsize = min(max(max(w, h), 3), 9);
356 for (i = 0; i < sz; ++i) {
357 if (board[i] != 1) continue;
359 for (j = 0; j < 4; ++j, board[i] = 1) {
360 const int x = (i % w) + dx[j], y = (i / w) + dy[j];
361 int oldsize, newsize, ok, ii = w*y + x;
362 if (x < 0 || x >= w || y < 0 || y >= h) continue;
363 if (board[ii] == maxsize) continue;
367 newsize = region_size(board, w, h, i);
369 if (newsize > maxsize) continue;
371 ok = mark_region(board, w, h, i, oldsize, newsize);
373 for (k = 0; k < sz; ++k)
375 board[k] = ok ? newsize : oldsize;
379 if (j < 4) change = TRUE;
384 /* generate a random valid board; uses validate_board. */
385 static void make_board(int *board, int w, int h, random_state *rs) {
386 const int sz = w * h;
388 /* w=h=2 is a special case which requires a number > max(w, h) */
389 /* TODO prove that this is the case ONLY for w=h=2. */
390 const int maxsize = min(max(max(w, h), 3), 9);
392 /* Note that if 1 in {w, h} then it's impossible to have a region
393 * of size > w*h, so the special case only affects w=h=2. */
401 /* I abuse the board variable: when generating the puzzle, it
402 * contains a shuffled list of numbers {0, ..., sz-1}. */
403 for (i = 0; i < sz; ++i) board[i] = i;
405 dsf = snewn(sz, int);
408 shuffle(board, sz, sizeof (int), rs);
411 change = FALSE; /* as long as the board potentially has errors */
412 for (i = 0; i < sz; ++i) {
413 const int square = dsf_canonify(dsf, board[i]);
414 const int size = dsf_size(dsf, square);
415 int merge = SENTINEL, min = maxsize - size + 1, error = FALSE;
416 int neighbour, neighbour_size, j;
418 for (j = 0; j < 4; ++j) {
419 const int x = (board[i] % w) + dx[j];
420 const int y = (board[i] / w) + dy[j];
421 if (x < 0 || x >= w || y < 0 || y >= h) continue;
423 neighbour = dsf_canonify(dsf, w*y + x);
424 if (square == neighbour) continue;
426 neighbour_size = dsf_size(dsf, neighbour);
427 if (size == neighbour_size) error = TRUE;
429 /* find the smallest neighbour to merge with, which
430 * wouldn't make the region too large. (This is
431 * guaranteed by the initial value of `min'.) */
432 if (neighbour_size < min) {
433 min = neighbour_size;
438 /* if this square is not in error, leave it be */
439 if (!error) continue;
441 /* if it is, but we can't fix it, retry the whole board.
442 * Maybe we could fix it by merging the conflicting
443 * neighbouring region(s) into some of their neighbours,
444 * but just restarting works out fine. */
445 if (merge == SENTINEL) goto retry;
447 /* merge with the smallest neighbouring workable region. */
448 dsf_merge(dsf, square, merge);
453 for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
454 merge_ones(board, w, h);
459 static void merge(int *dsf, int *connected, int a, int b) {
463 a = dsf_canonify(dsf, a);
464 b = dsf_canonify(dsf, b);
466 dsf_merge(dsf, a, b);
468 connected[a] = connected[b];
472 static void *memdup(const void *ptr, size_t len, size_t esz) {
473 void *dup = smalloc(len * esz);
475 memcpy(dup, ptr, len * esz);
479 static void expand(struct solver_state *s, int w, int h, int t, int f) {
482 assert(s->board[t] == EMPTY); /* expand to empty square */
483 assert(s->board[f] != EMPTY); /* expand from non-empty square */
485 "learn: expanding %d from (%d, %d) into (%d, %d)\n",
486 s->board[f], f % w, f / w, t % w, t / w);
487 s->board[t] = s->board[f];
488 for (j = 0; j < 4; ++j) {
489 const int x = (t % w) + dx[j];
490 const int y = (t / w) + dy[j];
491 const int idx = w*y + x;
492 if (x < 0 || x >= w || y < 0 || y >= h) continue;
493 if (s->board[idx] != s->board[t]) continue;
494 merge(s->dsf, s->connected, t, idx);
499 static void clear_count(int *board, int sz) {
501 for (i = 0; i < sz; ++i) {
502 if (board[i] >= 0) continue;
503 else if (board[i] == -SENTINEL) board[i] = EMPTY;
504 else board[i] = -board[i];
508 static void flood_count(int *board, int w, int h, int i, int n, int *c) {
509 const int sz = w * h;
512 if (board[i] == EMPTY) board[i] = -SENTINEL;
513 else if (board[i] == n) board[i] = -board[i];
516 if (--*c == 0) return;
518 for (k = 0; k < 4; ++k) {
519 const int x = (i % w) + dx[k];
520 const int y = (i / w) + dy[k];
521 const int idx = w*y + x;
522 if (x < 0 || x >= w || y < 0 || y >= h) continue;
523 flood_count(board, w, h, idx, n, c);
528 static int check_capacity(int *board, int w, int h, int i) {
530 flood_count(board, w, h, i, board[i], &n);
531 clear_count(board, w * h);
535 static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
540 for (j = 0; j < 4; ++j) {
541 const int x = (i % w) + dx[j];
542 const int y = (i / w) + dy[j];
543 const int idx = w*y + x;
546 if (x < 0 || x >= w || y < 0 || y >= h) continue;
547 if (board[idx] != n) continue;
548 root = dsf_canonify(dsf, idx);
549 for (m = 0; m < nhits && root != hits[m]; ++m);
550 if (m < nhits) continue;
551 printv("\t (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
552 size += dsf_size(dsf, root);
553 assert(dsf_size(dsf, root) >= 1);
554 hits[nhits++] = root;
560 * +---+---+---+---+---+---+---+
561 * | 6 | | | 2 | | | 2 |
562 * +---+---+---+---+---+---+---+
563 * | | 3 | | 6 | | 3 | |
564 * +---+---+---+---+---+---+---+
565 * | 3 | | | | | | 1 |
566 * +---+---+---+---+---+---+---+
567 * | | 2 | 3 | | 4 | 2 | |
568 * +---+---+---+---+---+---+---+
569 * | 2 | | | | | | 3 |
570 * +---+---+---+---+---+---+---+
571 * | | 5 | | 1 | | 4 | |
572 * +---+---+---+---+---+---+---+
573 * | 4 | | | 3 | | | 3 |
574 * +---+---+---+---+---+---+---+
577 /* Solving techniques:
579 * CONNECTED COMPONENT FORCED EXPANSION (too big):
580 * When a CC can only be expanded in one direction, because all the
581 * other ones would make the CC too big.
582 * +---+---+---+---+---+
583 * | 2 | 2 | | 2 | _ |
584 * +---+---+---+---+---+
586 * CONNECTED COMPONENT FORCED EXPANSION (too small):
587 * When a CC must include a particular square, because otherwise there
588 * would not be enough room to complete it. This includes squares not
589 * adjacent to the CC through learn_critical_square.
595 * When an empty square has no neighbouring empty squares and only a 1
596 * will go into the square (or other CCs would be too big).
601 * TODO: generalise DROPPING IN A ONE: find the size of the CC of
602 * empty squares and a list of all adjacent numbers. See if only one
603 * number in {1, ..., size} u {all adjacent numbers} is possible.
604 * Probably this is only effective for a CC size < n for some n (4?)
606 * TODO: backtracking.
609 static void filled_square(struct solver_state *s, int w, int h, int i) {
611 for (j = 0; j < 4; ++j) {
612 const int x = (i % w) + dx[j];
613 const int y = (i / w) + dy[j];
614 const int idx = w*y + x;
615 if (x < 0 || x >= w || y < 0 || y >= h) continue;
616 if (s->board[i] == s->board[idx])
617 merge(s->dsf, s->connected, i, idx);
621 static void init_solver_state(struct solver_state *s, int w, int h) {
622 const int sz = w * h;
627 for (i = 0; i < sz; ++i) s->connected[i] = i;
628 for (i = 0; i < sz; ++i)
629 if (s->board[i] == EMPTY) ++s->nempty;
630 else filled_square(s, w, h, i);
633 static int learn_expand_or_one(struct solver_state *s, int w, int h) {
634 const int sz = w * h;
640 for (i = 0; i < sz; ++i) {
644 if (s->board[i] != EMPTY) continue;
646 for (j = 0; j < 4; ++j) {
647 const int x = (i % w) + dx[j];
648 const int y = (i / w) + dy[j];
649 const int idx = w*y + x;
650 if (x < 0 || x >= w || y < 0 || y >= h) continue;
651 if (s->board[idx] == EMPTY) {
656 (s->board[idx] == 1 ||
657 (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
660 if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
661 assert(s->board[i] == EMPTY);
662 s->board[i] = -SENTINEL;
663 if (check_capacity(s->board, w, h, idx)) continue;
664 assert(s->board[i] == EMPTY);
665 printv("learn: expanding in one\n");
666 expand(s, w, h, i, idx);
672 printv("learn: one at (%d, %d)\n", i % w, i / w);
673 assert(s->board[i] == EMPTY);
683 static int learn_blocked_expansion(struct solver_state *s, int w, int h) {
684 const int sz = w * h;
689 /* for every connected component */
690 for (i = 0; i < sz; ++i) {
694 if (s->board[i] == EMPTY) continue;
695 j = dsf_canonify(s->dsf, i);
697 /* (but only for each connected component) */
698 if (i != j) continue;
700 /* (and not if it's already complete) */
701 if (dsf_size(s->dsf, j) == s->board[j]) continue;
703 /* for each square j _in_ the connected component */
706 printv(" looking at (%d, %d)\n", j % w, j / w);
708 /* for each neighbouring square (idx) */
709 for (k = 0; k < 4; ++k) {
710 const int x = (j % w) + dx[k];
711 const int y = (j / w) + dy[k];
712 const int idx = w*y + x;
717 if (x < 0 || x >= w || y < 0 || y >= h) continue;
718 if (s->board[idx] != EMPTY) continue;
719 if (exp == idx) continue;
720 printv("\ttrying to expand onto (%d, %d)\n", x, y);
722 /* find out the would-be size of the new connected
723 * component if we actually expanded into idx */
726 for (l = 0; l < 4; ++l) {
727 const int lx = x + dx[l];
728 const int ly = y + dy[l];
729 const int idxl = w*ly + lx;
732 if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
733 if (board[idxl] != board[j]) continue;
734 root = dsf_canonify(dsf, idxl);
735 for (m = 0; m < nhits && root != hits[m]; ++m);
736 if (m != nhits) continue;
737 // printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
738 size += dsf_size(dsf, root);
739 assert(dsf_size(dsf, root) >= 1);
740 hits[nhits++] = root;
744 size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
746 /* ... and see if that size is too big, or if we
747 * have other expansion candidates. Otherwise
748 * remember the (so far) only candidate. */
750 printv("\tthat would give a size of %d\n", size);
751 if (size > s->board[j]) continue;
752 /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
753 if (exp != SENTINEL) goto next_i;
758 j = s->connected[j]; /* next square in the same CC */
759 assert(s->board[i] == s->board[j]);
761 /* end: for each square j _in_ the connected component */
763 if (exp == SENTINEL) continue;
764 printv("learning to expand\n");
765 expand(s, w, h, exp, i);
771 /* end: for each connected component */
775 static int learn_critical_square(struct solver_state *s, int w, int h) {
776 const int sz = w * h;
781 /* for each connected component */
782 for (i = 0; i < sz; ++i) {
784 if (s->board[i] == EMPTY) continue;
785 if (i != dsf_canonify(s->dsf, i)) continue;
786 slack = s->board[i] - dsf_size(s->dsf, i);
787 if (slack == 0) continue;
788 assert(s->board[i] != 1);
789 /* for each empty square */
790 for (j = 0; j < sz; ++j) {
791 if (s->board[j] == EMPTY) {
792 /* if it's too far away from the CC, don't bother */
793 int k = i, jx = j % w, jy = j / w;
795 int kx = k % w, ky = k / w;
796 if (abs(kx - jx) + abs(ky - jy) <= slack) break;
799 if (i == k) continue; /* not within range */
801 s->board[j] = -SENTINEL;
802 if (check_capacity(s->board, w, h, i)) continue;
803 /* if not expanding s->board[i] to s->board[j] implies
804 * that s->board[i] can't reach its full size, ... */
807 "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
808 s->board[i], j % w, j / w, i % w, i / w);
810 s->board[j] = s->board[i];
811 filled_square(s, w, h, j);
818 static int solver(const int *orig, int w, int h, char **solution) {
819 const int sz = w * h;
821 struct solver_state ss;
822 ss.board = memdup(orig, sz, sizeof (int));
823 ss.dsf = snew_dsf(sz); /* eqv classes: connected components */
824 ss.connected = snewn(sz, int); /* connected[n] := n.next; */
825 /* cyclic disjoint singly linked lists, same partitioning as dsf.
826 * The lists lets you iterate over a partition given any member */
828 printv("trying to solve this:\n");
829 print_board(ss.board, w, h);
831 init_solver_state(&ss, w, h);
833 if (learn_blocked_expansion(&ss, w, h)) continue;
834 if (learn_expand_or_one(&ss, w, h)) continue;
835 if (learn_critical_square(&ss, w, h)) continue;
839 printv("best guess:\n");
840 print_board(ss.board, w, h);
844 *solution = snewn(sz + 2, char);
846 for (i = 0; i < sz; ++i) (*solution)[i + 1] = ss.board[i] + '0';
847 (*solution)[sz + 1] = '\0';
848 /* We don't need the \0 for execute_move (the only user)
849 * I'm just being printf-friendly in case I wanna print */
859 static int *make_dsf(int *dsf, int *board, const int w, const int h) {
860 const int sz = w * h;
864 dsf = snew_dsf(w * h);
866 dsf_init(dsf, w * h);
868 for (i = 0; i < sz; ++i) {
870 for (j = 0; j < 4; ++j) {
871 const int x = (i % w) + dx[j];
872 const int y = (i / w) + dy[j];
873 const int k = w*y + x;
874 if (x < 0 || x >= w || y < 0 || y >= h) continue;
875 if (board[i] == board[k]) dsf_merge(dsf, i, k);
881 static void minimize_clue_set(int *board, int w, int h, random_state *rs)
883 const int sz = w * h;
884 int *shuf = snewn(sz, int), i;
886 for (i = 0; i < sz; ++i) shuf[i] = i;
887 shuffle(shuf, sz, sizeof (int), rs);
889 /* the solver is monotone, so a second pass is superfluous. */
890 for (i = 0; i < sz; ++i) {
891 int tmp = board[shuf[i]];
892 board[shuf[i]] = EMPTY;
893 if (!solver(board, w, h, NULL)) board[shuf[i]] = tmp;
899 static char *new_game_desc(const game_params *params, random_state *rs,
900 char **aux, int interactive)
902 const int w = params->w, h = params->h, sz = w * h;
903 int *board = snewn(sz, int), i;
904 char *game_description = snewn(sz + 1, char);
906 make_board(board, w, h, rs);
907 minimize_clue_set(board, w, h, rs);
909 for (i = 0; i < sz; ++i) {
910 assert(board[i] >= 0);
911 assert(board[i] < 10);
912 game_description[i] = board[i] + '0';
914 game_description[sz] = '\0';
918 return game_description;
921 static char *validate_desc(const game_params *params, const char *desc)
924 const int sz = params->w * params->h;
925 const char m = '0' + max(max(params->w, params->h), 3);
927 printv("desc = '%s'; sz = %d\n", desc, sz);
929 for (i = 0; desc[i] && i < sz; ++i)
930 if (!isdigit((unsigned char) *desc))
931 return "non-digit in string";
932 else if (desc[i] > m)
933 return "too large digit in string";
934 if (desc[i]) return "string too long";
935 else if (i < sz) return "string too short";
939 static game_state *new_game(midend *me, const game_params *params,
942 game_state *state = snew(game_state);
943 int sz = params->w * params->h;
946 state->cheated = state->completed = FALSE;
947 state->shared = snew(struct shared_state);
948 state->shared->refcnt = 1;
949 state->shared->params = *params; /* struct copy */
950 state->shared->clues = snewn(sz, int);
951 for (i = 0; i < sz; ++i) state->shared->clues[i] = desc[i] - '0';
952 state->board = memdup(state->shared->clues, sz, sizeof (int));
957 static game_state *dup_game(const game_state *state)
959 const int sz = state->shared->params.w * state->shared->params.h;
960 game_state *ret = snew(game_state);
962 ret->board = memdup(state->board, sz, sizeof (int));
963 ret->shared = state->shared;
964 ret->cheated = state->cheated;
965 ret->completed = state->completed;
966 ++ret->shared->refcnt;
971 static void free_game(game_state *state)
975 if (--state->shared->refcnt == 0) {
976 sfree(state->shared->clues);
977 sfree(state->shared);
982 static char *solve_game(const game_state *state, const game_state *currstate,
983 const char *aux, char **error)
986 const int w = state->shared->params.w;
987 const int h = state->shared->params.h;
989 if (!solver(state->board, w, h, &new_aux))
990 *error = "Sorry, I couldn't find a solution";
996 /*****************************************************************************
997 * USER INTERFACE STATE AND ACTION *
998 *****************************************************************************/
1001 int *sel; /* w*h highlighted squares, or NULL */
1002 int cur_x, cur_y, cur_visible, keydragging;
1005 static game_ui *new_ui(const game_state *state)
1007 game_ui *ui = snew(game_ui);
1010 ui->cur_x = ui->cur_y = ui->cur_visible = ui->keydragging = 0;
1015 static void free_ui(game_ui *ui)
1022 static char *encode_ui(const game_ui *ui)
1027 static void decode_ui(game_ui *ui, const char *encoding)
1031 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1032 const game_state *newstate)
1034 /* Clear any selection */
1039 ui->keydragging = FALSE;
1042 #define PREFERRED_TILE_SIZE 32
1043 #define TILE_SIZE (ds->tilesize)
1044 #define BORDER (TILE_SIZE / 2)
1045 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1047 struct game_drawstate {
1048 struct game_params params;
1052 int *dsf_scratch, *border_scratch;
1055 static char *interpret_move(const game_state *state, game_ui *ui,
1056 const game_drawstate *ds,
1057 int x, int y, int button)
1059 const int w = state->shared->params.w;
1060 const int h = state->shared->params.h;
1062 const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1063 const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1071 button &= ~MOD_MASK;
1073 if (button == LEFT_BUTTON || button == LEFT_DRAG) {
1074 /* A left-click anywhere will clear the current selection. */
1075 if (button == LEFT_BUTTON) {
1081 if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
1083 ui->sel = snewn(w*h, int);
1084 memset(ui->sel, 0, w*h*sizeof(int));
1086 if (!state->shared->clues[w*ty+tx])
1087 ui->sel[w*ty+tx] = 1;
1089 ui->cur_visible = 0;
1090 return ""; /* redraw */
1093 if (IS_CURSOR_MOVE(button)) {
1094 ui->cur_visible = 1;
1095 move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, 0);
1096 if (ui->keydragging) goto select_square;
1099 if (button == CURSOR_SELECT) {
1100 if (!ui->cur_visible) {
1101 ui->cur_visible = 1;
1104 ui->keydragging = !ui->keydragging;
1105 if (!ui->keydragging) return "";
1109 ui->sel = snewn(w*h, int);
1110 memset(ui->sel, 0, w*h*sizeof(int));
1112 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1113 ui->sel[w*ui->cur_y + ui->cur_x] = 1;
1116 if (button == CURSOR_SELECT2) {
1117 if (!ui->cur_visible) {
1118 ui->cur_visible = 1;
1122 ui->sel = snewn(w*h, int);
1123 memset(ui->sel, 0, w*h*sizeof(int));
1125 ui->keydragging = FALSE;
1126 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1127 ui->sel[w*ui->cur_y + ui->cur_x] ^= 1;
1128 for (i = 0; i < w*h && !ui->sel[i]; i++);
1136 if (button == '\b' || button == 27) {
1139 ui->keydragging = FALSE;
1143 if (button < '0' || button > '9') return NULL;
1145 if (button > (w == 2 && h == 2 ? 3 : max(w, h))) return NULL;
1146 ui->keydragging = FALSE;
1148 for (i = 0; i < w*h; i++) {
1150 if ((ui->sel && ui->sel[i]) ||
1151 (!ui->sel && ui->cur_visible && (w*ui->cur_y+ui->cur_x) == i)) {
1152 if (state->shared->clues[i] != 0) continue; /* in case cursor is on clue */
1153 if (state->board[i] != button) {
1154 sprintf(buf, "%s%d", move ? "," : "", i);
1156 move = srealloc(move, strlen(move)+strlen(buf)+1);
1159 move = smalloc(strlen(buf)+1);
1167 sprintf(buf, "_%d", button);
1168 move = srealloc(move, strlen(move)+strlen(buf)+1);
1171 if (!ui->sel) return move ? move : NULL;
1174 /* Need to update UI at least, as we cleared the selection */
1175 return move ? move : "";
1178 static game_state *execute_move(const game_state *state, const char *move)
1180 game_state *new_state = NULL;
1181 const int sz = state->shared->params.w * state->shared->params.h;
1185 new_state = dup_game(state);
1186 for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
1187 new_state->cheated = TRUE;
1190 char *endptr, *delim = strchr(move, '_');
1191 if (!delim) goto err;
1192 value = strtol(delim+1, &endptr, 0);
1193 if (*endptr || endptr == delim+1) goto err;
1194 if (value < 0 || value > 9) goto err;
1195 new_state = dup_game(state);
1197 const int i = strtol(move, &endptr, 0);
1198 if (endptr == move) goto err;
1199 if (i < 0 || i >= sz) goto err;
1200 new_state->board[i] = value;
1201 if (*endptr == '_') break;
1202 if (*endptr != ',') goto err;
1208 * Check for completion.
1210 if (!new_state->completed) {
1211 const int w = new_state->shared->params.w;
1212 const int h = new_state->shared->params.h;
1213 const int sz = w * h;
1214 int *dsf = make_dsf(NULL, new_state->board, w, h);
1216 for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
1219 new_state->completed = TRUE;
1225 if (new_state) free_game(new_state);
1229 /* ----------------------------------------------------------------------
1233 #define FLASH_TIME 0.4F
1235 #define COL_CLUE COL_GRID
1247 static void game_compute_size(const game_params *params, int tilesize,
1250 *x = (params->w + 1) * tilesize;
1251 *y = (params->h + 1) * tilesize;
1254 static void game_set_size(drawing *dr, game_drawstate *ds,
1255 const game_params *params, int tilesize)
1257 ds->tilesize = tilesize;
1260 static float *game_colours(frontend *fe, int *ncolours)
1262 float *ret = snewn(3 * NCOLOURS, float);
1264 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1266 ret[COL_GRID * 3 + 0] = 0.0F;
1267 ret[COL_GRID * 3 + 1] = 0.0F;
1268 ret[COL_GRID * 3 + 2] = 0.0F;
1270 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1271 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1272 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1274 ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
1275 ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
1276 ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
1278 ret[COL_CURSOR * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1279 ret[COL_CURSOR * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1280 ret[COL_CURSOR * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1282 ret[COL_ERROR * 3 + 0] = 1.0F;
1283 ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1284 ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1286 ret[COL_USER * 3 + 0] = 0.0F;
1287 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1288 ret[COL_USER * 3 + 2] = 0.0F;
1290 *ncolours = NCOLOURS;
1294 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1296 struct game_drawstate *ds = snew(struct game_drawstate);
1299 ds->tilesize = PREFERRED_TILE_SIZE;
1301 ds->params = state->shared->params;
1302 ds->v = snewn(ds->params.w * ds->params.h, int);
1303 ds->flags = snewn(ds->params.w * ds->params.h, int);
1304 for (i = 0; i < ds->params.w * ds->params.h; i++)
1305 ds->v[i] = ds->flags[i] = -1;
1306 ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
1307 ds->dsf_scratch = NULL;
1312 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1316 sfree(ds->border_scratch);
1317 sfree(ds->dsf_scratch);
1321 #define BORDER_U 0x001
1322 #define BORDER_D 0x002
1323 #define BORDER_L 0x004
1324 #define BORDER_R 0x008
1325 #define BORDER_UR 0x010
1326 #define BORDER_DR 0x020
1327 #define BORDER_UL 0x040
1328 #define BORDER_DL 0x080
1329 #define HIGH_BG 0x100
1330 #define CORRECT_BG 0x200
1331 #define ERROR_BG 0x400
1332 #define USER_COL 0x800
1333 #define CURSOR_SQ 0x1000
1335 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
1342 * Clip to the grid square.
1344 clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1345 TILE_SIZE, TILE_SIZE);
1351 BORDER + x*TILE_SIZE,
1352 BORDER + y*TILE_SIZE,
1355 (flags & HIGH_BG ? COL_HIGHLIGHT :
1356 flags & ERROR_BG ? COL_ERROR :
1357 flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
1360 * Draw the grid lines.
1362 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1363 BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
1364 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1365 BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
1375 (x + 1) * TILE_SIZE,
1376 (y + 1) * TILE_SIZE,
1379 ALIGN_VCENTRE | ALIGN_HCENTRE,
1380 flags & USER_COL ? COL_USER : COL_CLUE,
1385 * Draw bold lines around the borders.
1387 if (flags & BORDER_L)
1389 BORDER + x*TILE_SIZE + 1,
1390 BORDER + y*TILE_SIZE + 1,
1394 if (flags & BORDER_U)
1396 BORDER + x*TILE_SIZE + 1,
1397 BORDER + y*TILE_SIZE + 1,
1401 if (flags & BORDER_R)
1403 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1404 BORDER + y*TILE_SIZE + 1,
1408 if (flags & BORDER_D)
1410 BORDER + x*TILE_SIZE + 1,
1411 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1415 if (flags & BORDER_UL)
1417 BORDER + x*TILE_SIZE + 1,
1418 BORDER + y*TILE_SIZE + 1,
1422 if (flags & BORDER_UR)
1424 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1425 BORDER + y*TILE_SIZE + 1,
1429 if (flags & BORDER_DL)
1431 BORDER + x*TILE_SIZE + 1,
1432 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1436 if (flags & BORDER_DR)
1438 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1439 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1444 if (flags & CURSOR_SQ) {
1445 int coff = TILE_SIZE/8;
1446 draw_rect_outline(dr,
1447 BORDER + x*TILE_SIZE + coff,
1448 BORDER + y*TILE_SIZE + coff,
1457 BORDER + x*TILE_SIZE,
1458 BORDER + y*TILE_SIZE,
1463 static void draw_grid(drawing *dr, game_drawstate *ds, const game_state *state,
1464 const game_ui *ui, int flashy, int borders, int shading)
1466 const int w = state->shared->params.w;
1467 const int h = state->shared->params.h;
1472 * Build a dsf for the board in its current state, to use for
1473 * highlights and hints.
1475 ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
1478 * Work out where we're putting borders between the cells.
1480 for (y = 0; y < w*h; y++)
1481 ds->border_scratch[y] = 0;
1483 for (y = 0; y < h; y++)
1484 for (x = 0; x < w; x++) {
1488 for (dx = 0; dx <= 1; dx++) {
1493 if (x+dx >= w || y+dy >= h)
1496 v1 = state->board[y*w+x];
1497 v2 = state->board[(y+dy)*w+(x+dx)];
1498 s1 = dsf_size(ds->dsf_scratch, y*w+x);
1499 s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
1502 * We only ever draw a border between two cells if
1503 * they don't have the same contents.
1507 * But in that situation, we don't always draw
1508 * a border. We do if the two cells both
1509 * contain actual numbers...
1515 * ... or if at least one of them is a
1516 * completed or overfull omino.
1525 ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
1530 * Actually do the drawing.
1532 for (y = 0; y < h; ++y)
1533 for (x = 0; x < w; ++x) {
1535 * Determine what we need to draw in this square.
1537 int i = y*w+x, v = state->board[i];
1540 if (flashy || !shading) {
1541 /* clear all background flags */
1542 } else if (ui && ui->sel && ui->sel[i]) {
1545 int size = dsf_size(ds->dsf_scratch, i);
1547 flags |= CORRECT_BG;
1551 int rt = dsf_canonify(ds->dsf_scratch, i), j;
1552 for (j = 0; j < w*h; ++j) {
1554 if (dsf_canonify(ds->dsf_scratch, j) != rt) continue;
1555 for (k = 0; k < 4; ++k) {
1556 const int xx = j % w + dx[k], yy = j / w + dy[k];
1557 if (xx >= 0 && xx < w && yy >= 0 && yy < h &&
1558 state->board[yy*w + xx] == EMPTY)
1567 if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
1571 * Borders at the very edges of the grid are
1572 * independent of the `borders' flag.
1584 if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
1586 if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
1588 if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
1590 if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
1593 if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
1595 if (y > 0 && x < w-1 &&
1596 ((ds->border_scratch[(y-1)*w+x] & 1) ||
1597 (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
1599 if (y < h-1 && x > 0 &&
1600 ((ds->border_scratch[y*w+(x-1)] & 2) ||
1601 (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
1603 if (y < h-1 && x < w-1 &&
1604 ((ds->border_scratch[y*w+(x+1)] & 2) ||
1605 (ds->border_scratch[(y+1)*w+x] & 1)))
1609 if (!state->shared->clues[y*w+x])
1612 if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
1613 draw_square(dr, ds, x, y, v, flags);
1615 ds->flags[y*w+x] = flags;
1620 static void game_redraw(drawing *dr, game_drawstate *ds,
1621 const game_state *oldstate, const game_state *state,
1622 int dir, const game_ui *ui,
1623 float animtime, float flashtime)
1625 const int w = state->shared->params.w;
1626 const int h = state->shared->params.h;
1630 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
1634 * The initial contents of the window are not guaranteed and
1635 * can vary with front ends. To be on the safe side, all games
1636 * should start by drawing a big background-colour rectangle
1637 * covering the whole window.
1639 draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
1643 * Smaller black rectangle which is the main grid.
1645 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1646 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1647 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1650 draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
1655 draw_grid(dr, ds, state, ui, flashy, TRUE, TRUE);
1658 static float game_anim_length(const game_state *oldstate,
1659 const game_state *newstate, int dir, game_ui *ui)
1664 static float game_flash_length(const game_state *oldstate,
1665 const game_state *newstate, int dir, game_ui *ui)
1669 assert(newstate->shared);
1670 assert(oldstate->shared == newstate->shared);
1671 if (!oldstate->completed && newstate->completed &&
1672 !oldstate->cheated && !newstate->cheated)
1677 static int game_status(const game_state *state)
1679 return state->completed ? +1 : 0;
1682 static int game_timing_state(const game_state *state, game_ui *ui)
1687 static void game_print_size(const game_params *params, float *x, float *y)
1692 * I'll use 6mm squares by default.
1694 game_compute_size(params, 600, &pw, &ph);
1699 static void game_print(drawing *dr, const game_state *state, int tilesize)
1701 const int w = state->shared->params.w;
1702 const int h = state->shared->params.h;
1705 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1706 game_drawstate *ds = game_new_drawstate(dr, state);
1707 game_set_size(dr, ds, NULL, tilesize);
1709 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1710 c = print_mono_colour(dr, 0); assert(c == COL_GRID);
1711 c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
1712 c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
1713 c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
1714 c = print_mono_colour(dr, 0); assert(c == COL_USER);
1719 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1720 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1721 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1725 * We'll draw borders between the ominoes iff the grid is not
1726 * pristine. So scan it to see if it is.
1729 for (i = 0; i < w*h; i++)
1730 if (state->board[i] && !state->shared->clues[i])
1736 print_line_width(dr, TILE_SIZE / 64);
1737 draw_grid(dr, ds, state, NULL, FALSE, borders, FALSE);
1742 game_free_drawstate(dr, ds);
1746 #define thegame filling
1749 const struct game thegame = {
1750 "Filling", "games.filling", "filling",
1757 TRUE, game_configure, custom_params,
1765 TRUE, game_can_format_as_text_now, game_text_format,
1773 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1776 game_free_drawstate,
1781 TRUE, FALSE, game_print_size, game_print,
1782 FALSE, /* wants_statusbar */
1783 FALSE, game_timing_state,
1784 REQUIRE_NUMPAD, /* flags */
1787 #ifdef STANDALONE_SOLVER /* solver? hah! */
1789 int main(int argc, char **argv) {
1791 game_params *params;
1796 for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
1797 if (*desc == '\0') {
1798 fprintf(stderr, "bad puzzle id: %s", par);
1804 params = snew(game_params);
1805 decode_params(params, par);
1806 state = new_game(NULL, params, desc);
1807 if (solver(state->board, params->w, params->h, NULL))
1808 printf("%s:%s: solvable\n", par, desc);
1810 printf("%s:%s: not solvable\n", par, desc);
1817 /* vim: set shiftwidth=4 tabstop=8: */