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