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