chiark / gitweb /
Render Filling presets as 'WxH', not 'HxW'.
[sgt-puzzles.git] / filling.c
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.
4  */
5
6 /* TODO:
7  *
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.
13  *
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?
20  *
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:).
25  *
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).
29  *
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).
33  *
34  *  - prove that only w=h=2 needs a special case
35  *
36  *  - solo-like pencil marks?
37  *
38  *  - a user says that the difficulty is unevenly distributed.
39  *     + partition into levels?  Will they be non-crap?
40  *
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?
48  *
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).
59  *
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?
64  */
65
66 #include <assert.h>
67 #include <ctype.h>
68 #include <math.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73
74 #include "puzzles.h"
75
76 static unsigned char verbose;
77
78 static void printv(char *fmt, ...) {
79 #ifndef PALM
80     if (verbose) {
81         va_list va;
82         va_start(va, fmt);
83         vprintf(fmt, va);
84         va_end(va);
85     }
86 #endif
87 }
88
89 /*****************************************************************************
90  * GAME CONFIGURATION AND PARAMETERS                                         *
91  *****************************************************************************/
92
93 struct game_params {
94     int w, h;
95 };
96
97 struct shared_state {
98     struct game_params params;
99     int *clues;
100     int refcnt;
101 };
102
103 struct game_state {
104     int *board;
105     struct shared_state *shared;
106     int completed, cheated;
107 };
108
109 static const struct game_params filling_defaults[3] = {
110     {9, 7}, {13, 9}, {17, 13}
111 };
112
113 static game_params *default_params(void)
114 {
115     game_params *ret = snew(game_params);
116
117     *ret = filling_defaults[1]; /* struct copy */
118
119     return ret;
120 }
121
122 static int game_fetch_preset(int i, char **name, game_params **params)
123 {
124     char buf[64];
125
126     if (i < 0 || i >= lenof(filling_defaults)) return FALSE;
127     *params = snew(game_params);
128     **params = filling_defaults[i]; /* struct copy */
129     sprintf(buf, "%dx%d", filling_defaults[i].w, filling_defaults[i].h);
130     *name = dupstr(buf);
131
132     return TRUE;
133 }
134
135 static void free_params(game_params *params)
136 {
137     sfree(params);
138 }
139
140 static game_params *dup_params(const game_params *params)
141 {
142     game_params *ret = snew(game_params);
143     *ret = *params; /* struct copy */
144     return ret;
145 }
146
147 static void decode_params(game_params *ret, char const *string)
148 {
149     ret->w = ret->h = atoi(string);
150     while (*string && isdigit((unsigned char) *string)) ++string;
151     if (*string == 'x') ret->h = atoi(++string);
152 }
153
154 static char *encode_params(const game_params *params, int full)
155 {
156     char buf[64];
157     sprintf(buf, "%dx%d", params->w, params->h);
158     return dupstr(buf);
159 }
160
161 static config_item *game_configure(const game_params *params)
162 {
163     config_item *ret;
164     char buf[64];
165
166     ret = snewn(3, config_item);
167
168     ret[0].name = "Width";
169     ret[0].type = C_STRING;
170     sprintf(buf, "%d", params->w);
171     ret[0].sval = dupstr(buf);
172     ret[0].ival = 0;
173
174     ret[1].name = "Height";
175     ret[1].type = C_STRING;
176     sprintf(buf, "%d", params->h);
177     ret[1].sval = dupstr(buf);
178     ret[1].ival = 0;
179
180     ret[2].name = NULL;
181     ret[2].type = C_END;
182     ret[2].sval = NULL;
183     ret[2].ival = 0;
184
185     return ret;
186 }
187
188 static game_params *custom_params(const config_item *cfg)
189 {
190     game_params *ret = snew(game_params);
191
192     ret->w = atoi(cfg[0].sval);
193     ret->h = atoi(cfg[1].sval);
194
195     return ret;
196 }
197
198 static char *validate_params(const game_params *params, int full)
199 {
200     if (params->w < 1) return "Width must be at least one";
201     if (params->h < 1) return "Height must be at least one";
202
203     return NULL;
204 }
205
206 /*****************************************************************************
207  * STRINGIFICATION OF GAME STATE                                             *
208  *****************************************************************************/
209
210 #define EMPTY 0
211
212 /* Example of plaintext rendering:
213  *  +---+---+---+---+---+---+---+
214  *  | 6 |   |   | 2 |   |   | 2 |
215  *  +---+---+---+---+---+---+---+
216  *  |   | 3 |   | 6 |   | 3 |   |
217  *  +---+---+---+---+---+---+---+
218  *  | 3 |   |   |   |   |   | 1 |
219  *  +---+---+---+---+---+---+---+
220  *  |   | 2 | 3 |   | 4 | 2 |   |
221  *  +---+---+---+---+---+---+---+
222  *  | 2 |   |   |   |   |   | 3 |
223  *  +---+---+---+---+---+---+---+
224  *  |   | 5 |   | 1 |   | 4 |   |
225  *  +---+---+---+---+---+---+---+
226  *  | 4 |   |   | 3 |   |   | 3 |
227  *  +---+---+---+---+---+---+---+
228  *
229  * This puzzle instance is taken from the nikoli website
230  * Encoded (unsolved and solved), the strings are these:
231  * 7x7:6002002030603030000010230420200000305010404003003
232  * 7x7:6662232336663232331311235422255544325413434443313
233  */
234 static char *board_to_string(int *board, int w, int h) {
235     const int sz = w * h;
236     const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
237     const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
238     const int chlen = chw * chh;
239     char *repr = snewn(chlen + 1, char);
240     int i;
241
242     assert(board);
243
244     /* build the first line ("^(\+---){n}\+$") */
245     for (i = 0; i < w; ++i) {
246         repr[4*i + 0] = '+';
247         repr[4*i + 1] = '-';
248         repr[4*i + 2] = '-';
249         repr[4*i + 3] = '-';
250     }
251     repr[4*i + 0] = '+';
252     repr[4*i + 1] = '\n';
253
254     /* ... and copy it onto the odd-numbered lines */
255     for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
256
257     /* build the second line ("^(\|\t){n}\|$") */
258     for (i = 0; i < w; ++i) {
259         repr[chw + 4*i + 0] = '|';
260         repr[chw + 4*i + 1] = ' ';
261         repr[chw + 4*i + 2] = ' ';
262         repr[chw + 4*i + 3] = ' ';
263     }
264     repr[chw + 4*i + 0] = '|';
265     repr[chw + 4*i + 1] = '\n';
266
267     /* ... and copy it onto the even-numbered lines */
268     for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
269
270     /* fill in the numbers */
271     for (i = 0; i < sz; ++i) {
272         const int x = i % w;
273         const int y = i / w;
274         if (board[i] == EMPTY) continue;
275         repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
276     }
277
278     repr[chlen] = '\0';
279     return repr;
280 }
281
282 static int game_can_format_as_text_now(const game_params *params)
283 {
284     return TRUE;
285 }
286
287 static char *game_text_format(const game_state *state)
288 {
289     const int w = state->shared->params.w;
290     const int h = state->shared->params.h;
291     return board_to_string(state->board, w, h);
292 }
293
294 /*****************************************************************************
295  * GAME GENERATION AND SOLVER                                                *
296  *****************************************************************************/
297
298 static const int dx[4] = {-1, 1, 0, 0};
299 static const int dy[4] = {0, 0, -1, 1};
300
301 struct solver_state
302 {
303     int *dsf;
304     int *board;
305     int *connected;
306     int nempty;
307 };
308
309 static void print_board(int *board, int w, int h) {
310     if (verbose) {
311         char *repr = board_to_string(board, w, h);
312         printv("%s\n", repr);
313         free(repr);
314     }
315 }
316
317 static game_state *new_game(midend *, const game_params *, const char *);
318 static void free_game(game_state *);
319
320 #define SENTINEL sz
321
322 static int mark_region(int *board, int w, int h, int i, int n, int m) {
323     int j;
324
325     board[i] = -1;
326
327     for (j = 0; j < 4; ++j) {
328         const int x = (i % w) + dx[j], y = (i / w) + dy[j], ii = w*y + x;
329         if (x < 0 || x >= w || y < 0 || y >= h) continue;
330         if (board[ii] == m) return FALSE;
331         if (board[ii] != n) continue;
332         if (!mark_region(board, w, h, ii, n, m)) return FALSE;
333     }
334     return TRUE;
335 }
336
337 static int region_size(int *board, int w, int h, int i) {
338     const int sz = w * h;
339     int j, size, copy;
340     if (board[i] == 0) return 0;
341     copy = board[i];
342     mark_region(board, w, h, i, board[i], SENTINEL);
343     for (size = j = 0; j < sz; ++j) {
344         if (board[j] != -1) continue;
345         ++size;
346         board[j] = copy;
347     }
348     return size;
349 }
350
351 static void merge_ones(int *board, int w, int h)
352 {
353     const int sz = w * h;
354     const int maxsize = min(max(max(w, h), 3), 9);
355     int i, j, k, change;
356     do {
357         change = FALSE;
358         for (i = 0; i < sz; ++i) {
359             if (board[i] != 1) continue;
360
361             for (j = 0; j < 4; ++j, board[i] = 1) {
362                 const int x = (i % w) + dx[j], y = (i / w) + dy[j];
363                 int oldsize, newsize, ok, ii = w*y + x;
364                 if (x < 0 || x >= w || y < 0 || y >= h) continue;
365                 if (board[ii] == maxsize) continue;
366
367                 oldsize = board[ii];
368                 board[i] = oldsize;
369                 newsize = region_size(board, w, h, i);
370
371                 if (newsize > maxsize) continue;
372
373                 ok = mark_region(board, w, h, i, oldsize, newsize);
374
375                 for (k = 0; k < sz; ++k)
376                     if (board[k] == -1)
377                         board[k] = ok ? newsize : oldsize;
378
379                 if (ok) break;
380             }
381             if (j < 4) change = TRUE;
382         }
383     } while (change);
384 }
385
386 /* generate a random valid board; uses validate_board. */
387 static void make_board(int *board, int w, int h, random_state *rs) {
388     const int sz = w * h;
389
390     /* w=h=2 is a special case which requires a number > max(w, h) */
391     /* TODO prove that this is the case ONLY for w=h=2. */
392     const int maxsize = min(max(max(w, h), 3), 9);
393
394     /* Note that if 1 in {w, h} then it's impossible to have a region
395      * of size > w*h, so the special case only affects w=h=2. */
396
397     int i, change, *dsf;
398
399     assert(w >= 1);
400     assert(h >= 1);
401     assert(board);
402
403     /* I abuse the board variable: when generating the puzzle, it
404      * contains a shuffled list of numbers {0, ..., sz-1}. */
405     for (i = 0; i < sz; ++i) board[i] = i;
406
407     dsf = snewn(sz, int);
408 retry:
409     dsf_init(dsf, sz);
410     shuffle(board, sz, sizeof (int), rs);
411
412     do {
413         change = FALSE; /* as long as the board potentially has errors */
414         for (i = 0; i < sz; ++i) {
415             const int square = dsf_canonify(dsf, board[i]);
416             const int size = dsf_size(dsf, square);
417             int merge = SENTINEL, min = maxsize - size + 1, error = FALSE;
418             int neighbour, neighbour_size, j;
419
420             for (j = 0; j < 4; ++j) {
421                 const int x = (board[i] % w) + dx[j];
422                 const int y = (board[i] / w) + dy[j];
423                 if (x < 0 || x >= w || y < 0 || y >= h) continue;
424
425                 neighbour = dsf_canonify(dsf, w*y + x);
426                 if (square == neighbour) continue;
427
428                 neighbour_size = dsf_size(dsf, neighbour);
429                 if (size == neighbour_size) error = TRUE;
430
431                 /* find the smallest neighbour to merge with, which
432                  * wouldn't make the region too large.  (This is
433                  * guaranteed by the initial value of `min'.) */
434                 if (neighbour_size < min) {
435                     min = neighbour_size;
436                     merge = neighbour;
437                 }
438             }
439
440             /* if this square is not in error, leave it be */
441             if (!error) continue;
442
443             /* if it is, but we can't fix it, retry the whole board.
444              * Maybe we could fix it by merging the conflicting
445              * neighbouring region(s) into some of their neighbours,
446              * but just restarting works out fine. */
447             if (merge == SENTINEL) goto retry;
448
449             /* merge with the smallest neighbouring workable region. */
450             dsf_merge(dsf, square, merge);
451             change = TRUE;
452         }
453     } while (change);
454
455     for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
456     merge_ones(board, w, h);
457
458     sfree(dsf);
459 }
460
461 static void merge(int *dsf, int *connected, int a, int b) {
462     int c;
463     assert(dsf);
464     assert(connected);
465     a = dsf_canonify(dsf, a);
466     b = dsf_canonify(dsf, b);
467     if (a == b) return;
468     dsf_merge(dsf, a, b);
469     c = connected[a];
470     connected[a] = connected[b];
471     connected[b] = c;
472 }
473
474 static void *memdup(const void *ptr, size_t len, size_t esz) {
475     void *dup = smalloc(len * esz);
476     assert(ptr);
477     memcpy(dup, ptr, len * esz);
478     return dup;
479 }
480
481 static void expand(struct solver_state *s, int w, int h, int t, int f) {
482     int j;
483     assert(s);
484     assert(s->board[t] == EMPTY); /* expand to empty square */
485     assert(s->board[f] != EMPTY); /* expand from non-empty square */
486     printv(
487         "learn: expanding %d from (%d, %d) into (%d, %d)\n",
488         s->board[f], f % w, f / w, t % w, t / w);
489     s->board[t] = s->board[f];
490     for (j = 0; j < 4; ++j) {
491         const int x = (t % w) + dx[j];
492         const int y = (t / w) + dy[j];
493         const int idx = w*y + x;
494         if (x < 0 || x >= w || y < 0 || y >= h) continue;
495         if (s->board[idx] != s->board[t]) continue;
496         merge(s->dsf, s->connected, t, idx);
497     }
498     --s->nempty;
499 }
500
501 static void clear_count(int *board, int sz) {
502     int i;
503     for (i = 0; i < sz; ++i) {
504         if (board[i] >= 0) continue;
505         else if (board[i] == -SENTINEL) board[i] = EMPTY;
506         else board[i] = -board[i];
507     }
508 }
509
510 static void flood_count(int *board, int w, int h, int i, int n, int *c) {
511     const int sz = w * h;
512     int k;
513
514     if (board[i] == EMPTY) board[i] = -SENTINEL;
515     else if (board[i] == n) board[i] = -board[i];
516     else return;
517
518     if (--*c == 0) return;
519
520     for (k = 0; k < 4; ++k) {
521         const int x = (i % w) + dx[k];
522         const int y = (i / w) + dy[k];
523         const int idx = w*y + x;
524         if (x < 0 || x >= w || y < 0 || y >= h) continue;
525         flood_count(board, w, h, idx, n, c);
526         if (*c == 0) return;
527     }
528 }
529
530 static int check_capacity(int *board, int w, int h, int i) {
531     int n = board[i];
532     flood_count(board, w, h, i, board[i], &n);
533     clear_count(board, w * h);
534     return n == 0;
535 }
536
537 static int expandsize(const int *board, int *dsf, int w, int h, int i, int n) {
538     int j;
539     int nhits = 0;
540     int hits[4];
541     int size = 1;
542     for (j = 0; j < 4; ++j) {
543         const int x = (i % w) + dx[j];
544         const int y = (i / w) + dy[j];
545         const int idx = w*y + x;
546         int root;
547         int m;
548         if (x < 0 || x >= w || y < 0 || y >= h) continue;
549         if (board[idx] != n) continue;
550         root = dsf_canonify(dsf, idx);
551         for (m = 0; m < nhits && root != hits[m]; ++m);
552         if (m < nhits) continue;
553         printv("\t  (%d, %d) contrib %d to size\n", x, y, dsf[root] >> 2);
554         size += dsf_size(dsf, root);
555         assert(dsf_size(dsf, root) >= 1);
556         hits[nhits++] = root;
557     }
558     return size;
559 }
560
561 /*
562  *  +---+---+---+---+---+---+---+
563  *  | 6 |   |   | 2 |   |   | 2 |
564  *  +---+---+---+---+---+---+---+
565  *  |   | 3 |   | 6 |   | 3 |   |
566  *  +---+---+---+---+---+---+---+
567  *  | 3 |   |   |   |   |   | 1 |
568  *  +---+---+---+---+---+---+---+
569  *  |   | 2 | 3 |   | 4 | 2 |   |
570  *  +---+---+---+---+---+---+---+
571  *  | 2 |   |   |   |   |   | 3 |
572  *  +---+---+---+---+---+---+---+
573  *  |   | 5 |   | 1 |   | 4 |   |
574  *  +---+---+---+---+---+---+---+
575  *  | 4 |   |   | 3 |   |   | 3 |
576  *  +---+---+---+---+---+---+---+
577  */
578
579 /* Solving techniques:
580  *
581  * CONNECTED COMPONENT FORCED EXPANSION (too big):
582  * When a CC can only be expanded in one direction, because all the
583  * other ones would make the CC too big.
584  *  +---+---+---+---+---+
585  *  | 2 | 2 |   | 2 | _ |
586  *  +---+---+---+---+---+
587  *
588  * CONNECTED COMPONENT FORCED EXPANSION (too small):
589  * When a CC must include a particular square, because otherwise there
590  * would not be enough room to complete it.  This includes squares not
591  * adjacent to the CC through learn_critical_square.
592  *  +---+---+
593  *  | 2 | _ |
594  *  +---+---+
595  *
596  * DROPPING IN A ONE:
597  * When an empty square has no neighbouring empty squares and only a 1
598  * will go into the square (or other CCs would be too big).
599  *  +---+---+---+
600  *  | 2 | 2 | _ |
601  *  +---+---+---+
602  *
603  * TODO: generalise DROPPING IN A ONE: find the size of the CC of
604  * empty squares and a list of all adjacent numbers.  See if only one
605  * number in {1, ..., size} u {all adjacent numbers} is possible.
606  * Probably this is only effective for a CC size < n for some n (4?)
607  *
608  * TODO: backtracking.
609  */
610
611 static void filled_square(struct solver_state *s, int w, int h, int i) {
612     int j;
613     for (j = 0; j < 4; ++j) {
614         const int x = (i % w) + dx[j];
615         const int y = (i / w) + dy[j];
616         const int idx = w*y + x;
617         if (x < 0 || x >= w || y < 0 || y >= h) continue;
618         if (s->board[i] == s->board[idx])
619             merge(s->dsf, s->connected, i, idx);
620     }
621 }
622
623 static void init_solver_state(struct solver_state *s, int w, int h) {
624     const int sz = w * h;
625     int i;
626     assert(s);
627
628     s->nempty = 0;
629     for (i = 0; i < sz; ++i) s->connected[i] = i;
630     for (i = 0; i < sz; ++i)
631         if (s->board[i] == EMPTY) ++s->nempty;
632         else filled_square(s, w, h, i);
633 }
634
635 static int learn_expand_or_one(struct solver_state *s, int w, int h) {
636     const int sz = w * h;
637     int i;
638     int learn = FALSE;
639
640     assert(s);
641
642     for (i = 0; i < sz; ++i) {
643         int j;
644         int one = TRUE;
645
646         if (s->board[i] != EMPTY) continue;
647
648         for (j = 0; j < 4; ++j) {
649             const int x = (i % w) + dx[j];
650             const int y = (i / w) + dy[j];
651             const int idx = w*y + x;
652             if (x < 0 || x >= w || y < 0 || y >= h) continue;
653             if (s->board[idx] == EMPTY) {
654                 one = FALSE;
655                 continue;
656             }
657             if (one &&
658                 (s->board[idx] == 1 ||
659                  (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
660                                               i, s->board[idx]))))
661                 one = FALSE;
662             if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
663             assert(s->board[i] == EMPTY);
664             s->board[i] = -SENTINEL;
665             if (check_capacity(s->board, w, h, idx)) continue;
666             assert(s->board[i] == EMPTY);
667             printv("learn: expanding in one\n");
668             expand(s, w, h, i, idx);
669             learn = TRUE;
670             break;
671         }
672
673         if (j == 4 && one) {
674             printv("learn: one at (%d, %d)\n", i % w, i / w);
675             assert(s->board[i] == EMPTY);
676             s->board[i] = 1;
677             assert(s->nempty);
678             --s->nempty;
679             learn = TRUE;
680         }
681     }
682     return learn;
683 }
684
685 static int learn_blocked_expansion(struct solver_state *s, int w, int h) {
686     const int sz = w * h;
687     int i;
688     int learn = FALSE;
689
690     assert(s);
691     /* for every connected component */
692     for (i = 0; i < sz; ++i) {
693         int exp = SENTINEL;
694         int j;
695
696         if (s->board[i] == EMPTY) continue;
697         j = dsf_canonify(s->dsf, i);
698
699         /* (but only for each connected component) */
700         if (i != j) continue;
701
702         /* (and not if it's already complete) */
703         if (dsf_size(s->dsf, j) == s->board[j]) continue;
704
705         /* for each square j _in_ the connected component */
706         do {
707             int k;
708             printv("  looking at (%d, %d)\n", j % w, j / w);
709
710             /* for each neighbouring square (idx) */
711             for (k = 0; k < 4; ++k) {
712                 const int x = (j % w) + dx[k];
713                 const int y = (j / w) + dy[k];
714                 const int idx = w*y + x;
715                 int size;
716                 /* int l;
717                    int nhits = 0;
718                    int hits[4]; */
719                 if (x < 0 || x >= w || y < 0 || y >= h) continue;
720                 if (s->board[idx] != EMPTY) continue;
721                 if (exp == idx) continue;
722                 printv("\ttrying to expand onto (%d, %d)\n", x, y);
723
724                 /* find out the would-be size of the new connected
725                  * component if we actually expanded into idx */
726                 /*
727                 size = 1;
728                 for (l = 0; l < 4; ++l) {
729                     const int lx = x + dx[l];
730                     const int ly = y + dy[l];
731                     const int idxl = w*ly + lx;
732                     int root;
733                     int m;
734                     if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
735                     if (board[idxl] != board[j]) continue;
736                     root = dsf_canonify(dsf, idxl);
737                     for (m = 0; m < nhits && root != hits[m]; ++m);
738                     if (m != nhits) continue;
739                     // printv("\t  (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
740                     size += dsf_size(dsf, root);
741                     assert(dsf_size(dsf, root) >= 1);
742                     hits[nhits++] = root;
743                 }
744                 */
745
746                 size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
747
748                 /* ... and see if that size is too big, or if we
749                  * have other expansion candidates.  Otherwise
750                  * remember the (so far) only candidate. */
751
752                 printv("\tthat would give a size of %d\n", size);
753                 if (size > s->board[j]) continue;
754                 /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
755                 if (exp != SENTINEL) goto next_i;
756                 assert(exp != idx);
757                 exp = idx;
758             }
759
760             j = s->connected[j]; /* next square in the same CC */
761             assert(s->board[i] == s->board[j]);
762         } while (j != i);
763         /* end: for each square j _in_ the connected component */
764
765         if (exp == SENTINEL) continue;
766         printv("learning to expand\n");
767         expand(s, w, h, exp, i);
768         learn = TRUE;
769
770         next_i:
771         ;
772     }
773     /* end: for each connected component */
774     return learn;
775 }
776
777 static int learn_critical_square(struct solver_state *s, int w, int h) {
778     const int sz = w * h;
779     int i;
780     int learn = FALSE;
781     assert(s);
782
783     /* for each connected component */
784     for (i = 0; i < sz; ++i) {
785         int j, slack;
786         if (s->board[i] == EMPTY) continue;
787         if (i != dsf_canonify(s->dsf, i)) continue;
788         slack = s->board[i] - dsf_size(s->dsf, i);
789         if (slack == 0) continue;
790         assert(s->board[i] != 1);
791         /* for each empty square */
792         for (j = 0; j < sz; ++j) {
793             if (s->board[j] == EMPTY) {
794                 /* if it's too far away from the CC, don't bother */
795                 int k = i, jx = j % w, jy = j / w;
796                 do {
797                     int kx = k % w, ky = k / w;
798                     if (abs(kx - jx) + abs(ky - jy) <= slack) break;
799                     k = s->connected[k];
800                 } while (i != k);
801                 if (i == k) continue; /* not within range */
802             } else continue;
803             s->board[j] = -SENTINEL;
804             if (check_capacity(s->board, w, h, i)) continue;
805             /* if not expanding s->board[i] to s->board[j] implies
806              * that s->board[i] can't reach its full size, ... */
807             assert(s->nempty);
808             printv(
809                 "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
810                 s->board[i], j % w, j / w, i % w, i / w);
811             --s->nempty;
812             s->board[j] = s->board[i];
813             filled_square(s, w, h, j);
814             learn = TRUE;
815         }
816     }
817     return learn;
818 }
819
820 static int solver(const int *orig, int w, int h, char **solution) {
821     const int sz = w * h;
822
823     struct solver_state ss;
824     ss.board = memdup(orig, sz, sizeof (int));
825     ss.dsf = snew_dsf(sz); /* eqv classes: connected components */
826     ss.connected = snewn(sz, int); /* connected[n] := n.next; */
827     /* cyclic disjoint singly linked lists, same partitioning as dsf.
828      * The lists lets you iterate over a partition given any member */
829
830     printv("trying to solve this:\n");
831     print_board(ss.board, w, h);
832
833     init_solver_state(&ss, w, h);
834     do {
835         if (learn_blocked_expansion(&ss, w, h)) continue;
836         if (learn_expand_or_one(&ss, w, h)) continue;
837         if (learn_critical_square(&ss, w, h)) continue;
838         break;
839     } while (ss.nempty);
840
841     printv("best guess:\n");
842     print_board(ss.board, w, h);
843
844     if (solution) {
845         int i;
846         *solution = snewn(sz + 2, char);
847         **solution = 's';
848         for (i = 0; i < sz; ++i) (*solution)[i + 1] = ss.board[i] + '0';
849         (*solution)[sz + 1] = '\0';
850         /* We don't need the \0 for execute_move (the only user)
851          * I'm just being printf-friendly in case I wanna print */
852     }
853
854     sfree(ss.dsf);
855     sfree(ss.board);
856     sfree(ss.connected);
857
858     return !ss.nempty;
859 }
860
861 static int *make_dsf(int *dsf, int *board, const int w, const int h) {
862     const int sz = w * h;
863     int i;
864
865     if (!dsf)
866         dsf = snew_dsf(w * h);
867     else
868         dsf_init(dsf, w * h);
869
870     for (i = 0; i < sz; ++i) {
871         int j;
872         for (j = 0; j < 4; ++j) {
873             const int x = (i % w) + dx[j];
874             const int y = (i / w) + dy[j];
875             const int k = w*y + x;
876             if (x < 0 || x >= w || y < 0 || y >= h) continue;
877             if (board[i] == board[k]) dsf_merge(dsf, i, k);
878         }
879     }
880     return dsf;
881 }
882
883 static void minimize_clue_set(int *board, int w, int h, random_state *rs)
884 {
885     const int sz = w * h;
886     int *shuf = snewn(sz, int), i;
887
888     for (i = 0; i < sz; ++i) shuf[i] = i;
889     shuffle(shuf, sz, sizeof (int), rs);
890
891     /* the solver is monotone, so a second pass is superfluous. */
892     for (i = 0; i < sz; ++i) {
893         int tmp = board[shuf[i]];
894         board[shuf[i]] = EMPTY;
895         if (!solver(board, w, h, NULL)) board[shuf[i]] = tmp;
896     }
897
898     sfree(shuf);
899 }
900
901 static char *new_game_desc(const game_params *params, random_state *rs,
902                            char **aux, int interactive)
903 {
904     const int w = params->w, h = params->h, sz = w * h;
905     int *board = snewn(sz, int), i;
906     char *game_description = snewn(sz + 1, char);
907
908     make_board(board, w, h, rs);
909     minimize_clue_set(board, w, h, rs);
910
911     for (i = 0; i < sz; ++i) {
912         assert(board[i] >= 0);
913         assert(board[i] < 10);
914         game_description[i] = board[i] + '0';
915     }
916     game_description[sz] = '\0';
917
918     sfree(board);
919
920     return game_description;
921 }
922
923 static char *validate_desc(const game_params *params, const char *desc)
924 {
925     int i;
926     const int sz = params->w * params->h;
927     const char m = '0' + max(max(params->w, params->h), 3);
928
929     printv("desc = '%s'; sz = %d\n", desc, sz);
930
931     for (i = 0; desc[i] && i < sz; ++i)
932         if (!isdigit((unsigned char) *desc))
933             return "non-digit in string";
934         else if (desc[i] > m)
935             return "too large digit in string";
936     if (desc[i]) return "string too long";
937     else if (i < sz) return "string too short";
938     return NULL;
939 }
940
941 static game_state *new_game(midend *me, const game_params *params,
942                             const char *desc)
943 {
944     game_state *state = snew(game_state);
945     int sz = params->w * params->h;
946     int i;
947
948     state->cheated = state->completed = FALSE;
949     state->shared = snew(struct shared_state);
950     state->shared->refcnt = 1;
951     state->shared->params = *params; /* struct copy */
952     state->shared->clues = snewn(sz, int);
953     for (i = 0; i < sz; ++i) state->shared->clues[i] = desc[i] - '0';
954     state->board = memdup(state->shared->clues, sz, sizeof (int));
955
956     return state;
957 }
958
959 static game_state *dup_game(const game_state *state)
960 {
961     const int sz = state->shared->params.w * state->shared->params.h;
962     game_state *ret = snew(game_state);
963
964     ret->board = memdup(state->board, sz, sizeof (int));
965     ret->shared = state->shared;
966     ret->cheated = state->cheated;
967     ret->completed = state->completed;
968     ++ret->shared->refcnt;
969
970     return ret;
971 }
972
973 static void free_game(game_state *state)
974 {
975     assert(state);
976     sfree(state->board);
977     if (--state->shared->refcnt == 0) {
978         sfree(state->shared->clues);
979         sfree(state->shared);
980     }
981     sfree(state);
982 }
983
984 static char *solve_game(const game_state *state, const game_state *currstate,
985                         const char *aux, char **error)
986 {
987     if (aux == NULL) {
988         const int w = state->shared->params.w;
989         const int h = state->shared->params.h;
990         char *new_aux;
991         if (!solver(state->board, w, h, &new_aux))
992             *error = "Sorry, I couldn't find a solution";
993         return new_aux;
994     }
995     return dupstr(aux);
996 }
997
998 /*****************************************************************************
999  * USER INTERFACE STATE AND ACTION                                           *
1000  *****************************************************************************/
1001
1002 struct game_ui {
1003     int *sel; /* w*h highlighted squares, or NULL */
1004     int cur_x, cur_y, cur_visible, keydragging;
1005 };
1006
1007 static game_ui *new_ui(const game_state *state)
1008 {
1009     game_ui *ui = snew(game_ui);
1010
1011     ui->sel = NULL;
1012     ui->cur_x = ui->cur_y = ui->cur_visible = ui->keydragging = 0;
1013
1014     return ui;
1015 }
1016
1017 static void free_ui(game_ui *ui)
1018 {
1019     if (ui->sel)
1020         sfree(ui->sel);
1021     sfree(ui);
1022 }
1023
1024 static char *encode_ui(const game_ui *ui)
1025 {
1026     return NULL;
1027 }
1028
1029 static void decode_ui(game_ui *ui, const char *encoding)
1030 {
1031 }
1032
1033 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1034                                const game_state *newstate)
1035 {
1036     /* Clear any selection */
1037     if (ui->sel) {
1038         sfree(ui->sel);
1039         ui->sel = NULL;
1040     }
1041     ui->keydragging = FALSE;
1042 }
1043
1044 #define PREFERRED_TILE_SIZE 32
1045 #define TILE_SIZE (ds->tilesize)
1046 #define BORDER (TILE_SIZE / 2)
1047 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1048
1049 struct game_drawstate {
1050     struct game_params params;
1051     int tilesize;
1052     int started;
1053     int *v, *flags;
1054     int *dsf_scratch, *border_scratch;
1055 };
1056
1057 static char *interpret_move(const game_state *state, game_ui *ui,
1058                             const game_drawstate *ds,
1059                             int x, int y, int button)
1060 {
1061     const int w = state->shared->params.w;
1062     const int h = state->shared->params.h;
1063
1064     const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1065     const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1066
1067     char *move = NULL;
1068     int i;
1069
1070     assert(ui);
1071     assert(ds);
1072
1073     button &= ~MOD_MASK;
1074
1075     if (button == LEFT_BUTTON || button == LEFT_DRAG) {
1076         /* A left-click anywhere will clear the current selection. */
1077         if (button == LEFT_BUTTON) {
1078             if (ui->sel) {
1079                 sfree(ui->sel);
1080                 ui->sel = NULL;
1081             }
1082         }
1083         if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
1084             if (!ui->sel) {
1085                 ui->sel = snewn(w*h, int);
1086                 memset(ui->sel, 0, w*h*sizeof(int));
1087             }
1088             if (!state->shared->clues[w*ty+tx])
1089                 ui->sel[w*ty+tx] = 1;
1090         }
1091         ui->cur_visible = 0;
1092         return ""; /* redraw */
1093     }
1094
1095     if (IS_CURSOR_MOVE(button)) {
1096         ui->cur_visible = 1;
1097         move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, 0);
1098         if (ui->keydragging) goto select_square;
1099         return "";
1100     }
1101     if (button == CURSOR_SELECT) {
1102         if (!ui->cur_visible) {
1103             ui->cur_visible = 1;
1104             return "";
1105         }
1106         ui->keydragging = !ui->keydragging;
1107         if (!ui->keydragging) return "";
1108
1109       select_square:
1110         if (!ui->sel) {
1111             ui->sel = snewn(w*h, int);
1112             memset(ui->sel, 0, w*h*sizeof(int));
1113         }
1114         if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1115             ui->sel[w*ui->cur_y + ui->cur_x] = 1;
1116         return "";
1117     }
1118     if (button == CURSOR_SELECT2) {
1119         if (!ui->cur_visible) {
1120             ui->cur_visible = 1;
1121             return "";
1122         }
1123         if (!ui->sel) {
1124             ui->sel = snewn(w*h, int);
1125             memset(ui->sel, 0, w*h*sizeof(int));
1126         }
1127         ui->keydragging = FALSE;
1128         if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
1129             ui->sel[w*ui->cur_y + ui->cur_x] ^= 1;
1130         for (i = 0; i < w*h && !ui->sel[i]; i++);
1131         if (i == w*h) {
1132             sfree(ui->sel);
1133             ui->sel = NULL;
1134         }
1135         return "";
1136     }
1137
1138     if (button == '\b' || button == 27) {
1139         sfree(ui->sel);
1140         ui->sel = NULL;
1141         ui->keydragging = FALSE;
1142         return "";
1143     }
1144
1145     if (button < '0' || button > '9') return NULL;
1146     button -= '0';
1147     if (button > (w == 2 && h == 2 ? 3 : max(w, h))) return NULL;
1148     ui->keydragging = FALSE;
1149
1150     for (i = 0; i < w*h; i++) {
1151         char buf[32];
1152         if ((ui->sel && ui->sel[i]) ||
1153             (!ui->sel && ui->cur_visible && (w*ui->cur_y+ui->cur_x) == i)) {
1154             if (state->shared->clues[i] != 0) continue; /* in case cursor is on clue */
1155             if (state->board[i] != button) {
1156                 sprintf(buf, "%s%d", move ? "," : "", i);
1157                 if (move) {
1158                     move = srealloc(move, strlen(move)+strlen(buf)+1);
1159                     strcat(move, buf);
1160                 } else {
1161                     move = smalloc(strlen(buf)+1);
1162                     strcpy(move, buf);
1163                 }
1164             }
1165         }
1166     }
1167     if (move) {
1168         char buf[32];
1169         sprintf(buf, "_%d", button);
1170         move = srealloc(move, strlen(move)+strlen(buf)+1);
1171         strcat(move, buf);
1172     }
1173     if (!ui->sel) return move ? move : NULL;
1174     sfree(ui->sel);
1175     ui->sel = NULL;
1176     /* Need to update UI at least, as we cleared the selection */
1177     return move ? move : "";
1178 }
1179
1180 static game_state *execute_move(const game_state *state, const char *move)
1181 {
1182     game_state *new_state = NULL;
1183     const int sz = state->shared->params.w * state->shared->params.h;
1184
1185     if (*move == 's') {
1186         int i = 0;
1187         new_state = dup_game(state);
1188         for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
1189         new_state->cheated = TRUE;
1190     } else {
1191         int value;
1192         char *endptr, *delim = strchr(move, '_');
1193         if (!delim) goto err;
1194         value = strtol(delim+1, &endptr, 0);
1195         if (*endptr || endptr == delim+1) goto err;
1196         if (value < 0 || value > 9) goto err;
1197         new_state = dup_game(state);
1198         while (*move) {
1199             const int i = strtol(move, &endptr, 0);
1200             if (endptr == move) goto err;
1201             if (i < 0 || i >= sz) goto err;
1202             new_state->board[i] = value;
1203             if (*endptr == '_') break;
1204             if (*endptr != ',') goto err;
1205             move = endptr + 1;
1206         }
1207     }
1208
1209     /*
1210      * Check for completion.
1211      */
1212     if (!new_state->completed) {
1213         const int w = new_state->shared->params.w;
1214         const int h = new_state->shared->params.h;
1215         const int sz = w * h;
1216         int *dsf = make_dsf(NULL, new_state->board, w, h);
1217         int i;
1218         for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
1219         sfree(dsf);
1220         if (i == sz)
1221             new_state->completed = TRUE;
1222     }
1223
1224     return new_state;
1225
1226 err:
1227     if (new_state) free_game(new_state);
1228     return NULL;
1229 }
1230
1231 /* ----------------------------------------------------------------------
1232  * Drawing routines.
1233  */
1234
1235 #define FLASH_TIME 0.4F
1236
1237 #define COL_CLUE COL_GRID
1238 enum {
1239     COL_BACKGROUND,
1240     COL_GRID,
1241     COL_HIGHLIGHT,
1242     COL_CORRECT,
1243     COL_ERROR,
1244     COL_USER,
1245     COL_CURSOR,
1246     NCOLOURS
1247 };
1248
1249 static void game_compute_size(const game_params *params, int tilesize,
1250                               int *x, int *y)
1251 {
1252     *x = (params->w + 1) * tilesize;
1253     *y = (params->h + 1) * tilesize;
1254 }
1255
1256 static void game_set_size(drawing *dr, game_drawstate *ds,
1257                           const game_params *params, int tilesize)
1258 {
1259     ds->tilesize = tilesize;
1260 }
1261
1262 static float *game_colours(frontend *fe, int *ncolours)
1263 {
1264     float *ret = snewn(3 * NCOLOURS, float);
1265
1266     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1267
1268     ret[COL_GRID * 3 + 0] = 0.0F;
1269     ret[COL_GRID * 3 + 1] = 0.0F;
1270     ret[COL_GRID * 3 + 2] = 0.0F;
1271
1272     ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1273     ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1274     ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1275
1276     ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
1277     ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
1278     ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
1279
1280     ret[COL_CURSOR * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1281     ret[COL_CURSOR * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1282     ret[COL_CURSOR * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1283
1284     ret[COL_ERROR * 3 + 0] = 1.0F;
1285     ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1286     ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1287
1288     ret[COL_USER * 3 + 0] = 0.0F;
1289     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1290     ret[COL_USER * 3 + 2] = 0.0F;
1291
1292     *ncolours = NCOLOURS;
1293     return ret;
1294 }
1295
1296 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1297 {
1298     struct game_drawstate *ds = snew(struct game_drawstate);
1299     int i;
1300
1301     ds->tilesize = PREFERRED_TILE_SIZE;
1302     ds->started = 0;
1303     ds->params = state->shared->params;
1304     ds->v = snewn(ds->params.w * ds->params.h, int);
1305     ds->flags = snewn(ds->params.w * ds->params.h, int);
1306     for (i = 0; i < ds->params.w * ds->params.h; i++)
1307         ds->v[i] = ds->flags[i] = -1;
1308     ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
1309     ds->dsf_scratch = NULL;
1310
1311     return ds;
1312 }
1313
1314 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1315 {
1316     sfree(ds->v);
1317     sfree(ds->flags);
1318     sfree(ds->border_scratch);
1319     sfree(ds->dsf_scratch);
1320     sfree(ds);
1321 }
1322
1323 #define BORDER_U   0x001
1324 #define BORDER_D   0x002
1325 #define BORDER_L   0x004
1326 #define BORDER_R   0x008
1327 #define BORDER_UR  0x010
1328 #define BORDER_DR  0x020
1329 #define BORDER_UL  0x040
1330 #define BORDER_DL  0x080
1331 #define HIGH_BG    0x100
1332 #define CORRECT_BG 0x200
1333 #define ERROR_BG   0x400
1334 #define USER_COL   0x800
1335 #define CURSOR_SQ 0x1000
1336
1337 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
1338                         int n, int flags)
1339 {
1340     assert(dr);
1341     assert(ds);
1342
1343     /*
1344      * Clip to the grid square.
1345      */
1346     clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1347          TILE_SIZE, TILE_SIZE);
1348
1349     /*
1350      * Clear the square.
1351      */
1352     draw_rect(dr,
1353               BORDER + x*TILE_SIZE,
1354               BORDER + y*TILE_SIZE,
1355               TILE_SIZE,
1356               TILE_SIZE,
1357               (flags & HIGH_BG ? COL_HIGHLIGHT :
1358                flags & ERROR_BG ? COL_ERROR :
1359                flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
1360
1361     /*
1362      * Draw the grid lines.
1363      */
1364     draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1365               BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
1366     draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
1367               BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
1368
1369     /*
1370      * Draw the number.
1371      */
1372     if (n) {
1373         char buf[2];
1374         buf[0] = n + '0';
1375         buf[1] = '\0';
1376         draw_text(dr,
1377                   (x + 1) * TILE_SIZE,
1378                   (y + 1) * TILE_SIZE,
1379                   FONT_VARIABLE,
1380                   TILE_SIZE / 2,
1381                   ALIGN_VCENTRE | ALIGN_HCENTRE,
1382                   flags & USER_COL ? COL_USER : COL_CLUE,
1383                   buf);
1384     }
1385
1386     /*
1387      * Draw bold lines around the borders.
1388      */
1389     if (flags & BORDER_L)
1390         draw_rect(dr,
1391                   BORDER + x*TILE_SIZE + 1,
1392                   BORDER + y*TILE_SIZE + 1,
1393                   BORDER_WIDTH,
1394                   TILE_SIZE - 1,
1395                   COL_GRID);
1396     if (flags & BORDER_U)
1397         draw_rect(dr,
1398                   BORDER + x*TILE_SIZE + 1,
1399                   BORDER + y*TILE_SIZE + 1,
1400                   TILE_SIZE - 1,
1401                   BORDER_WIDTH,
1402                   COL_GRID);
1403     if (flags & BORDER_R)
1404         draw_rect(dr,
1405                   BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1406                   BORDER + y*TILE_SIZE + 1,
1407                   BORDER_WIDTH,
1408                   TILE_SIZE - 1,
1409                   COL_GRID);
1410     if (flags & BORDER_D)
1411         draw_rect(dr,
1412                   BORDER + x*TILE_SIZE + 1,
1413                   BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1414                   TILE_SIZE - 1,
1415                   BORDER_WIDTH,
1416                   COL_GRID);
1417     if (flags & BORDER_UL)
1418         draw_rect(dr,
1419                   BORDER + x*TILE_SIZE + 1,
1420                   BORDER + y*TILE_SIZE + 1,
1421                   BORDER_WIDTH,
1422                   BORDER_WIDTH,
1423                   COL_GRID);
1424     if (flags & BORDER_UR)
1425         draw_rect(dr,
1426                   BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1427                   BORDER + y*TILE_SIZE + 1,
1428                   BORDER_WIDTH,
1429                   BORDER_WIDTH,
1430                   COL_GRID);
1431     if (flags & BORDER_DL)
1432         draw_rect(dr,
1433                   BORDER + x*TILE_SIZE + 1,
1434                   BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1435                   BORDER_WIDTH,
1436                   BORDER_WIDTH,
1437                   COL_GRID);
1438     if (flags & BORDER_DR)
1439         draw_rect(dr,
1440                   BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
1441                   BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
1442                   BORDER_WIDTH,
1443                   BORDER_WIDTH,
1444                   COL_GRID);
1445
1446     if (flags & CURSOR_SQ) {
1447         int coff = TILE_SIZE/8;
1448         draw_rect_outline(dr,
1449                           BORDER + x*TILE_SIZE + coff,
1450                           BORDER + y*TILE_SIZE + coff,
1451                           TILE_SIZE - coff*2,
1452                           TILE_SIZE - coff*2,
1453                           COL_CURSOR);
1454     }
1455
1456     unclip(dr);
1457
1458     draw_update(dr,
1459                 BORDER + x*TILE_SIZE,
1460                 BORDER + y*TILE_SIZE,
1461                 TILE_SIZE,
1462                 TILE_SIZE);
1463 }
1464
1465 static void draw_grid(drawing *dr, game_drawstate *ds, const game_state *state,
1466                       const game_ui *ui, int flashy, int borders, int shading)
1467 {
1468     const int w = state->shared->params.w;
1469     const int h = state->shared->params.h;
1470     int x;
1471     int y;
1472
1473     /*
1474      * Build a dsf for the board in its current state, to use for
1475      * highlights and hints.
1476      */
1477     ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
1478
1479     /*
1480      * Work out where we're putting borders between the cells.
1481      */
1482     for (y = 0; y < w*h; y++)
1483         ds->border_scratch[y] = 0;
1484
1485     for (y = 0; y < h; y++)
1486         for (x = 0; x < w; x++) {
1487             int dx, dy;
1488             int v1, s1, v2, s2;
1489
1490             for (dx = 0; dx <= 1; dx++) {
1491                 int border = FALSE;
1492
1493                 dy = 1 - dx;
1494
1495                 if (x+dx >= w || y+dy >= h)
1496                     continue;
1497
1498                 v1 = state->board[y*w+x];
1499                 v2 = state->board[(y+dy)*w+(x+dx)];
1500                 s1 = dsf_size(ds->dsf_scratch, y*w+x);
1501                 s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
1502
1503                 /*
1504                  * We only ever draw a border between two cells if
1505                  * they don't have the same contents.
1506                  */
1507                 if (v1 != v2) {
1508                     /*
1509                      * But in that situation, we don't always draw
1510                      * a border. We do if the two cells both
1511                      * contain actual numbers...
1512                      */
1513                     if (v1 && v2)
1514                         border = TRUE;
1515
1516                     /*
1517                      * ... or if at least one of them is a
1518                      * completed or overfull omino.
1519                      */
1520                     if (v1 && s1 >= v1)
1521                         border = TRUE;
1522                     if (v2 && s2 >= v2)
1523                         border = TRUE;
1524                 }
1525
1526                 if (border)
1527                     ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
1528             }
1529         }
1530
1531     /*
1532      * Actually do the drawing.
1533      */
1534     for (y = 0; y < h; ++y)
1535         for (x = 0; x < w; ++x) {
1536             /*
1537              * Determine what we need to draw in this square.
1538              */
1539             int i = y*w+x, v = state->board[i];
1540             int flags = 0;
1541
1542             if (flashy || !shading) {
1543                 /* clear all background flags */
1544             } else if (ui && ui->sel && ui->sel[i]) {
1545                 flags |= HIGH_BG;
1546             } else if (v) {
1547                 int size = dsf_size(ds->dsf_scratch, i);
1548                 if (size == v)
1549                     flags |= CORRECT_BG;
1550                 else if (size > v)
1551                     flags |= ERROR_BG;
1552                 else {
1553                     int rt = dsf_canonify(ds->dsf_scratch, i), j;
1554                     for (j = 0; j < w*h; ++j) {
1555                         int k;
1556                         if (dsf_canonify(ds->dsf_scratch, j) != rt) continue;
1557                         for (k = 0; k < 4; ++k) {
1558                             const int xx = j % w + dx[k], yy = j / w + dy[k];
1559                             if (xx >= 0 && xx < w && yy >= 0 && yy < h &&
1560                                 state->board[yy*w + xx] == EMPTY)
1561                                 goto noflag;
1562                         }
1563                     }
1564                     flags |= ERROR_BG;
1565                   noflag:
1566                     ;
1567                 }
1568             }
1569             if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
1570               flags |= CURSOR_SQ;
1571
1572             /*
1573              * Borders at the very edges of the grid are
1574              * independent of the `borders' flag.
1575              */
1576             if (x == 0)
1577                 flags |= BORDER_L;
1578             if (y == 0)
1579                 flags |= BORDER_U;
1580             if (x == w-1)
1581                 flags |= BORDER_R;
1582             if (y == h-1)
1583                 flags |= BORDER_D;
1584
1585             if (borders) {
1586                 if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
1587                     flags |= BORDER_L;
1588                 if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
1589                     flags |= BORDER_U;
1590                 if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
1591                     flags |= BORDER_R;
1592                 if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
1593                     flags |= BORDER_D;
1594
1595                 if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
1596                     flags |= BORDER_UL;
1597                 if (y > 0 && x < w-1 &&
1598                     ((ds->border_scratch[(y-1)*w+x] & 1) ||
1599                      (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
1600                     flags |= BORDER_UR;
1601                 if (y < h-1 && x > 0 &&
1602                     ((ds->border_scratch[y*w+(x-1)] & 2) ||
1603                      (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
1604                     flags |= BORDER_DL;
1605                 if (y < h-1 && x < w-1 &&
1606                     ((ds->border_scratch[y*w+(x+1)] & 2) ||
1607                      (ds->border_scratch[(y+1)*w+x] & 1)))
1608                     flags |= BORDER_DR;
1609             }
1610
1611             if (!state->shared->clues[y*w+x])
1612                 flags |= USER_COL;
1613
1614             if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
1615                 draw_square(dr, ds, x, y, v, flags);
1616                 ds->v[y*w+x] = v;
1617                 ds->flags[y*w+x] = flags;
1618             }
1619         }
1620 }
1621
1622 static void game_redraw(drawing *dr, game_drawstate *ds,
1623                         const game_state *oldstate, const game_state *state,
1624                         int dir, const game_ui *ui,
1625                         float animtime, float flashtime)
1626 {
1627     const int w = state->shared->params.w;
1628     const int h = state->shared->params.h;
1629
1630     const int flashy =
1631         flashtime > 0 &&
1632         (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
1633
1634     if (!ds->started) {
1635         /*
1636          * The initial contents of the window are not guaranteed and
1637          * can vary with front ends. To be on the safe side, all games
1638          * should start by drawing a big background-colour rectangle
1639          * covering the whole window.
1640          */
1641         draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
1642                   COL_BACKGROUND);
1643
1644         /*
1645          * Smaller black rectangle which is the main grid.
1646          */
1647         draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1648                   w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1649                   h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1650                   COL_GRID);
1651
1652         draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
1653
1654         ds->started = TRUE;
1655     }
1656
1657     draw_grid(dr, ds, state, ui, flashy, TRUE, TRUE);
1658 }
1659
1660 static float game_anim_length(const game_state *oldstate,
1661                               const game_state *newstate, int dir, game_ui *ui)
1662 {
1663     return 0.0F;
1664 }
1665
1666 static float game_flash_length(const game_state *oldstate,
1667                                const game_state *newstate, int dir, game_ui *ui)
1668 {
1669     assert(oldstate);
1670     assert(newstate);
1671     assert(newstate->shared);
1672     assert(oldstate->shared == newstate->shared);
1673     if (!oldstate->completed && newstate->completed &&
1674         !oldstate->cheated && !newstate->cheated)
1675         return FLASH_TIME;
1676     return 0.0F;
1677 }
1678
1679 static int game_status(const game_state *state)
1680 {
1681     return state->completed ? +1 : 0;
1682 }
1683
1684 static int game_timing_state(const game_state *state, game_ui *ui)
1685 {
1686     return TRUE;
1687 }
1688
1689 static void game_print_size(const game_params *params, float *x, float *y)
1690 {
1691     int pw, ph;
1692
1693     /*
1694      * I'll use 6mm squares by default.
1695      */
1696     game_compute_size(params, 600, &pw, &ph);
1697     *x = pw / 100.0F;
1698     *y = ph / 100.0F;
1699 }
1700
1701 static void game_print(drawing *dr, const game_state *state, int tilesize)
1702 {
1703     const int w = state->shared->params.w;
1704     const int h = state->shared->params.h;
1705     int c, i, borders;
1706
1707     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1708     game_drawstate *ds = game_new_drawstate(dr, state);
1709     game_set_size(dr, ds, NULL, tilesize);
1710
1711     c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1712     c = print_mono_colour(dr, 0); assert(c == COL_GRID);
1713     c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
1714     c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
1715     c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
1716     c = print_mono_colour(dr, 0); assert(c == COL_USER);
1717
1718     /*
1719      * Border.
1720      */
1721     draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
1722               w*TILE_SIZE + 2*BORDER_WIDTH + 1,
1723               h*TILE_SIZE + 2*BORDER_WIDTH + 1,
1724               COL_GRID);
1725
1726     /*
1727      * We'll draw borders between the ominoes iff the grid is not
1728      * pristine. So scan it to see if it is.
1729      */
1730     borders = FALSE;
1731     for (i = 0; i < w*h; i++)
1732         if (state->board[i] && !state->shared->clues[i])
1733             borders = TRUE;
1734
1735     /*
1736      * Draw grid.
1737      */
1738     print_line_width(dr, TILE_SIZE / 64);
1739     draw_grid(dr, ds, state, NULL, FALSE, borders, FALSE);
1740
1741     /*
1742      * Clean up.
1743      */
1744     game_free_drawstate(dr, ds);
1745 }
1746
1747 #ifdef COMBINED
1748 #define thegame filling
1749 #endif
1750
1751 const struct game thegame = {
1752     "Filling", "games.filling", "filling",
1753     default_params,
1754     game_fetch_preset,
1755     decode_params,
1756     encode_params,
1757     free_params,
1758     dup_params,
1759     TRUE, game_configure, custom_params,
1760     validate_params,
1761     new_game_desc,
1762     validate_desc,
1763     new_game,
1764     dup_game,
1765     free_game,
1766     TRUE, solve_game,
1767     TRUE, game_can_format_as_text_now, game_text_format,
1768     new_ui,
1769     free_ui,
1770     encode_ui,
1771     decode_ui,
1772     game_changed_state,
1773     interpret_move,
1774     execute_move,
1775     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1776     game_colours,
1777     game_new_drawstate,
1778     game_free_drawstate,
1779     game_redraw,
1780     game_anim_length,
1781     game_flash_length,
1782     game_status,
1783     TRUE, FALSE, game_print_size, game_print,
1784     FALSE,                                 /* wants_statusbar */
1785     FALSE, game_timing_state,
1786     REQUIRE_NUMPAD,                    /* flags */
1787 };
1788
1789 #ifdef STANDALONE_SOLVER /* solver? hah! */
1790
1791 int main(int argc, char **argv) {
1792     while (*++argv) {
1793         game_params *params;
1794         game_state *state;
1795         char *par;
1796         char *desc;
1797
1798         for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
1799         if (*desc == '\0') {
1800             fprintf(stderr, "bad puzzle id: %s", par);
1801             continue;
1802         }
1803
1804         *desc++ = '\0';
1805
1806         params = snew(game_params);
1807         decode_params(params, par);
1808         state = new_game(NULL, params, desc);
1809         if (solver(state->board, params->w, params->h, NULL))
1810             printf("%s:%s: solvable\n", par, desc);
1811         else
1812             printf("%s:%s: not solvable\n", par, desc);
1813     }
1814     return 0;
1815 }
1816
1817 #endif
1818
1819 /* vim: set shiftwidth=4 tabstop=8: */