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