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