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