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