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 /* generate a random valid board; uses validate_board. */
321 static void make_board(int *board, int w, int h, random_state *rs) {
324 const unsigned int sz = w * h;
326 /* w=h=2 is a special case which requires a number > max(w, h) */
327 /* TODO prove that this is the case ONLY for w=h=2. */
328 const int maxsize = min(max(max(w, h), 3), 9);
330 /* Note that if 1 in {w, h} then it's impossible to have a region
331 * of size > w*h, so the special case only affects w=h=2. */
341 dsf = snew_dsf(sz); /* implicit dsf_init */
343 /* I abuse the board variable: when generating the puzzle, it
344 * contains a shuffled list of numbers {0, ..., nsq-1}. */
345 for (i = 0; i < (int)sz; ++i) board[i] = i;
350 shuffle(board, sz, sizeof (int), rs);
351 /* while the board can in principle be fixed */
354 for (i = 0; i < (int)sz; ++i) {
358 const int aa = dsf_canonify(dsf, board[i]);
361 for (j = 0; j < 4; ++j) {
362 const int x = (board[i] % w) + dx[j];
363 const int y = (board[i] / w) + dy[j];
365 if (x < 0 || x >= w || y < 0 || y >= h) continue;
366 bb = dsf_canonify(dsf, w*y + x);
367 if (aa == bb) continue;
368 else if (dsf_size(dsf, aa) == dsf_size(dsf, bb)) {
372 } else if (cc == sz) c = cc = bb;
375 a = dsf_canonify(dsf, a);
376 assert(a != dsf_canonify(dsf, b));
377 if (c != sz) assert(a != dsf_canonify(dsf, c));
378 dsf_merge(dsf, a, c == sz? b: c);
379 /* if repair impossible; make a new board */
380 if (dsf_size(dsf, a) > maxsize) goto retry;
386 for (i = 0; i < (int)sz; ++i) board[i] = dsf_size(dsf, i);
389 printv("returning board number %d\n", nboards);
395 assert(FALSE); /* unreachable */
398 static void merge(int *dsf, int *connected, int a, int b) {
402 a = dsf_canonify(dsf, a);
403 b = dsf_canonify(dsf, b);
405 dsf_merge(dsf, a, b);
407 connected[a] = connected[b];
411 static void *memdup(const void *ptr, size_t len, size_t esz) {
412 void *dup = smalloc(len * esz);
414 memcpy(dup, ptr, len * esz);
418 static void expand(struct solver_state *s, int w, int h, int t, int f) {
421 assert(s->board[t] == EMPTY); /* expand to empty square */
422 assert(s->board[f] != EMPTY); /* expand from non-empty square */
424 "learn: expanding %d from (%d, %d) into (%d, %d)\n",
425 s->board[f], f % w, f / w, t % w, t / w);
426 s->board[t] = s->board[f];
427 for (j = 0; j < 4; ++j) {
428 const int x = (t % w) + dx[j];
429 const int y = (t / w) + dy[j];
430 const int idx = w*y + x;
431 if (x < 0 || x >= w || y < 0 || y >= h) continue;
432 if (s->board[idx] != s->board[t]) continue;
433 merge(s->dsf, s->connected, t, idx);
438 static void clear_count(int *board, int sz) {
440 for (i = 0; i < sz; ++i) {
441 if (board[i] >= 0) continue;
442 else if (board[i] == -SENTINEL) board[i] = EMPTY;
443 else board[i] = -board[i];
447 static void flood_count(int *board, int w, int h, int i, int n, int *c) {
448 const int sz = w * h;
451 if (board[i] == EMPTY) board[i] = -SENTINEL;
452 else if (board[i] == n) board[i] = -board[i];
455 if (--*c == 0) return;
457 for (k = 0; k < 4; ++k) {
458 const int x = (i % w) + dx[k];
459 const int y = (i / w) + dy[k];
460 const int idx = w*y + x;
461 if (x < 0 || x >= w || y < 0 || y >= h) continue;
462 flood_count(board, w, h, idx, n, c);
467 static int check_capacity(int *board, int w, int h, int i) {
469 flood_count(board, w, h, i, board[i], &n);
470 clear_count(board, w * h);
474 static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
479 for (j = 0; j < 4; ++j) {
480 const int x = (i % w) + dx[j];
481 const int y = (i / w) + dy[j];
482 const int idx = w*y + x;
485 if (x < 0 || x >= w || y < 0 || y >= h) continue;
486 if (board[idx] != n) continue;
487 root = dsf_canonify(dsf, idx);
488 for (m = 0; m < nhits && root != hits[m]; ++m);
489 if (m < nhits) continue;
490 printv("\t (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
491 size += dsf_size(dsf, root);
492 assert(dsf_size(dsf, root) >= 1);
493 hits[nhits++] = root;
499 * +---+---+---+---+---+---+---+
500 * | 6 | | | 2 | | | 2 |
501 * +---+---+---+---+---+---+---+
502 * | | 3 | | 6 | | 3 | |
503 * +---+---+---+---+---+---+---+
504 * | 3 | | | | | | 1 |
505 * +---+---+---+---+---+---+---+
506 * | | 2 | 3 | | 4 | 2 | |
507 * +---+---+---+---+---+---+---+
508 * | 2 | | | | | | 3 |
509 * +---+---+---+---+---+---+---+
510 * | | 5 | | 1 | | 4 | |
511 * +---+---+---+---+---+---+---+
512 * | 4 | | | 3 | | | 3 |
513 * +---+---+---+---+---+---+---+
516 /* Solving techniques:
518 * CONNECTED COMPONENT FORCED EXPANSION (too big):
519 * When a CC can only be expanded in one direction, because all the
520 * other ones would make the CC too big.
521 * +---+---+---+---+---+
522 * | 2 | 2 | | 2 | _ |
523 * +---+---+---+---+---+
525 * CONNECTED COMPONENT FORCED EXPANSION (too small):
526 * When a CC must include a particular square, because otherwise there
527 * would not be enough room to complete it. This includes squares not
528 * adjacent to the CC through learn_critical_square.
534 * When an empty square has no neighbouring empty squares and only a 1
535 * will go into the square (or other CCs would be too big).
540 * TODO: generalise DROPPING IN A ONE: find the size of the CC of
541 * empty squares and a list of all adjacent numbers. See if only one
542 * number in {1, ..., size} u {all adjacent numbers} is possible.
543 * Probably this is only effective for a CC size < n for some n (4?)
545 * TODO: backtracking.
548 static void filled_square(struct solver_state *s, int w, int h, int i) {
550 for (j = 0; j < 4; ++j) {
551 const int x = (i % w) + dx[j];
552 const int y = (i / w) + dy[j];
553 const int idx = w*y + x;
554 if (x < 0 || x >= w || y < 0 || y >= h) continue;
555 if (s->board[i] == s->board[idx])
556 merge(s->dsf, s->connected, i, idx);
560 static void init_solver_state(struct solver_state *s, int w, int h) {
561 const int sz = w * h;
566 for (i = 0; i < sz; ++i) s->connected[i] = i;
567 for (i = 0; i < sz; ++i)
568 if (s->board[i] == EMPTY) ++s->nempty;
569 else filled_square(s, w, h, i);
572 static int learn_expand_or_one(struct solver_state *s, int w, int h) {
573 const int sz = w * h;
579 for (i = 0; i < sz; ++i) {
583 if (s->board[i] != EMPTY) continue;
585 for (j = 0; j < 4; ++j) {
586 const int x = (i % w) + dx[j];
587 const int y = (i / w) + dy[j];
588 const int idx = w*y + x;
589 if (x < 0 || x >= w || y < 0 || y >= h) continue;
590 if (s->board[idx] == EMPTY) {
595 (s->board[idx] == 1 ||
596 (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
599 if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
600 assert(s->board[i] == EMPTY);
601 s->board[i] = -SENTINEL;
602 if (check_capacity(s->board, w, h, idx)) continue;
603 assert(s->board[i] == EMPTY);
604 printv("learn: expanding in one\n");
605 expand(s, w, h, i, idx);
611 printv("learn: one at (%d, %d)\n", i % w, i / w);
612 assert(s->board[i] == EMPTY);
622 static int learn_blocked_expansion(struct solver_state *s, int w, int h) {
623 const int sz = w * h;
628 /* for every connected component */
629 for (i = 0; i < sz; ++i) {
633 if (s->board[i] == EMPTY) continue;
634 j = dsf_canonify(s->dsf, i);
636 /* (but only for each connected component) */
637 if (i != j) continue;
639 /* (and not if it's already complete) */
640 if (dsf_size(s->dsf, j) == s->board[j]) continue;
642 /* for each square j _in_ the connected component */
645 printv(" looking at (%d, %d)\n", j % w, j / w);
647 /* for each neighbouring square (idx) */
648 for (k = 0; k < 4; ++k) {
649 const int x = (j % w) + dx[k];
650 const int y = (j / w) + dy[k];
651 const int idx = w*y + x;
656 if (x < 0 || x >= w || y < 0 || y >= h) continue;
657 if (s->board[idx] != EMPTY) continue;
658 if (exp == idx) continue;
659 printv("\ttrying to expand onto (%d, %d)\n", x, y);
661 /* find out the would-be size of the new connected
662 * component if we actually expanded into idx */
665 for (l = 0; l < 4; ++l) {
666 const int lx = x + dx[l];
667 const int ly = y + dy[l];
668 const int idxl = w*ly + lx;
671 if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
672 if (board[idxl] != board[j]) continue;
673 root = dsf_canonify(dsf, idxl);
674 for (m = 0; m < nhits && root != hits[m]; ++m);
675 if (m != nhits) continue;
676 // printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
677 size += dsf_size(dsf, root);
678 assert(dsf_size(dsf, root) >= 1);
679 hits[nhits++] = root;
683 size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
685 /* ... and see if that size is too big, or if we
686 * have other expansion candidates. Otherwise
687 * remember the (so far) only candidate. */
689 printv("\tthat would give a size of %d\n", size);
690 if (size > s->board[j]) continue;
691 /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
692 if (exp != SENTINEL) goto next_i;
697 j = s->connected[j]; /* next square in the same CC */
698 assert(s->board[i] == s->board[j]);
700 /* end: for each square j _in_ the connected component */
702 if (exp == SENTINEL) continue;
703 printv("learning to expand\n");
704 expand(s, w, h, exp, i);
710 /* end: for each connected component */
714 static int learn_critical_square(struct solver_state *s, int w, int h) {
715 const int sz = w * h;
720 /* for each connected component */
721 for (i = 0; i < sz; ++i) {
723 if (s->board[i] == EMPTY) continue;
724 if (i != dsf_canonify(s->dsf, i)) continue;
725 slack = s->board[i] - dsf_size(s->dsf, i);
726 if (slack == 0) continue;
727 assert(s->board[i] != 1);
728 /* for each empty square */
729 for (j = 0; j < sz; ++j) {
730 if (s->board[j] == EMPTY) {
731 /* if it's too far away from the CC, don't bother */
732 int k = i, jx = j % w, jy = j / w;
734 int kx = k % w, ky = k / w;
735 if (abs(kx - jx) + abs(ky - jy) <= slack) break;
738 if (i == k) continue; /* not within range */
740 s->board[j] = -SENTINEL;
741 if (check_capacity(s->board, w, h, i)) continue;
742 /* if not expanding s->board[i] to s->board[j] implies
743 * that s->board[i] can't reach its full size, ... */
746 "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
747 s->board[i], j % w, j / w, i % w, i / w);
749 s->board[j] = s->board[i];
750 filled_square(s, w, h, j);
757 static int solver(const int *orig, int w, int h, char **solution) {
758 const int sz = w * h;
760 struct solver_state ss;
761 ss.board = memdup(orig, sz, sizeof (int));
762 ss.dsf = snew_dsf(sz); /* eqv classes: connected components */
763 ss.connected = snewn(sz, int); /* connected[n] := n.next; */
764 /* cyclic disjoint singly linked lists, same partitioning as dsf.
765 * The lists lets you iterate over a partition given any member */
767 printv("trying to solve this:\n");
768 print_board(ss.board, w, h);
770 init_solver_state(&ss, w, h);
772 if (learn_blocked_expansion(&ss, w, h)) continue;
773 if (learn_expand_or_one(&ss, w, h)) continue;
774 if (learn_critical_square(&ss, w, h)) continue;
778 printv("best guess:\n");
779 print_board(ss.board, w, h);
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(const 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(const game_params *params, const 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, const game_params *params,
923 game_state *state = snew(game_state);
924 int sz = params->w * params->h;
927 state->cheated = state->completed = FALSE;
928 state->shared = snew(struct shared_state);
929 state->shared->refcnt = 1;
930 state->shared->params = *params; /* struct copy */
931 state->shared->clues = snewn(sz, int);
932 for (i = 0; i < sz; ++i) state->shared->clues[i] = desc[i] - '0';
933 state->board = memdup(state->shared->clues, sz, sizeof (int));
938 static game_state *dup_game(const game_state *state)
940 const int sz = state->shared->params.w * state->shared->params.h;
941 game_state *ret = snew(game_state);
943 ret->board = memdup(state->board, sz, sizeof (int));
944 ret->shared = state->shared;
945 ret->cheated = state->cheated;
946 ret->completed = state->completed;
947 ++ret->shared->refcnt;
952 static void free_game(game_state *state)
956 if (--state->shared->refcnt == 0) {
957 sfree(state->shared->clues);
958 sfree(state->shared);
963 static char *solve_game(const game_state *state, const game_state *currstate,
964 const char *aux, char **error)
967 const int w = state->shared->params.w;
968 const int h = state->shared->params.h;
970 if (!solver(state->board, w, h, &new_aux))
971 *error = "Sorry, I couldn't find a solution";
977 /*****************************************************************************
978 * USER INTERFACE STATE AND ACTION *
979 *****************************************************************************/
982 int *sel; /* w*h highlighted squares, or NULL */
983 int cur_x, cur_y, cur_visible, keydragging;
986 static game_ui *new_ui(const game_state *state)
988 game_ui *ui = snew(game_ui);
991 ui->cur_x = ui->cur_y = ui->cur_visible = ui->keydragging = 0;
996 static void free_ui(game_ui *ui)
1003 static char *encode_ui(const game_ui *ui)
1008 static void decode_ui(game_ui *ui, const char *encoding)
1012 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1013 const game_state *newstate)
1015 /* Clear any selection */
1020 ui->keydragging = FALSE;
1023 #define PREFERRED_TILE_SIZE 32
1024 #define TILE_SIZE (ds->tilesize)
1025 #define BORDER (TILE_SIZE / 2)
1026 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1028 struct game_drawstate {
1029 struct game_params params;
1033 int *dsf_scratch, *border_scratch;
1036 static char *interpret_move(const game_state *state, game_ui *ui,
1037 const game_drawstate *ds,
1038 int x, int y, int button)
1040 const int w = state->shared->params.w;
1041 const int h = state->shared->params.h;
1043 const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1044 const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1052 button &= ~MOD_MASK;
1054 if (button == LEFT_BUTTON || button == LEFT_DRAG) {
1055 /* A left-click anywhere will clear the current selection. */
1056 if (button == LEFT_BUTTON) {
1062 if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
1064 ui->sel = snewn(w*h, int);
1065 memset(ui->sel, 0, w*h*sizeof(int));
1067 if (!state->shared->clues[w*ty+tx])
1068 ui->sel[w*ty+tx] = 1;
1070 ui->cur_visible = 0;
1071 return ""; /* redraw */
1074 if (IS_CURSOR_MOVE(button)) {
1075 ui->cur_visible = 1;
1076 move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, 0);
1077 if (ui->keydragging) goto select_square;
1080 if (button == CURSOR_SELECT) {
1081 if (!ui->cur_visible) {
1082 ui->cur_visible = 1;
1085 ui->keydragging = !ui->keydragging;
1086 if (!ui->keydragging) return "";
1090 ui->sel = snewn(w*h, int);
1091 memset(ui->sel, 0, w*h*sizeof(int));
1093 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1094 ui->sel[w*ui->cur_y + ui->cur_x] = 1;
1097 if (button == CURSOR_SELECT2) {
1098 if (!ui->cur_visible) {
1099 ui->cur_visible = 1;
1103 ui->sel = snewn(w*h, int);
1104 memset(ui->sel, 0, w*h*sizeof(int));
1106 ui->keydragging = FALSE;
1107 if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1108 ui->sel[w*ui->cur_y + ui->cur_x] ^= 1;
1109 for (i = 0; i < w*h && !ui->sel[i]; i++);
1117 if (button == '\b' || button == 27) {
1120 ui->keydragging = FALSE;
1124 if (button < '0' || button > '9') return NULL;
1126 if (button > (w == 2 && h == 2 ? 3 : max(w, h))) return NULL;
1127 ui->keydragging = FALSE;
1129 for (i = 0; i < w*h; i++) {
1131 if ((ui->sel && ui->sel[i]) ||
1132 (!ui->sel && ui->cur_visible && (w*ui->cur_y+ui->cur_x) == i)) {
1133 if (state->shared->clues[i] != 0) continue; /* in case cursor is on clue */
1134 if (state->board[i] != button) {
1135 sprintf(buf, "%s%d", move ? "," : "", i);
1137 move = srealloc(move, strlen(move)+strlen(buf)+1);
1140 move = smalloc(strlen(buf)+1);
1148 sprintf(buf, "_%d", button);
1149 move = srealloc(move, strlen(move)+strlen(buf)+1);
1152 if (!ui->sel) return move ? move : NULL;
1155 /* Need to update UI at least, as we cleared the selection */
1156 return move ? move : "";
1159 static game_state *execute_move(const game_state *state, const char *move)
1161 game_state *new_state = NULL;
1162 const int sz = state->shared->params.w * state->shared->params.h;
1166 new_state = dup_game(state);
1167 for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
1168 new_state->cheated = TRUE;
1171 char *endptr, *delim = strchr(move, '_');
1172 if (!delim) goto err;
1173 value = strtol(delim+1, &endptr, 0);
1174 if (*endptr || endptr == delim+1) goto err;
1175 if (value < 0 || value > 9) goto err;
1176 new_state = dup_game(state);
1178 const int i = strtol(move, &endptr, 0);
1179 if (endptr == move) goto err;
1180 if (i < 0 || i >= sz) goto err;
1181 new_state->board[i] = value;
1182 if (*endptr == '_') break;
1183 if (*endptr != ',') goto err;
1189 * Check for completion.
1191 if (!new_state->completed) {
1192 const int w = new_state->shared->params.w;
1193 const int h = new_state->shared->params.h;
1194 const int sz = w * h;
1195 int *dsf = make_dsf(NULL, new_state->board, w, h);
1197 for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
1200 new_state->completed = TRUE;
1206 if (new_state) free_game(new_state);
1210 /* ----------------------------------------------------------------------
1214 #define FLASH_TIME 0.4F
1216 #define COL_CLUE COL_GRID
1228 static void game_compute_size(const game_params *params, int tilesize,
1231 *x = (params->w + 1) * tilesize;
1232 *y = (params->h + 1) * tilesize;
1235 static void game_set_size(drawing *dr, game_drawstate *ds,
1236 const game_params *params, int tilesize)
1238 ds->tilesize = tilesize;
1241 static float *game_colours(frontend *fe, int *ncolours)
1243 float *ret = snewn(3 * NCOLOURS, float);
1245 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1247 ret[COL_GRID * 3 + 0] = 0.0F;
1248 ret[COL_GRID * 3 + 1] = 0.0F;
1249 ret[COL_GRID * 3 + 2] = 0.0F;
1251 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1252 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1253 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1255 ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
1256 ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
1257 ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
1259 ret[COL_CURSOR * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1260 ret[COL_CURSOR * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1261 ret[COL_CURSOR * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1263 ret[COL_ERROR * 3 + 0] = 1.0F;
1264 ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1265 ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1267 ret[COL_USER * 3 + 0] = 0.0F;
1268 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1269 ret[COL_USER * 3 + 2] = 0.0F;
1271 *ncolours = NCOLOURS;
1275 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1277 struct game_drawstate *ds = snew(struct game_drawstate);
1280 ds->tilesize = PREFERRED_TILE_SIZE;
1282 ds->params = state->shared->params;
1283 ds->v = snewn(ds->params.w * ds->params.h, int);
1284 ds->flags = snewn(ds->params.w * ds->params.h, int);
1285 for (i = 0; i < ds->params.w * ds->params.h; i++)
1286 ds->v[i] = ds->flags[i] = -1;
1287 ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
1288 ds->dsf_scratch = NULL;
1293 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1297 sfree(ds->border_scratch);
1298 sfree(ds->dsf_scratch);
1302 #define BORDER_U 0x001
1303 #define BORDER_D 0x002
1304 #define BORDER_L 0x004
1305 #define BORDER_R 0x008
1306 #define BORDER_UR 0x010
1307 #define BORDER_DR 0x020
1308 #define BORDER_UL 0x040
1309 #define BORDER_DL 0x080
1310 #define HIGH_BG 0x100
1311 #define CORRECT_BG 0x200
1312 #define ERROR_BG 0x400
1313 #define USER_COL 0x800
1314 #define CURSOR_SQ 0x1000
1316 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
1323 * Clip to the grid square.
1325 clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1326 TILE_SIZE, TILE_SIZE);
1332 BORDER + x*TILE_SIZE,
1333 BORDER + y*TILE_SIZE,
1336 (flags & HIGH_BG ? COL_HIGHLIGHT :
1337 flags & ERROR_BG ? COL_ERROR :
1338 flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
1341 * Draw the grid lines.
1343 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1344 BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
1345 draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1346 BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
1356 (x + 1) * TILE_SIZE,
1357 (y + 1) * TILE_SIZE,
1360 ALIGN_VCENTRE | ALIGN_HCENTRE,
1361 flags & USER_COL ? COL_USER : COL_CLUE,
1366 * Draw bold lines around the borders.
1368 if (flags & BORDER_L)
1370 BORDER + x*TILE_SIZE + 1,
1371 BORDER + y*TILE_SIZE + 1,
1375 if (flags & BORDER_U)
1377 BORDER + x*TILE_SIZE + 1,
1378 BORDER + y*TILE_SIZE + 1,
1382 if (flags & BORDER_R)
1384 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1385 BORDER + y*TILE_SIZE + 1,
1389 if (flags & BORDER_D)
1391 BORDER + x*TILE_SIZE + 1,
1392 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1396 if (flags & BORDER_UL)
1398 BORDER + x*TILE_SIZE + 1,
1399 BORDER + y*TILE_SIZE + 1,
1403 if (flags & BORDER_UR)
1405 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1406 BORDER + y*TILE_SIZE + 1,
1410 if (flags & BORDER_DL)
1412 BORDER + x*TILE_SIZE + 1,
1413 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1417 if (flags & BORDER_DR)
1419 BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1420 BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1425 if (flags & CURSOR_SQ) {
1426 int coff = TILE_SIZE/8;
1427 draw_rect_outline(dr,
1428 BORDER + x*TILE_SIZE + coff,
1429 BORDER + y*TILE_SIZE + coff,
1438 BORDER + x*TILE_SIZE,
1439 BORDER + y*TILE_SIZE,
1444 static void draw_grid(drawing *dr, game_drawstate *ds, const game_state *state,
1445 const game_ui *ui, int flashy, int borders, int shading)
1447 const int w = state->shared->params.w;
1448 const int h = state->shared->params.h;
1453 * Build a dsf for the board in its current state, to use for
1454 * highlights and hints.
1456 ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
1459 * Work out where we're putting borders between the cells.
1461 for (y = 0; y < w*h; y++)
1462 ds->border_scratch[y] = 0;
1464 for (y = 0; y < h; y++)
1465 for (x = 0; x < w; x++) {
1469 for (dx = 0; dx <= 1; dx++) {
1474 if (x+dx >= w || y+dy >= h)
1477 v1 = state->board[y*w+x];
1478 v2 = state->board[(y+dy)*w+(x+dx)];
1479 s1 = dsf_size(ds->dsf_scratch, y*w+x);
1480 s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
1483 * We only ever draw a border between two cells if
1484 * they don't have the same contents.
1488 * But in that situation, we don't always draw
1489 * a border. We do if the two cells both
1490 * contain actual numbers...
1496 * ... or if at least one of them is a
1497 * completed or overfull omino.
1506 ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
1511 * Actually do the drawing.
1513 for (y = 0; y < h; ++y)
1514 for (x = 0; x < w; ++x) {
1516 * Determine what we need to draw in this square.
1518 int i = y*w+x, v = state->board[i];
1521 if (flashy || !shading) {
1522 /* clear all background flags */
1523 } else if (ui && ui->sel && ui->sel[i]) {
1526 int size = dsf_size(ds->dsf_scratch, i);
1528 flags |= CORRECT_BG;
1532 int rt = dsf_canonify(ds->dsf_scratch, i), j;
1533 for (j = 0; j < w*h; ++j) {
1535 if (dsf_canonify(ds->dsf_scratch, j) != rt) continue;
1536 for (k = 0; k < 4; ++k) {
1537 const int xx = j % w + dx[k], yy = j / w + dy[k];
1538 if (xx >= 0 && xx < w && yy >= 0 && yy < h &&
1539 state->board[yy*w + xx] == EMPTY)
1548 if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
1552 * Borders at the very edges of the grid are
1553 * independent of the `borders' flag.
1565 if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
1567 if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
1569 if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
1571 if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
1574 if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
1576 if (y > 0 && x < w-1 &&
1577 ((ds->border_scratch[(y-1)*w+x] & 1) ||
1578 (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
1580 if (y < h-1 && x > 0 &&
1581 ((ds->border_scratch[y*w+(x-1)] & 2) ||
1582 (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
1584 if (y < h-1 && x < w-1 &&
1585 ((ds->border_scratch[y*w+(x+1)] & 2) ||
1586 (ds->border_scratch[(y+1)*w+x] & 1)))
1590 if (!state->shared->clues[y*w+x])
1593 if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
1594 draw_square(dr, ds, x, y, v, flags);
1596 ds->flags[y*w+x] = flags;
1601 static void game_redraw(drawing *dr, game_drawstate *ds,
1602 const game_state *oldstate, const game_state *state,
1603 int dir, const game_ui *ui,
1604 float animtime, float flashtime)
1606 const int w = state->shared->params.w;
1607 const int h = state->shared->params.h;
1611 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
1615 * The initial contents of the window are not guaranteed and
1616 * can vary with front ends. To be on the safe side, all games
1617 * should start by drawing a big background-colour rectangle
1618 * covering the whole window.
1620 draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
1624 * Smaller black rectangle which is the main grid.
1626 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1627 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1628 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1631 draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
1636 draw_grid(dr, ds, state, ui, flashy, TRUE, TRUE);
1639 static float game_anim_length(const game_state *oldstate,
1640 const game_state *newstate, int dir, game_ui *ui)
1645 static float game_flash_length(const game_state *oldstate,
1646 const game_state *newstate, int dir, game_ui *ui)
1650 assert(newstate->shared);
1651 assert(oldstate->shared == newstate->shared);
1652 if (!oldstate->completed && newstate->completed &&
1653 !oldstate->cheated && !newstate->cheated)
1658 static int game_status(const game_state *state)
1660 return state->completed ? +1 : 0;
1663 static int game_timing_state(const game_state *state, game_ui *ui)
1668 static void game_print_size(const game_params *params, float *x, float *y)
1673 * I'll use 6mm squares by default.
1675 game_compute_size(params, 600, &pw, &ph);
1680 static void game_print(drawing *dr, const game_state *state, int tilesize)
1682 const int w = state->shared->params.w;
1683 const int h = state->shared->params.h;
1686 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1687 game_drawstate *ds = game_new_drawstate(dr, state);
1688 game_set_size(dr, ds, NULL, tilesize);
1690 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1691 c = print_mono_colour(dr, 0); assert(c == COL_GRID);
1692 c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
1693 c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
1694 c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
1695 c = print_mono_colour(dr, 0); assert(c == COL_USER);
1700 draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1701 w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1702 h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1706 * We'll draw borders between the ominoes iff the grid is not
1707 * pristine. So scan it to see if it is.
1710 for (i = 0; i < w*h; i++)
1711 if (state->board[i] && !state->shared->clues[i])
1717 print_line_width(dr, TILE_SIZE / 64);
1718 draw_grid(dr, ds, state, NULL, FALSE, borders, FALSE);
1723 game_free_drawstate(dr, ds);
1727 #define thegame filling
1730 const struct game thegame = {
1731 "Filling", "games.filling", "filling",
1738 TRUE, game_configure, custom_params,
1746 TRUE, game_can_format_as_text_now, game_text_format,
1754 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1757 game_free_drawstate,
1762 TRUE, FALSE, game_print_size, game_print,
1763 FALSE, /* wants_statusbar */
1764 FALSE, game_timing_state,
1765 REQUIRE_NUMPAD, /* flags */
1768 #ifdef STANDALONE_SOLVER /* solver? hah! */
1770 int main(int argc, char **argv) {
1772 game_params *params;
1777 for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
1778 if (*desc == '\0') {
1779 fprintf(stderr, "bad puzzle id: %s", par);
1785 params = snew(game_params);
1786 decode_params(params, par);
1787 state = new_game(NULL, params, desc);
1788 if (solver(state->board, params->w, params->h, NULL))
1789 printf("%s:%s: solvable\n", par, desc);
1791 printf("%s:%s: not solvable\n", par, desc);
1798 /* vim: set shiftwidth=4 tabstop=8: */