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, ...) {
87 /*****************************************************************************
88 * GAME CONFIGURATION AND PARAMETERS *
89 *****************************************************************************/
96 struct game_params params;
103 struct shared_state *shared;
104 int completed, cheated;
107 static const struct game_params defaults[3] = {{7, 9}, {9, 13}, {13, 17}};
109 static game_params *default_params(void)
111 game_params *ret = snew(game_params);
113 *ret = defaults[1]; /* struct copy */
118 static int game_fetch_preset(int i, char **name, game_params **params)
122 if (i < 0 || i >= lenof(defaults)) return FALSE;
123 *params = snew(game_params);
124 **params = defaults[i]; /* struct copy */
125 sprintf(buf, "%dx%d", defaults[i].h, defaults[i].w);
131 static void free_params(game_params *params)
136 static game_params *dup_params(game_params *params)
138 game_params *ret = snew(game_params);
139 *ret = *params; /* struct copy */
143 static void decode_params(game_params *ret, char const *string)
145 ret->w = ret->h = atoi(string);
146 while (*string && isdigit((unsigned char) *string)) ++string;
147 if (*string == 'x') ret->h = atoi(++string);
150 static char *encode_params(game_params *params, int full)
153 sprintf(buf, "%dx%d", params->w, params->h);
157 static config_item *game_configure(game_params *params)
162 ret = snewn(3, config_item);
164 ret[0].name = "Width";
165 ret[0].type = C_STRING;
166 sprintf(buf, "%d", params->w);
167 ret[0].sval = dupstr(buf);
170 ret[1].name = "Height";
171 ret[1].type = C_STRING;
172 sprintf(buf, "%d", params->h);
173 ret[1].sval = dupstr(buf);
184 static game_params *custom_params(config_item *cfg)
186 game_params *ret = snew(game_params);
188 ret->w = atoi(cfg[0].sval);
189 ret->h = atoi(cfg[1].sval);
194 static char *validate_params(game_params *params, int full)
196 if (params->w < 1) return "Width must be at least one";
197 if (params->h < 1) return "Height must be at least one";
202 /*****************************************************************************
203 * STRINGIFICATION OF GAME STATE *
204 *****************************************************************************/
208 /* Example of plaintext rendering:
209 * +---+---+---+---+---+---+---+
210 * | 6 | | | 2 | | | 2 |
211 * +---+---+---+---+---+---+---+
212 * | | 3 | | 6 | | 3 | |
213 * +---+---+---+---+---+---+---+
214 * | 3 | | | | | | 1 |
215 * +---+---+---+---+---+---+---+
216 * | | 2 | 3 | | 4 | 2 | |
217 * +---+---+---+---+---+---+---+
218 * | 2 | | | | | | 3 |
219 * +---+---+---+---+---+---+---+
220 * | | 5 | | 1 | | 4 | |
221 * +---+---+---+---+---+---+---+
222 * | 4 | | | 3 | | | 3 |
223 * +---+---+---+---+---+---+---+
225 * This puzzle instance is taken from the nikoli website
226 * Encoded (unsolved and solved), the strings are these:
227 * 7x7:6002002030603030000010230420200000305010404003003
228 * 7x7:6662232336663232331311235422255544325413434443313
230 static char *board_to_string(int *board, int w, int h) {
231 const int sz = w * h;
232 const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
233 const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
234 const int chlen = chw * chh;
235 char *repr = snewn(chlen + 1, char);
240 /* build the first line ("^(\+---){n}\+$") */
241 for (i = 0; i < w; ++i) {
248 repr[4*i + 1] = '\n';
250 /* ... and copy it onto the odd-numbered lines */
251 for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
253 /* build the second line ("^(\|\t){n}\|$") */
254 for (i = 0; i < w; ++i) {
255 repr[chw + 4*i + 0] = '|';
256 repr[chw + 4*i + 1] = ' ';
257 repr[chw + 4*i + 2] = ' ';
258 repr[chw + 4*i + 3] = ' ';
260 repr[chw + 4*i + 0] = '|';
261 repr[chw + 4*i + 1] = '\n';
263 /* ... and copy it onto the even-numbered lines */
264 for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
266 /* fill in the numbers */
267 for (i = 0; i < sz; ++i) {
270 if (board[i] == EMPTY) continue;
271 repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
278 static char *game_text_format(game_state *state)
280 const int w = state->shared->params.w;
281 const int h = state->shared->params.h;
282 return board_to_string(state->board, w, h);
285 /*****************************************************************************
286 * GAME GENERATION AND SOLVER *
287 *****************************************************************************/
289 static const int dx[4] = {-1, 1, 0, 0};
290 static const int dy[4] = {0, 0, -1, 1};
300 static void print_board(int *board, int w, int h) {
302 char *repr = board_to_string(board, w, h);
303 printv("%s\n", repr);
308 static game_state *new_game(midend *, game_params *, char *);
309 static void free_game(game_state *);
313 /* generate a random valid board; uses validate_board. */
314 static void make_board(int *board, int w, int h, random_state *rs) {
317 const unsigned int sz = w * h;
319 /* w=h=2 is a special case which requires a number > max(w, h) */
320 /* TODO prove that this is the case ONLY for w=h=2. */
321 const int maxsize = min(max(max(w, h), 3), 9);
323 /* Note that if 1 in {w, h} then it's impossible to have a region
324 * of size > w*h, so the special case only affects w=h=2. */
334 dsf = snew_dsf(sz); /* implicit dsf_init */
336 /* I abuse the board variable: when generating the puzzle, it
337 * contains a shuffled list of numbers {0, ..., nsq-1}. */
338 for (i = 0; i < sz; ++i) board[i] = i;
343 shuffle(board, sz, sizeof (int), rs);
344 /* while the board can in principle be fixed */
347 for (i = 0; i < sz; ++i) {
351 const int aa = dsf_canonify(dsf, board[i]);
354 for (j = 0; j < 4; ++j) {
355 const int x = (board[i] % w) + dx[j];
356 const int y = (board[i] / w) + dy[j];
358 if (x < 0 || x >= w || y < 0 || y >= h) continue;
359 bb = dsf_canonify(dsf, w*y + x);
360 if (aa == bb) continue;
361 else if (dsf_size(dsf, aa) == dsf_size(dsf, bb)) {
365 } else if (cc == sz) c = cc = bb;
368 a = dsf_canonify(dsf, a);
369 assert(a != dsf_canonify(dsf, b));
370 if (c != sz) assert(a != dsf_canonify(dsf, c));
371 dsf_merge(dsf, a, c == sz? b: c);
372 /* if repair impossible; make a new board */
373 if (dsf_size(dsf, a) > maxsize) goto retry;
379 for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
382 printv("returning board number %d\n", nboards);
388 assert(FALSE); /* unreachable */
391 static int rhofree(int *hop, int start) {
392 int turtle = start, rabbit = hop[start];
393 while (rabbit != turtle) { /* find a cycle */
394 turtle = hop[turtle];
395 rabbit = hop[hop[rabbit]];
397 do { /* check that start is in the cycle */
398 rabbit = hop[rabbit];
399 if (start == rabbit) return 1;
400 } while (rabbit != turtle);
404 static void merge(int *dsf, int *connected, int a, int b) {
408 assert(rhofree(connected, a));
409 assert(rhofree(connected, b));
410 a = dsf_canonify(dsf, a);
411 b = dsf_canonify(dsf, b);
413 dsf_merge(dsf, a, b);
415 connected[a] = connected[b];
417 assert(rhofree(connected, a));
418 assert(rhofree(connected, b));
421 static void *memdup(const void *ptr, size_t len, size_t esz) {
422 void *dup = smalloc(len * esz);
424 memcpy(dup, ptr, len * esz);
428 static void expand(struct solver_state *s, int w, int h, int t, int f) {
431 assert(s->board[t] == EMPTY); /* expand to empty square */
432 assert(s->board[f] != EMPTY); /* expand from non-empty square */
434 "learn: expanding %d from (%d, %d) into (%d, %d)\n",
435 s->board[f], f % w, f / w, t % w, t / w);
436 s->board[t] = s->board[f];
437 for (j = 0; j < 4; ++j) {
438 const int x = (t % w) + dx[j];
439 const int y = (t / w) + dy[j];
440 const int idx = w*y + x;
441 if (x < 0 || x >= w || y < 0 || y >= h) continue;
442 if (s->board[idx] != s->board[t]) continue;
443 merge(s->dsf, s->connected, t, idx);
448 static void clear_count(int *board, int sz) {
450 for (i = 0; i < sz; ++i) {
451 if (board[i] >= 0) continue;
452 else if (board[i] == -SENTINEL) board[i] = EMPTY;
453 else board[i] = -board[i];
457 static void flood_count(int *board, int w, int h, int i, int n, int *c) {
458 const int sz = w * h;
461 if (board[i] == EMPTY) board[i] = -SENTINEL;
462 else if (board[i] == n) board[i] = -board[i];
465 if (--*c == 0) return;
467 for (k = 0; k < 4; ++k) {
468 const int x = (i % w) + dx[k];
469 const int y = (i / w) + dy[k];
470 const int idx = w*y + x;
471 if (x < 0 || x >= w || y < 0 || y >= h) continue;
472 flood_count(board, w, h, idx, n, c);
477 static int check_capacity(int *board, int w, int h, int i) {
479 flood_count(board, w, h, i, board[i], &n);
480 clear_count(board, w * h);
484 static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
489 for (j = 0; j < 4; ++j) {
490 const int x = (i % w) + dx[j];
491 const int y = (i / w) + dy[j];
492 const int idx = w*y + x;
495 if (x < 0 || x >= w || y < 0 || y >= h) continue;
496 if (board[idx] != n) continue;
497 root = dsf_canonify(dsf, idx);
498 for (m = 0; m < nhits && root != hits[m]; ++m);
499 if (m < nhits) continue;
500 printv("\t (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
501 size += dsf_size(dsf, root);
502 assert(dsf_size(dsf, root) >= 1);
503 hits[nhits++] = root;
509 * +---+---+---+---+---+---+---+
510 * | 6 | | | 2 | | | 2 |
511 * +---+---+---+---+---+---+---+
512 * | | 3 | | 6 | | 3 | |
513 * +---+---+---+---+---+---+---+
514 * | 3 | | | | | | 1 |
515 * +---+---+---+---+---+---+---+
516 * | | 2 | 3 | | 4 | 2 | |
517 * +---+---+---+---+---+---+---+
518 * | 2 | | | | | | 3 |
519 * +---+---+---+---+---+---+---+
520 * | | 5 | | 1 | | 4 | |
521 * +---+---+---+---+---+---+---+
522 * | 4 | | | 3 | | | 3 |
523 * +---+---+---+---+---+---+---+
526 /* Solving techniques:
528 * CONNECTED COMPONENT FORCED EXPANSION (too big):
529 * When a CC can only be expanded in one direction, because all the
530 * other ones would make the CC too big.
531 * +---+---+---+---+---+
532 * | 2 | 2 | | 2 | _ |
533 * +---+---+---+---+---+
535 * CONNECTED COMPONENT FORCED EXPANSION (too small):
536 * When a CC must include a particular square, because otherwise there
537 * would not be enough room to complete it. This includes squares not
538 * adjacent to the CC through learn_critical_square.
544 * When an empty square has no neighbouring empty squares and only a 1
545 * will go into the square (or other CCs would be too big).
550 * TODO: generalise DROPPING IN A ONE: find the size of the CC of
551 * empty squares and a list of all adjacent numbers. See if only one
552 * number in {1, ..., size} u {all adjacent numbers} is possible.
553 * Probably this is only effective for a CC size < n for some n (4?)
555 * TODO: backtracking.
558 static void filled_square(struct solver_state *s, int w, int h, int i) {
560 for (j = 0; j < 4; ++j) {
561 const int x = (i % w) + dx[j];
562 const int y = (i / w) + dy[j];
563 const int idx = w*y + x;
564 if (x < 0 || x >= w || y < 0 || y >= h) continue;
565 if (s->board[i] == s->board[idx])
566 merge(s->dsf, s->connected, i, idx);
570 static void init_solver_state(struct solver_state *s, int w, int h) {
571 const int sz = w * h;
576 for (i = 0; i < sz; ++i) s->connected[i] = i;
577 for (i = 0; i < sz; ++i)
578 if (s->board[i] == EMPTY) ++s->nempty;
579 else filled_square(s, w, h, i);
582 static int learn_expand_or_one(struct solver_state *s, int w, int h) {
583 const int sz = w * h;
589 for (i = 0; i < sz; ++i) {
593 if (s->board[i] != EMPTY) continue;
595 for (j = 0; j < 4; ++j) {
596 const int x = (i % w) + dx[j];
597 const int y = (i / w) + dy[j];
598 const int idx = w*y + x;
599 if (x < 0 || x >= w || y < 0 || y >= h) continue;
600 if (s->board[idx] == EMPTY) {
605 (s->board[idx] == 1 ||
606 (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
609 assert(s->board[i] == EMPTY);
610 s->board[i] = -SENTINEL;
611 if (check_capacity(s->board, w, h, idx)) continue;
612 assert(s->board[i] == EMPTY);
613 printv("learn: expanding in one\n");
614 expand(s, w, h, i, idx);
620 printv("learn: one at (%d, %d)\n", i % w, i / w);
621 assert(s->board[i] == EMPTY);
631 static int learn_blocked_expansion(struct solver_state *s, int w, int h) {
632 const int sz = w * h;
637 /* for every connected component */
638 for (i = 0; i < sz; ++i) {
642 if (s->board[i] == EMPTY) continue;
643 j = dsf_canonify(s->dsf, i);
645 /* (but only for each connected component) */
646 if (i != j) continue;
648 /* (and not if it's already complete) */
649 if (dsf_size(s->dsf, j) == s->board[j]) continue;
651 /* for each square j _in_ the connected component */
654 printv(" looking at (%d, %d)\n", j % w, j / w);
656 /* for each neighbouring square (idx) */
657 for (k = 0; k < 4; ++k) {
658 const int x = (j % w) + dx[k];
659 const int y = (j / w) + dy[k];
660 const int idx = w*y + x;
665 if (x < 0 || x >= w || y < 0 || y >= h) continue;
666 if (s->board[idx] != EMPTY) continue;
667 if (exp == idx) continue;
668 printv("\ttrying to expand onto (%d, %d)\n", x, y);
670 /* find out the would-be size of the new connected
671 * component if we actually expanded into idx */
674 for (l = 0; l < 4; ++l) {
675 const int lx = x + dx[l];
676 const int ly = y + dy[l];
677 const int idxl = w*ly + lx;
680 if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
681 if (board[idxl] != board[j]) continue;
682 root = dsf_canonify(dsf, idxl);
683 for (m = 0; m < nhits && root != hits[m]; ++m);
684 if (m != nhits) continue;
685 // printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
686 size += dsf_size(dsf, root);
687 assert(dsf_size(dsf, root) >= 1);
688 hits[nhits++] = root;
692 size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
694 /* ... and see if that size is too big, or if we
695 * have other expansion candidates. Otherwise
696 * remember the (so far) only candidate. */
698 printv("\tthat would give a size of %d\n", size);
699 if (size > s->board[j]) continue;
700 /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
701 if (exp != SENTINEL) goto next_i;
706 j = s->connected[j]; /* next square in the same CC */
707 assert(s->board[i] == s->board[j]);
709 /* end: for each square j _in_ the connected component */
711 if (exp == SENTINEL) continue;
712 printv("learning to expand\n");
713 expand(s, w, h, exp, i);
719 /* end: for each connected component */
723 static int learn_critical_square(struct solver_state *s, int w, int h) {
724 const int sz = w * h;
729 /* for each connected component */
730 for (i = 0; i < sz; ++i) {
732 if (s->board[i] == EMPTY) continue;
733 if (i != dsf_canonify(s->dsf, i)) continue;
734 if (dsf_size(s->dsf, i) == s->board[i]) continue;
735 assert(s->board[i] != 1);
736 /* for each empty square */
737 for (j = 0; j < sz; ++j) {
738 if (s->board[j] != EMPTY) continue;
739 s->board[j] = -SENTINEL;
740 if (check_capacity(s->board, w, h, i)) continue;
741 /* if not expanding s->board[i] to s->board[j] implies
742 * that s->board[i] can't reach its full size, ... */
745 "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
746 s->board[i], j % w, j / w, i % w, i / w);
748 s->board[j] = s->board[i];
749 filled_square(s, w, h, j);
756 static int solver(const int *orig, int w, int h, char **solution) {
757 const int sz = w * h;
759 struct solver_state ss;
760 ss.board = memdup(orig, sz, sizeof (int));
761 ss.dsf = snew_dsf(sz); /* eqv classes: connected components */
762 ss.connected = snewn(sz, int); /* connected[n] := n.next; */
763 /* cyclic disjoint singly linked lists, same partitioning as dsf.
764 * The lists lets you iterate over a partition given any member */
766 printv("trying to solve this:\n");
767 print_board(ss.board, w, h);
769 init_solver_state(&ss, w, h);
771 if (learn_blocked_expansion(&ss, w, h)) continue;
772 if (learn_expand_or_one(&ss, w, h)) continue;
773 if (learn_critical_square(&ss, w, h)) continue;
777 printv("best guess:\n");
778 print_board(ss.board, w, h);
782 assert(*solution == NULL);
783 *solution = snewn(sz + 2, char);
785 for (i = 0; i < sz; ++i) (*solution)[i + 1] = ss.board[i] + '0';
786 (*solution)[sz + 1] = '\0';
787 /* We don't need the \0 for execute_move (the only user)
788 * I'm just being printf-friendly in case I wanna print */
798 static int *make_dsf(int *dsf, int *board, const int w, const int h) {
799 const int sz = w * h;
803 dsf = snew_dsf(w * h);
805 dsf_init(dsf, w * h);
807 for (i = 0; i < sz; ++i) {
809 for (j = 0; j < 4; ++j) {
810 const int x = (i % w) + dx[j];
811 const int y = (i / w) + dy[j];
812 const int k = w*y + x;
813 if (x < 0 || x >= w || y < 0 || y >= h) continue;
814 if (board[i] == board[k]) dsf_merge(dsf, i, k);
821 static int filled(int *board, int *randomize, int k, int n) {
823 if (board == NULL) return FALSE;
824 if (randomize == NULL) return FALSE;
825 if (k > n) return FALSE;
826 for (i = 0; i < k; ++i) if (board[randomize[i]] == 0) return FALSE;
827 for (; i < n; ++i) if (board[randomize[i]] != 0) return FALSE;
833 static int compare(const void *pa, const void *pb) {
834 if (!g_board) return 0;
835 return g_board[*(const int *)pb] - g_board[*(const int *)pa];
838 static void minimize_clue_set(int *board, int w, int h, int *randomize) {
839 const int sz = w * h;
841 int *board_cp = snewn(sz, int);
842 memcpy(board_cp, board, sz * sizeof (int));
844 /* since more clues only helps and never hurts, one pass will do
845 * just fine: if we can remove clue n with k clues of index > n,
846 * we could have removed clue n with >= k clues of index > n.
847 * So an additional pass wouldn't do anything [use induction]. */
848 for (i = 0; i < sz; ++i) {
849 if (board[randomize[i]] == EMPTY) continue;
850 board[randomize[i]] = EMPTY;
851 /* (rot.) symmetry tends to include _way_ too many hints */
852 /* board[sz - randomize[i] - 1] = EMPTY; */
853 if (!solver(board, w, h, NULL)) {
854 board[randomize[i]] = board_cp[randomize[i]];
855 /* board[sz - randomize[i] - 1] =
856 board_cp[sz - randomize[i] - 1]; */
863 static char *new_game_desc(game_params *params, random_state *rs,
864 char **aux, int interactive)
866 const int w = params->w;
867 const int h = params->h;
868 const int sz = w * h;
869 int *board = snewn(sz, int);
870 int *randomize = snewn(sz, int);
871 char *game_description = snewn(sz + 1, char);
874 for (i = 0; i < sz; ++i) {
879 make_board(board, w, h, rs);
881 qsort(randomize, sz, sizeof (int), compare);
882 minimize_clue_set(board, w, h, randomize);
884 for (i = 0; i < sz; ++i) {
885 assert(board[i] >= 0);
886 assert(board[i] < 10);
887 game_description[i] = board[i] + '0';
889 game_description[sz] = '\0';
892 solver(board, w, h, aux);
893 print_board(board, w, h);
899 return game_description;
902 static char *validate_desc(game_params *params, char *desc)
905 const int sz = params->w * params->h;
906 const char m = '0' + max(max(params->w, params->h), 3);
908 printv("desc = '%s'; sz = %d\n", desc, sz);
910 for (i = 0; desc[i] && i < sz; ++i)
911 if (!isdigit((unsigned char) *desc))
912 return "non-digit in string";
913 else if (desc[i] > m)
914 return "too large digit in string";
915 if (desc[i]) return "string too long";
916 else if (i < sz) return "string too short";
920 static game_state *new_game(midend *me, game_params *params, char *desc)
922 game_state *state = snew(game_state);
923 int sz = params->w * params->h;
926 state->cheated = state->completed = FALSE;
927 state->shared = snew(struct shared_state);
928 state->shared->refcnt = 1;
929 state->shared->params = *params; /* struct copy */
930 state->shared->clues = snewn(sz, int);
931 for (i = 0; i < sz; ++i) state->shared->clues[i] = desc[i] - '0';
932 state->board = memdup(state->shared->clues, sz, sizeof (int));
937 static game_state *dup_game(game_state *state)
939 const int sz = state->shared->params.w * state->shared->params.h;
940 game_state *ret = snew(game_state);
942 ret->board = memdup(state->board, sz, sizeof (int));
943 ret->shared = state->shared;
944 ret->cheated = state->cheated;
945 ret->completed = state->completed;
946 ++ret->shared->refcnt;
951 static void free_game(game_state *state)
955 if (--state->shared->refcnt == 0) {
956 sfree(state->shared->clues);
957 sfree(state->shared);
962 static char *solve_game(game_state *state, game_state *currstate,
963 char *aux, char **error)
966 const int w = state->shared->params.w;
967 const int h = state->shared->params.h;
968 if (!solver(state->board, w, h, &aux))
969 *error = "Sorry, I couldn't find a solution";
974 /*****************************************************************************
975 * USER INTERFACE STATE AND ACTION *
976 *****************************************************************************/
979 int *sel; /* w*h highlighted squares, or NULL */
982 static game_ui *new_ui(game_state *state)
984 game_ui *ui = snew(game_ui);
991 static void free_ui(game_ui *ui)
998 static char *encode_ui(game_ui *ui)
1003 static void decode_ui(game_ui *ui, char *encoding)
1007 static void game_changed_state(game_ui *ui, game_state *oldstate,
1008 game_state *newstate)
1010 /* Clear any selection */
1017 #define PREFERRED_TILE_SIZE 32
1018 #define TILE_SIZE (ds->tilesize)
1019 #define BORDER (TILE_SIZE / 2)
1020 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1022 struct game_drawstate {
1023 struct game_params params;
1027 int *dsf_scratch, *border_scratch;
1030 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1031 int x, int y, int button)
1033 const int w = state->shared->params.w;
1034 const int h = state->shared->params.h;
1036 const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1037 const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1045 button &= ~MOD_MASK;
1047 if (button == LEFT_BUTTON || button == LEFT_DRAG) {
1048 /* A left-click anywhere will clear the current selection. */
1049 if (button == LEFT_BUTTON) {
1055 if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
1057 ui->sel = snewn(w*h, int);
1058 memset(ui->sel, 0, w*h*sizeof(int));
1060 if (!state->shared->clues[w*ty+tx])
1061 ui->sel[w*ty+tx] = 1;
1063 return ""; /* redraw */
1066 if (!ui->sel) return NULL;
1077 if (!isdigit(button)) return NULL;
1079 if (button > (w == 2 && h == 2? 3: max(w, h))) return NULL;
1082 for (i = 0; i < w*h; i++) {
1085 assert(state->shared->clues[i] == 0);
1086 if (state->board[i] != button) {
1087 sprintf(buf, "%s%d", move ? "," : "", i);
1089 move = srealloc(move, strlen(move)+strlen(buf)+1);
1092 move = smalloc(strlen(buf)+1);
1100 sprintf(buf, "_%d", button);
1101 move = srealloc(move, strlen(move)+strlen(buf)+1);
1106 /* Need to update UI at least, as we cleared the selection */
1107 return move ? move : "";
1110 static game_state *execute_move(game_state *state, char *move)
1112 game_state *new_state;
1113 const int sz = state->shared->params.w * state->shared->params.h;
1117 new_state = dup_game(state);
1118 for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
1119 new_state->cheated = TRUE;
1122 char *endptr, *delim = strchr(move, '_');
1123 if (!delim) return NULL;
1124 value = strtol(delim+1, &endptr, 0);
1125 if (*endptr || endptr == delim+1) return NULL;
1126 if (value < 0 || value > 9) return NULL;
1127 new_state = dup_game(state);
1129 const int i = strtol(move, &endptr, 0);
1130 if (endptr == move) return NULL;
1131 if (i < 0 || i >= sz) return NULL;
1132 new_state->board[i] = value;
1133 if (*endptr == '_') break;
1134 if (*endptr != ',') return NULL;
1140 * Check for completion.
1142 if (!new_state->completed) {
1143 const int w = new_state->shared->params.w;
1144 const int h = new_state->shared->params.h;
1145 const int sz = w * h;
1146 int *dsf = make_dsf(NULL, new_state->board, w, h);
1148 for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
1151 new_state->completed = TRUE;
1157 /* ----------------------------------------------------------------------
1161 #define FLASH_TIME 0.4F
1163 #define COL_CLUE COL_GRID
1174 static void game_compute_size(game_params *params, int tilesize,
1177 *x = (params->w + 1) * tilesize;
1178 *y = (params->h + 1) * tilesize;
1181 static void game_set_size(drawing *dr, game_drawstate *ds,
1182 game_params *params, int tilesize)
1184 ds->tilesize = tilesize;
1187 static float *game_colours(frontend *fe, int *ncolours)
1189 float *ret = snewn(3 * NCOLOURS, float);
1191 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1193 ret[COL_GRID * 3 + 0] = 0.0F;
1194 ret[COL_GRID * 3 + 1] = 0.0F;
1195 ret[COL_GRID * 3 + 2] = 0.0F;
1197 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1198 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1199 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1201 ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
1202 ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
1203 ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
1205 ret[COL_ERROR * 3 + 0] = 1.0F;
1206 ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1207 ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1209 ret[COL_USER * 3 + 0] = 0.0F;
1210 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1211 ret[COL_USER * 3 + 2] = 0.0F;
1213 *ncolours = NCOLOURS;
1217 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1219 struct game_drawstate *ds = snew(struct game_drawstate);
1222 ds->tilesize = PREFERRED_TILE_SIZE;
1224 ds->params = state->shared->params;
1225 ds->v = snewn(ds->params.w * ds->params.h, int);
1226 ds->flags = snewn(ds->params.w * ds->params.h, int);
1227 for (i = 0; i < ds->params.w * ds->params.h; i++)
1228 ds->v[i] = ds->flags[i] = -1;
1229 ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
1230 ds->dsf_scratch = NULL;
1235 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1239 sfree(ds->border_scratch);
1240 sfree(ds->dsf_scratch);
1244 #define BORDER_U 0x001
1245 #define BORDER_D 0x002
1246 #define BORDER_L 0x004
1247 #define BORDER_R 0x008
1248 #define BORDER_UR 0x010
1249 #define BORDER_DR 0x020
1250 #define BORDER_UL 0x040
1251 #define BORDER_DL 0x080
1252 #define CURSOR_BG 0x100
1253 #define CORRECT_BG 0x200
1254 #define ERROR_BG 0x400
1255 #define USER_COL 0x800
1257 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
1264 * Clip to the grid square.
1266 clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1267 TILE_SIZE, TILE_SIZE);
1273 BORDER + x*TILE_SIZE,
1274 BORDER + y*TILE_SIZE,
1277 (flags & CURSOR_BG ? COL_HIGHLIGHT :
1278 flags & ERROR_BG ? COL_ERROR :
1279 flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
1282 * Draw the grid lines.
1284 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1285 BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
1286 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1287 BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
1297 (x + 1) * TILE_SIZE,
1298 (y + 1) * TILE_SIZE,
1301 ALIGN_VCENTRE | ALIGN_HCENTRE,
1302 flags & USER_COL ? COL_USER : COL_CLUE,
1307 * Draw bold lines around the borders.
1309 if (flags & BORDER_L)
1311 BORDER + x*TILE_SIZE + 1,
1312 BORDER + y*TILE_SIZE + 1,
1316 if (flags & BORDER_U)
1318 BORDER + x*TILE_SIZE + 1,
1319 BORDER + y*TILE_SIZE + 1,
1323 if (flags & BORDER_R)
1325 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1326 BORDER + y*TILE_SIZE + 1,
1330 if (flags & BORDER_D)
1332 BORDER + x*TILE_SIZE + 1,
1333 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1337 if (flags & BORDER_UL)
1339 BORDER + x*TILE_SIZE + 1,
1340 BORDER + y*TILE_SIZE + 1,
1344 if (flags & BORDER_UR)
1346 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1347 BORDER + y*TILE_SIZE + 1,
1351 if (flags & BORDER_DL)
1353 BORDER + x*TILE_SIZE + 1,
1354 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1358 if (flags & BORDER_DR)
1360 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1361 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1369 BORDER + x*TILE_SIZE,
1370 BORDER + y*TILE_SIZE,
1375 static void draw_grid(drawing *dr, game_drawstate *ds, game_state *state,
1376 game_ui *ui, int flashy, int borders, int shading)
1378 const int w = state->shared->params.w;
1379 const int h = state->shared->params.h;
1384 * Build a dsf for the board in its current state, to use for
1385 * highlights and hints.
1387 ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
1390 * Work out where we're putting borders between the cells.
1392 for (y = 0; y < w*h; y++)
1393 ds->border_scratch[y] = 0;
1395 for (y = 0; y < h; y++)
1396 for (x = 0; x < w; x++) {
1400 for (dx = 0; dx <= 1; dx++) {
1405 if (x+dx >= w || y+dy >= h)
1408 v1 = state->board[y*w+x];
1409 v2 = state->board[(y+dy)*w+(x+dx)];
1410 s1 = dsf_size(ds->dsf_scratch, y*w+x);
1411 s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
1414 * We only ever draw a border between two cells if
1415 * they don't have the same contents.
1419 * But in that situation, we don't always draw
1420 * a border. We do if the two cells both
1421 * contain actual numbers...
1427 * ... or if at least one of them is a
1428 * completed or overfull omino.
1437 ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
1442 * Actually do the drawing.
1444 for (y = 0; y < h; ++y)
1445 for (x = 0; x < w; ++x) {
1447 * Determine what we need to draw in this square.
1449 int v = state->board[y*w+x];
1452 if (flashy || !shading) {
1453 /* clear all background flags */
1454 } else if (ui->sel && ui->sel[y*w+x]) {
1457 int size = dsf_size(ds->dsf_scratch, y*w+x);
1459 flags |= CORRECT_BG;
1465 * Borders at the very edges of the grid are
1466 * independent of the `borders' flag.
1478 if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
1480 if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
1482 if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
1484 if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
1487 if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
1489 if (y > 0 && x < w-1 &&
1490 ((ds->border_scratch[(y-1)*w+x] & 1) ||
1491 (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
1493 if (y < h-1 && x > 0 &&
1494 ((ds->border_scratch[y*w+(x-1)] & 2) ||
1495 (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
1497 if (y < h-1 && x < w-1 &&
1498 ((ds->border_scratch[y*w+(x+1)] & 2) ||
1499 (ds->border_scratch[(y+1)*w+x] & 1)))
1503 if (!state->shared->clues[y*w+x])
1506 if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
1507 draw_square(dr, ds, x, y, v, flags);
1509 ds->flags[y*w+x] = flags;
1514 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1515 game_state *state, int dir, game_ui *ui,
1516 float animtime, float flashtime)
1518 const int w = state->shared->params.w;
1519 const int h = state->shared->params.h;
1523 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
1527 * The initial contents of the window are not guaranteed and
1528 * can vary with front ends. To be on the safe side, all games
1529 * should start by drawing a big background-colour rectangle
1530 * covering the whole window.
1532 draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
1536 * Smaller black rectangle which is the main grid.
1538 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1539 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1540 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1543 draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
1548 draw_grid(dr, ds, state, ui, flashy, TRUE, TRUE);
1551 static float game_anim_length(game_state *oldstate, game_state *newstate,
1552 int dir, game_ui *ui)
1557 static float game_flash_length(game_state *oldstate, game_state *newstate,
1558 int dir, game_ui *ui)
1562 assert(newstate->shared);
1563 assert(oldstate->shared == newstate->shared);
1564 if (!oldstate->completed && newstate->completed &&
1565 !oldstate->cheated && !newstate->cheated)
1570 static int game_timing_state(game_state *state, game_ui *ui)
1575 static void game_print_size(game_params *params, float *x, float *y)
1580 * I'll use 6mm squares by default.
1582 game_compute_size(params, 600, &pw, &ph);
1587 static void game_print(drawing *dr, game_state *state, int tilesize)
1589 const int w = state->shared->params.w;
1590 const int h = state->shared->params.h;
1593 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1594 game_drawstate *ds = game_new_drawstate(dr, state);
1595 game_set_size(dr, ds, NULL, tilesize);
1597 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1598 c = print_mono_colour(dr, 0); assert(c == COL_GRID);
1599 c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
1600 c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
1601 c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
1602 c = print_mono_colour(dr, 0); assert(c == COL_USER);
1607 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1608 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1609 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1613 * We'll draw borders between the ominoes iff the grid is not
1614 * pristine. So scan it to see if it is.
1617 for (i = 0; i < w*h; i++)
1618 if (state->board[i] && !state->shared->clues[i])
1624 print_line_width(dr, TILE_SIZE / 64);
1625 draw_grid(dr, ds, state, NULL, FALSE, borders, FALSE);
1630 game_free_drawstate(dr, ds);
1634 #define thegame filling
1637 const struct game thegame = {
1638 "Filling", "games.filling", "filling",
1645 TRUE, game_configure, custom_params,
1653 TRUE, game_text_format,
1661 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1664 game_free_drawstate,
1668 TRUE, FALSE, game_print_size, game_print,
1669 FALSE, /* wants_statusbar */
1670 FALSE, game_timing_state,
1671 REQUIRE_NUMPAD, /* flags */
1674 #ifdef STANDALONE_SOLVER /* solver? hah! */
1676 int main(int argc, char **argv) {
1678 game_params *params;
1683 for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
1684 if (*desc == '\0') {
1685 fprintf(stderr, "bad puzzle id: %s", par);
1691 params = snew(game_params);
1692 decode_params(params, par);
1693 state = new_game(NULL, params, desc);
1694 if (solver(state->board, params->w, params->h, NULL))
1695 printf("%s:%s: solvable\n", par, desc);
1697 printf("%s:%s: not solvable\n", par, desc);