chiark / gitweb /
New infrastructure feature. Games are now permitted to be
[sgt-puzzles.git] / rect.c
1 /*
2  * rect.c: Puzzle from nikoli.co.jp. You have a square grid with
3  * numbers in some squares; you must divide the square grid up into
4  * variously sized rectangles, such that every rectangle contains
5  * exactly one numbered square and the area of each rectangle is
6  * equal to the number contained in it.
7  */
8
9 /*
10  * TODO:
11  * 
12  *  - Improve singleton removal.
13  *     + It would be nice to limit the size of the generated
14  *       rectangles in accordance with existing constraints such as
15  *       the maximum rectangle size and the one about not
16  *       generating a rectangle the full width or height of the
17  *       grid.
18  *     + This could be achieved by making a less random choice
19  *       about which of the available options to use.
20  *     + Alternatively, we could create our rectangle and then
21  *       split it up.
22  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <ctype.h>
29 #include <math.h>
30
31 #include "puzzles.h"
32
33 enum {
34     COL_BACKGROUND,
35     COL_CORRECT,
36     COL_LINE,
37     COL_TEXT,
38     COL_GRID,
39     COL_DRAG,
40     NCOLOURS
41 };
42
43 struct game_params {
44     int w, h;
45     float expandfactor;
46     int unique;
47 };
48
49 #define INDEX(state, x, y)    (((y) * (state)->w) + (x))
50 #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
51 #define grid(state,x,y)       index(state, (state)->grid, x, y)
52 #define vedge(state,x,y)      index(state, (state)->vedge, x, y)
53 #define hedge(state,x,y)      index(state, (state)->hedge, x, y)
54
55 #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
56                                 (y) >= dy && (y) < (state)->h )
57 #define RANGE(state,x,y)  CRANGE(state,x,y,0,0)
58 #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
59 #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
60
61 #define PREFERRED_TILE_SIZE 24
62 #define TILE_SIZE (ds->tilesize)
63 #ifdef SMALL_SCREEN
64 #define BORDER (2)
65 #else
66 #define BORDER (TILE_SIZE * 3 / 4)
67 #endif
68
69 #define CORNER_TOLERANCE 0.15F
70 #define CENTRE_TOLERANCE 0.15F
71
72 #define FLASH_TIME 0.13F
73
74 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
75 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
76
77 struct game_state {
78     int w, h;
79     int *grid;                         /* contains the numbers */
80     unsigned char *vedge;              /* (w+1) x h */
81     unsigned char *hedge;              /* w x (h+1) */
82     int completed, cheated;
83     unsigned char *correct;
84 };
85
86 static game_params *default_params(void)
87 {
88     game_params *ret = snew(game_params);
89
90     ret->w = ret->h = 7;
91     ret->expandfactor = 0.0F;
92     ret->unique = TRUE;
93
94     return ret;
95 }
96
97 static int game_fetch_preset(int i, char **name, game_params **params)
98 {
99     game_params *ret;
100     int w, h;
101     char buf[80];
102
103     switch (i) {
104       case 0: w = 7, h = 7; break;
105       case 1: w = 9, h = 9; break;
106       case 2: w = 11, h = 11; break;
107       case 3: w = 13, h = 13; break;
108       case 4: w = 15, h = 15; break;
109 #ifndef SMALL_SCREEN
110       case 5: w = 17, h = 17; break;
111       case 6: w = 19, h = 19; break;
112 #endif
113       default: return FALSE;
114     }
115
116     sprintf(buf, "%dx%d", w, h);
117     *name = dupstr(buf);
118     *params = ret = snew(game_params);
119     ret->w = w;
120     ret->h = h;
121     ret->expandfactor = 0.0F;
122     ret->unique = TRUE;
123     return TRUE;
124 }
125
126 static void free_params(game_params *params)
127 {
128     sfree(params);
129 }
130
131 static game_params *dup_params(game_params *params)
132 {
133     game_params *ret = snew(game_params);
134     *ret = *params;                    /* structure copy */
135     return ret;
136 }
137
138 static void decode_params(game_params *ret, char const *string)
139 {
140     ret->w = ret->h = atoi(string);
141     while (*string && isdigit((unsigned char)*string)) string++;
142     if (*string == 'x') {
143         string++;
144         ret->h = atoi(string);
145         while (*string && isdigit((unsigned char)*string)) string++;
146     }
147     if (*string == 'e') {
148         string++;
149         ret->expandfactor = atof(string);
150         while (*string &&
151                (*string == '.' || isdigit((unsigned char)*string))) string++;
152     }
153     if (*string == 'a') {
154         string++;
155         ret->unique = FALSE;
156     }
157 }
158
159 static char *encode_params(game_params *params, int full)
160 {
161     char data[256];
162
163     sprintf(data, "%dx%d", params->w, params->h);
164     if (full && params->expandfactor)
165         sprintf(data + strlen(data), "e%g", params->expandfactor);
166     if (full && !params->unique)
167         strcat(data, "a");
168
169     return dupstr(data);
170 }
171
172 static config_item *game_configure(game_params *params)
173 {
174     config_item *ret;
175     char buf[80];
176
177     ret = snewn(5, config_item);
178
179     ret[0].name = "Width";
180     ret[0].type = C_STRING;
181     sprintf(buf, "%d", params->w);
182     ret[0].sval = dupstr(buf);
183     ret[0].ival = 0;
184
185     ret[1].name = "Height";
186     ret[1].type = C_STRING;
187     sprintf(buf, "%d", params->h);
188     ret[1].sval = dupstr(buf);
189     ret[1].ival = 0;
190
191     ret[2].name = "Expansion factor";
192     ret[2].type = C_STRING;
193     sprintf(buf, "%g", params->expandfactor);
194     ret[2].sval = dupstr(buf);
195     ret[2].ival = 0;
196
197     ret[3].name = "Ensure unique solution";
198     ret[3].type = C_BOOLEAN;
199     ret[3].sval = NULL;
200     ret[3].ival = params->unique;
201
202     ret[4].name = NULL;
203     ret[4].type = C_END;
204     ret[4].sval = NULL;
205     ret[4].ival = 0;
206
207     return ret;
208 }
209
210 static game_params *custom_params(config_item *cfg)
211 {
212     game_params *ret = snew(game_params);
213
214     ret->w = atoi(cfg[0].sval);
215     ret->h = atoi(cfg[1].sval);
216     ret->expandfactor = atof(cfg[2].sval);
217     ret->unique = cfg[3].ival;
218
219     return ret;
220 }
221
222 static char *validate_params(game_params *params, int full)
223 {
224     if (params->w <= 0 || params->h <= 0)
225         return "Width and height must both be greater than zero";
226     if (params->w*params->h < 2)
227         return "Grid area must be greater than one";
228     if (params->expandfactor < 0.0F)
229         return "Expansion factor may not be negative";
230     return NULL;
231 }
232
233 struct point {
234     int x, y;
235 };
236
237 struct rect {
238     int x, y;
239     int w, h;
240 };
241
242 struct rectlist {
243     struct rect *rects;
244     int n;
245 };
246
247 struct numberdata {
248     int area;
249     int npoints;
250     struct point *points;
251 };
252
253 /* ----------------------------------------------------------------------
254  * Solver for Rectangles games.
255  * 
256  * This solver is souped up beyond the needs of actually _solving_
257  * a puzzle. It is also designed to cope with uncertainty about
258  * where the numbers have been placed. This is because I run it on
259  * my generated grids _before_ placing the numbers, and have it
260  * tell me where I need to place the numbers to ensure a unique
261  * solution.
262  */
263
264 static void remove_rect_placement(int w, int h,
265                                   struct rectlist *rectpositions,
266                                   int *overlaps,
267                                   int rectnum, int placement)
268 {
269     int x, y, xx, yy;
270
271 #ifdef SOLVER_DIAGNOSTICS
272     printf("ruling out rect %d placement at %d,%d w=%d h=%d\n", rectnum,
273            rectpositions[rectnum].rects[placement].x,
274            rectpositions[rectnum].rects[placement].y,
275            rectpositions[rectnum].rects[placement].w,
276            rectpositions[rectnum].rects[placement].h);
277 #endif
278
279     /*
280      * Decrement each entry in the overlaps array to reflect the
281      * removal of this rectangle placement.
282      */
283     for (yy = 0; yy < rectpositions[rectnum].rects[placement].h; yy++) {
284         y = yy + rectpositions[rectnum].rects[placement].y;
285         for (xx = 0; xx < rectpositions[rectnum].rects[placement].w; xx++) {
286             x = xx + rectpositions[rectnum].rects[placement].x;
287
288             assert(overlaps[(rectnum * h + y) * w + x] != 0);
289
290             if (overlaps[(rectnum * h + y) * w + x] > 0)
291                 overlaps[(rectnum * h + y) * w + x]--;
292         }
293     }
294
295     /*
296      * Remove the placement from the list of positions for that
297      * rectangle, by interchanging it with the one on the end.
298      */
299     if (placement < rectpositions[rectnum].n - 1) {
300         struct rect t;
301
302         t = rectpositions[rectnum].rects[rectpositions[rectnum].n - 1];
303         rectpositions[rectnum].rects[rectpositions[rectnum].n - 1] =
304             rectpositions[rectnum].rects[placement];
305         rectpositions[rectnum].rects[placement] = t;
306     }
307     rectpositions[rectnum].n--;
308 }
309
310 static void remove_number_placement(int w, int h, struct numberdata *number,
311                                     int index, int *rectbyplace)
312 {
313     /*
314      * Remove the entry from the rectbyplace array.
315      */
316     rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
317
318     /*
319      * Remove the placement from the list of candidates for that
320      * number, by interchanging it with the one on the end.
321      */
322     if (index < number->npoints - 1) {
323         struct point t;
324
325         t = number->points[number->npoints - 1];
326         number->points[number->npoints - 1] = number->points[index];
327         number->points[index] = t;
328     }
329     number->npoints--;
330 }
331
332 /*
333  * Returns 0 for failure to solve due to inconsistency; 1 for
334  * success; 2 for failure to complete a solution due to either
335  * ambiguity or it being too difficult.
336  */
337 static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
338                        unsigned char *hedge, unsigned char *vedge,
339                        random_state *rs)
340 {
341     struct rectlist *rectpositions;
342     int *overlaps, *rectbyplace, *workspace;
343     int i, ret;
344
345     /*
346      * Start by setting up a list of candidate positions for each
347      * rectangle.
348      */
349     rectpositions = snewn(nrects, struct rectlist);
350     for (i = 0; i < nrects; i++) {
351         int rw, rh, area = numbers[i].area;
352         int j, minx, miny, maxx, maxy;
353         struct rect *rlist;
354         int rlistn, rlistsize;
355
356         /*
357          * For each rectangle, begin by finding the bounding
358          * rectangle of its candidate number placements.
359          */
360         maxx = maxy = -1;
361         minx = w;
362         miny = h;
363         for (j = 0; j < numbers[i].npoints; j++) {
364             if (minx > numbers[i].points[j].x) minx = numbers[i].points[j].x;
365             if (miny > numbers[i].points[j].y) miny = numbers[i].points[j].y;
366             if (maxx < numbers[i].points[j].x) maxx = numbers[i].points[j].x;
367             if (maxy < numbers[i].points[j].y) maxy = numbers[i].points[j].y;
368         }
369
370         /*
371          * Now loop over all possible rectangle placements
372          * overlapping a point within that bounding rectangle;
373          * ensure each one actually contains a candidate number
374          * placement, and add it to the list.
375          */
376         rlist = NULL;
377         rlistn = rlistsize = 0;
378
379         for (rw = 1; rw <= area && rw <= w; rw++) {
380             int x, y;
381
382             if (area % rw)
383                 continue;
384             rh = area / rw;
385             if (rh > h)
386                 continue;
387
388             for (y = miny - rh + 1; y <= maxy; y++) {
389                 if (y < 0 || y+rh > h)
390                     continue;
391
392                 for (x = minx - rw + 1; x <= maxx; x++) {
393                     if (x < 0 || x+rw > w)
394                         continue;
395
396                     /*
397                      * See if we can find a candidate number
398                      * placement within this rectangle.
399                      */
400                     for (j = 0; j < numbers[i].npoints; j++)
401                         if (numbers[i].points[j].x >= x &&
402                             numbers[i].points[j].x < x+rw &&
403                             numbers[i].points[j].y >= y &&
404                             numbers[i].points[j].y < y+rh)
405                             break;
406
407                     if (j < numbers[i].npoints) {
408                         /*
409                          * Add this to the list of candidate
410                          * placements for this rectangle.
411                          */
412                         if (rlistn >= rlistsize) {
413                             rlistsize = rlistn + 32;
414                             rlist = sresize(rlist, rlistsize, struct rect);
415                         }
416                         rlist[rlistn].x = x;
417                         rlist[rlistn].y = y;
418                         rlist[rlistn].w = rw;
419                         rlist[rlistn].h = rh;
420 #ifdef SOLVER_DIAGNOSTICS
421                         printf("rect %d [area %d]: candidate position at"
422                                " %d,%d w=%d h=%d\n",
423                                i, area, x, y, rw, rh);
424 #endif
425                         rlistn++;
426                     }
427                 }
428             }
429         }
430
431         rectpositions[i].rects = rlist;
432         rectpositions[i].n = rlistn;
433     }
434
435     /*
436      * Next, construct a multidimensional array tracking how many
437      * candidate positions for each rectangle overlap each square.
438      * 
439      * Indexing of this array is by the formula
440      * 
441      *   overlaps[(rectindex * h + y) * w + x]
442      * 
443      * A positive or zero value indicates what it sounds as if it
444      * should; -1 indicates that this square _cannot_ be part of
445      * this rectangle; and -2 indicates that it _definitely_ is
446      * (which is distinct from 1, because one might very well know
447      * that _if_ square S is part of rectangle R then it must be
448      * because R is placed in a certain position without knowing
449      * that it definitely _is_).
450      */
451     overlaps = snewn(nrects * w * h, int);
452     memset(overlaps, 0, nrects * w * h * sizeof(int));
453     for (i = 0; i < nrects; i++) {
454         int j;
455
456         for (j = 0; j < rectpositions[i].n; j++) {
457             int xx, yy;
458
459             for (yy = 0; yy < rectpositions[i].rects[j].h; yy++)
460                 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++)
461                     overlaps[(i * h + yy+rectpositions[i].rects[j].y) * w +
462                              xx+rectpositions[i].rects[j].x]++;
463         }
464     }
465
466     /*
467      * Also we want an array covering the grid once, to make it
468      * easy to figure out which squares are candidate number
469      * placements for which rectangles. (The existence of this
470      * single array assumes that no square starts off as a
471      * candidate number placement for more than one rectangle. This
472      * assumption is justified, because this solver is _either_
473      * used to solve real problems - in which case there is a
474      * single placement for every number - _or_ used to decide on
475      * number placements for a new puzzle, in which case each
476      * number's placements are confined to the intended position of
477      * the rectangle containing that number.)
478      */
479     rectbyplace = snewn(w * h, int);
480     for (i = 0; i < w*h; i++)
481         rectbyplace[i] = -1;
482
483     for (i = 0; i < nrects; i++) {
484         int j;
485
486         for (j = 0; j < numbers[i].npoints; j++) {
487             int x = numbers[i].points[j].x;
488             int y = numbers[i].points[j].y;
489
490             assert(rectbyplace[y * w + x] == -1);
491             rectbyplace[y * w + x] = i;
492         }
493     }
494
495     workspace = snewn(nrects, int);
496
497     /*
498      * Now run the actual deduction loop.
499      */
500     while (1) {
501         int done_something = FALSE;
502
503 #ifdef SOLVER_DIAGNOSTICS
504         printf("starting deduction loop\n");
505
506         for (i = 0; i < nrects; i++) {
507             printf("rect %d overlaps:\n", i);
508             {
509                 int x, y;
510                 for (y = 0; y < h; y++) {
511                     for (x = 0; x < w; x++) {
512                         printf("%3d", overlaps[(i * h + y) * w + x]);
513                     }
514                     printf("\n");
515                 }
516             }
517         }
518         printf("rectbyplace:\n");
519         {
520             int x, y;
521             for (y = 0; y < h; y++) {
522                 for (x = 0; x < w; x++) {
523                     printf("%3d", rectbyplace[y * w + x]);
524                 }
525                 printf("\n");
526             }
527         }
528 #endif
529
530         /*
531          * Housekeeping. Look for rectangles whose number has only
532          * one candidate position left, and mark that square as
533          * known if it isn't already.
534          */
535         for (i = 0; i < nrects; i++) {
536             if (numbers[i].npoints == 1) {
537                 int x = numbers[i].points[0].x;
538                 int y = numbers[i].points[0].y;
539                 if (overlaps[(i * h + y) * w + x] >= -1) {
540                     int j;
541
542                     if (overlaps[(i * h + y) * w + x] <= 0) {
543                         ret = 0;       /* inconsistency */
544                         goto cleanup;
545                     }
546 #ifdef SOLVER_DIAGNOSTICS
547                     printf("marking %d,%d as known for rect %d"
548                            " (sole remaining number position)\n", x, y, i);
549 #endif
550
551                     for (j = 0; j < nrects; j++)
552                         overlaps[(j * h + y) * w + x] = -1;
553                     
554                     overlaps[(i * h + y) * w + x] = -2;
555                 }
556             }
557         }
558
559         /*
560          * Now look at the intersection of all possible placements
561          * for each rectangle, and mark all squares in that
562          * intersection as known for that rectangle if they aren't
563          * already.
564          */
565         for (i = 0; i < nrects; i++) {
566             int minx, miny, maxx, maxy, xx, yy, j;
567
568             minx = miny = 0;
569             maxx = w;
570             maxy = h;
571
572             for (j = 0; j < rectpositions[i].n; j++) {
573                 int x = rectpositions[i].rects[j].x;
574                 int y = rectpositions[i].rects[j].y;
575                 int w = rectpositions[i].rects[j].w;
576                 int h = rectpositions[i].rects[j].h;
577
578                 if (minx < x) minx = x;
579                 if (miny < y) miny = y;
580                 if (maxx > x+w) maxx = x+w;
581                 if (maxy > y+h) maxy = y+h;
582             }
583
584             for (yy = miny; yy < maxy; yy++)
585                 for (xx = minx; xx < maxx; xx++)
586                     if (overlaps[(i * h + yy) * w + xx] >= -1) {
587                         if (overlaps[(i * h + yy) * w + xx] <= 0) {
588                             ret = 0;   /* inconsistency */
589                             goto cleanup;
590                         }
591 #ifdef SOLVER_DIAGNOSTICS
592                         printf("marking %d,%d as known for rect %d"
593                                " (intersection of all placements)\n",
594                                xx, yy, i);
595 #endif
596
597                         for (j = 0; j < nrects; j++)
598                             overlaps[(j * h + yy) * w + xx] = -1;
599                     
600                         overlaps[(i * h + yy) * w + xx] = -2;
601                     }
602         }
603
604         /*
605          * Rectangle-focused deduction. Look at each rectangle in
606          * turn and try to rule out some of its candidate
607          * placements.
608          */
609         for (i = 0; i < nrects; i++) {
610             int j;
611
612             for (j = 0; j < rectpositions[i].n; j++) {
613                 int xx, yy, k;
614                 int del = FALSE;
615
616                 for (k = 0; k < nrects; k++)
617                     workspace[k] = 0;
618
619                 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
620                     int y = yy + rectpositions[i].rects[j].y;
621                     for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
622                         int x = xx + rectpositions[i].rects[j].x;
623  
624                         if (overlaps[(i * h + y) * w + x] == -1) {
625                             /*
626                              * This placement overlaps a square
627                              * which is _known_ to be part of
628                              * another rectangle. Therefore we must
629                              * rule it out.
630                              */
631 #ifdef SOLVER_DIAGNOSTICS
632                             printf("rect %d placement at %d,%d w=%d h=%d "
633                                    "contains %d,%d which is known-other\n", i,
634                                    rectpositions[i].rects[j].x,
635                                    rectpositions[i].rects[j].y,
636                                    rectpositions[i].rects[j].w,
637                                    rectpositions[i].rects[j].h,
638                                    x, y);
639 #endif
640                             del = TRUE;
641                         }
642
643                         if (rectbyplace[y * w + x] != -1) {
644                             /*
645                              * This placement overlaps one of the
646                              * candidate number placements for some
647                              * rectangle. Count it.
648                              */
649                             workspace[rectbyplace[y * w + x]]++;
650                         }
651                     }
652                 }
653
654                 if (!del) {
655                     /*
656                      * If we haven't ruled this placement out
657                      * already, see if it overlaps _all_ of the
658                      * candidate number placements for any
659                      * rectangle. If so, we can rule it out.
660                      */
661                     for (k = 0; k < nrects; k++)
662                         if (k != i && workspace[k] == numbers[k].npoints) {
663 #ifdef SOLVER_DIAGNOSTICS
664                             printf("rect %d placement at %d,%d w=%d h=%d "
665                                    "contains all number points for rect %d\n",
666                                    i,
667                                    rectpositions[i].rects[j].x,
668                                    rectpositions[i].rects[j].y,
669                                    rectpositions[i].rects[j].w,
670                                    rectpositions[i].rects[j].h,
671                                    k);
672 #endif
673                             del = TRUE;
674                             break;
675                         }
676
677                     /*
678                      * Failing that, see if it overlaps at least
679                      * one of the candidate number placements for
680                      * itself! (This might not be the case if one
681                      * of those number placements has been removed
682                      * recently.).
683                      */
684                     if (!del && workspace[i] == 0) {
685 #ifdef SOLVER_DIAGNOSTICS
686                         printf("rect %d placement at %d,%d w=%d h=%d "
687                                "contains none of its own number points\n",
688                                i,
689                                rectpositions[i].rects[j].x,
690                                rectpositions[i].rects[j].y,
691                                rectpositions[i].rects[j].w,
692                                rectpositions[i].rects[j].h);
693 #endif
694                         del = TRUE;
695                     }
696                 }
697
698                 if (del) {
699                     remove_rect_placement(w, h, rectpositions, overlaps, i, j);
700
701                     j--;               /* don't skip over next placement */
702
703                     done_something = TRUE;
704                 }
705             }
706         }
707
708         /*
709          * Square-focused deduction. Look at each square not marked
710          * as known, and see if there are any which can only be
711          * part of a single rectangle.
712          */
713         {
714             int x, y, n, index;
715             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
716                 /* Known squares are marked as <0 everywhere, so we only need
717                  * to check the overlaps entry for rect 0. */
718                 if (overlaps[y * w + x] < 0)
719                     continue;          /* known already */
720
721                 n = 0;
722                 index = -1;
723                 for (i = 0; i < nrects; i++)
724                     if (overlaps[(i * h + y) * w + x] > 0)
725                         n++, index = i;
726
727                 if (n == 1) {
728                     int j;
729
730                     /*
731                      * Now we can rule out all placements for
732                      * rectangle `index' which _don't_ contain
733                      * square x,y.
734                      */
735 #ifdef SOLVER_DIAGNOSTICS
736                     printf("square %d,%d can only be in rectangle %d\n",
737                            x, y, index);
738 #endif
739                     for (j = 0; j < rectpositions[index].n; j++) {
740                         struct rect *r = &rectpositions[index].rects[j];
741                         if (x >= r->x && x < r->x + r->w &&
742                             y >= r->y && y < r->y + r->h)
743                             continue;  /* this one is OK */
744                         remove_rect_placement(w, h, rectpositions, overlaps,
745                                               index, j);
746                         j--;           /* don't skip over next placement */
747                         done_something = TRUE;
748                     }
749                 }
750             }
751         }
752
753         /*
754          * If we've managed to deduce anything by normal means,
755          * loop round again and see if there's more to be done.
756          * Only if normal deduction has completely failed us should
757          * we now move on to narrowing down the possible number
758          * placements.
759          */
760         if (done_something)
761             continue;
762
763         /*
764          * Now we have done everything we can with the current set
765          * of number placements. So we need to winnow the number
766          * placements so as to narrow down the possibilities. We do
767          * this by searching for a candidate placement (of _any_
768          * rectangle) which overlaps a candidate placement of the
769          * number for some other rectangle.
770          */
771         if (rs) {
772             struct rpn {
773                 int rect;
774                 int placement;
775                 int number;
776             } *rpns = NULL;
777             size_t nrpns = 0, rpnsize = 0;
778             int j;
779
780             for (i = 0; i < nrects; i++) {
781                 for (j = 0; j < rectpositions[i].n; j++) {
782                     int xx, yy;
783
784                     for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
785                         int y = yy + rectpositions[i].rects[j].y;
786                         for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
787                             int x = xx + rectpositions[i].rects[j].x;
788
789                             if (rectbyplace[y * w + x] >= 0 &&
790                                 rectbyplace[y * w + x] != i) {
791                                 /*
792                                  * Add this to the list of
793                                  * winnowing possibilities.
794                                  */
795                                 if (nrpns >= rpnsize) {
796                                     rpnsize = rpnsize * 3 / 2 + 32;
797                                     rpns = sresize(rpns, rpnsize, struct rpn);
798                                 }
799                                 rpns[nrpns].rect = i;
800                                 rpns[nrpns].placement = j;
801                                 rpns[nrpns].number = rectbyplace[y * w + x];
802                                 nrpns++;
803                             }
804                         }
805                     }
806  
807                 }
808             }
809
810 #ifdef SOLVER_DIAGNOSTICS
811             printf("%d candidate rect placements we could eliminate\n", nrpns);
812 #endif
813             if (nrpns > 0) {
814                 /*
815                  * Now choose one of these unwanted rectangle
816                  * placements, and eliminate it.
817                  */
818                 int index = random_upto(rs, nrpns);
819                 int k, m;
820                 struct rpn rpn = rpns[index];
821                 struct rect r;
822                 sfree(rpns);
823
824                 i = rpn.rect;
825                 j = rpn.placement;
826                 k = rpn.number;
827                 r = rectpositions[i].rects[j];
828
829                 /*
830                  * We rule out placement j of rectangle i by means
831                  * of removing all of rectangle k's candidate
832                  * number placements which do _not_ overlap it.
833                  * This will ensure that it is eliminated during
834                  * the next pass of rectangle-focused deduction.
835                  */
836 #ifdef SOLVER_DIAGNOSTICS
837                 printf("ensuring number for rect %d is within"
838                        " rect %d's placement at %d,%d w=%d h=%d\n",
839                        k, i, r.x, r.y, r.w, r.h);
840 #endif
841
842                 for (m = 0; m < numbers[k].npoints; m++) {
843                     int x = numbers[k].points[m].x;
844                     int y = numbers[k].points[m].y;
845
846                     if (x < r.x || x >= r.x + r.w ||
847                         y < r.y || y >= r.y + r.h) {
848 #ifdef SOLVER_DIAGNOSTICS
849                         printf("eliminating number for rect %d at %d,%d\n",
850                                k, x, y);
851 #endif
852                         remove_number_placement(w, h, &numbers[k],
853                                                 m, rectbyplace);
854                         m--;           /* don't skip the next one */
855                         done_something = TRUE;
856                     }
857                 }
858             }
859         }
860
861         if (!done_something) {
862 #ifdef SOLVER_DIAGNOSTICS
863             printf("terminating deduction loop\n");
864 #endif
865             break;
866         }
867     }
868
869     cleanup:
870     ret = 1;
871     for (i = 0; i < nrects; i++) {
872 #ifdef SOLVER_DIAGNOSTICS
873         printf("rect %d has %d possible placements\n",
874                i, rectpositions[i].n);
875 #endif
876         if (rectpositions[i].n <= 0) {
877             ret = 0;                   /* inconsistency */
878         } else if (rectpositions[i].n > 1) {
879             ret = 2;                   /* remaining uncertainty */
880         } else if (hedge && vedge) {
881             /*
882              * Place the rectangle in its only possible position.
883              */
884             int x, y;
885             struct rect *r = &rectpositions[i].rects[0];
886
887             for (y = 0; y < r->h; y++) {
888                 if (r->x > 0)
889                     vedge[(r->y+y) * w + r->x] = 1;
890                 if (r->x+r->w < w)
891                     vedge[(r->y+y) * w + r->x+r->w] = 1;
892             }
893             for (x = 0; x < r->w; x++) {
894                 if (r->y > 0)
895                     hedge[r->y * w + r->x+x] = 1;
896                 if (r->y+r->h < h)
897                     hedge[(r->y+r->h) * w + r->x+x] = 1;
898             }
899         }
900     }
901
902     /*
903      * Free up all allocated storage.
904      */
905     sfree(workspace);
906     sfree(rectbyplace);
907     sfree(overlaps);
908     for (i = 0; i < nrects; i++)
909         sfree(rectpositions[i].rects);
910     sfree(rectpositions);
911
912     return ret;
913 }
914
915 /* ----------------------------------------------------------------------
916  * Grid generation code.
917  */
918
919 /*
920  * This function does one of two things. If passed r==NULL, it
921  * counts the number of possible rectangles which cover the given
922  * square, and returns it in *n. If passed r!=NULL then it _reads_
923  * *n to find an index, counts the possible rectangles until it
924  * reaches the nth, and writes it into r.
925  * 
926  * `scratch' is expected to point to an array of 2 * params->w
927  * ints, used internally as scratch space (and passed in like this
928  * to avoid re-allocating and re-freeing it every time round a
929  * tight loop).
930  */
931 static void enum_rects(game_params *params, int *grid, struct rect *r, int *n,
932                        int sx, int sy, int *scratch)
933 {
934     int rw, rh, mw, mh;
935     int x, y, dx, dy;
936     int maxarea, realmaxarea;
937     int index = 0;
938     int *top, *bottom;
939
940     /*
941      * Maximum rectangle area is 1/6 of total grid size, unless
942      * this means we can't place any rectangles at all in which
943      * case we set it to 2 at minimum.
944      */
945     maxarea = params->w * params->h / 6;
946     if (maxarea < 2)
947         maxarea = 2;
948
949     /*
950      * Scan the grid to find the limits of the region within which
951      * any rectangle containing this point must fall. This will
952      * save us trawling the inside of every rectangle later on to
953      * see if it contains any used squares.
954      */
955     top = scratch;
956     bottom = scratch + params->w;
957     for (dy = -1; dy <= +1; dy += 2) {
958         int *array = (dy == -1 ? top : bottom);
959         for (dx = -1; dx <= +1; dx += 2) {
960             for (x = sx; x >= 0 && x < params->w; x += dx) {
961                 array[x] = -2 * params->h * dy;
962                 for (y = sy; y >= 0 && y < params->h; y += dy) {
963                     if (index(params, grid, x, y) == -1 &&
964                         (x == sx || dy*y <= dy*array[x-dx]))
965                         array[x] = y;
966                     else
967                         break;
968                 }
969             }
970         }
971     }
972
973     /*
974      * Now scan again to work out the largest rectangles we can fit
975      * in the grid, so that we can terminate the following loops
976      * early once we get down to not having much space left in the
977      * grid.
978      */
979     realmaxarea = 0;
980     for (x = 0; x < params->w; x++) {
981         int x2;
982
983         rh = bottom[x] - top[x] + 1;
984         if (rh <= 0)
985             continue;                  /* no rectangles can start here */
986
987         dx = (x > sx ? -1 : +1);
988         for (x2 = x; x2 >= 0 && x2 < params->w; x2 += dx)
989             if (bottom[x2] < bottom[x] || top[x2] > top[x])
990                 break;
991
992         rw = abs(x2 - x);
993         if (realmaxarea < rw * rh)
994             realmaxarea = rw * rh;
995     }
996
997     if (realmaxarea > maxarea)
998         realmaxarea = maxarea;
999
1000     /*
1001      * Rectangles which go right the way across the grid are
1002      * boring, although they can't be helped in the case of
1003      * extremely small grids. (Also they might be generated later
1004      * on by the singleton-removal process; we can't help that.)
1005      */
1006     mw = params->w - 1;
1007     if (mw < 3) mw++;
1008     mh = params->h - 1;
1009     if (mh < 3) mh++;
1010
1011     for (rw = 1; rw <= mw; rw++)
1012         for (rh = 1; rh <= mh; rh++) {
1013             if (rw * rh > realmaxarea)
1014                 continue;
1015             if (rw * rh == 1)
1016                 continue;
1017             for (x = max(sx - rw + 1, 0); x <= min(sx, params->w - rw); x++)
1018                 for (y = max(sy - rh + 1, 0); y <= min(sy, params->h - rh);
1019                      y++) {
1020                     /*
1021                      * Check this rectangle against the region we
1022                      * defined above.
1023                      */
1024                     if (top[x] <= y && top[x+rw-1] <= y &&
1025                         bottom[x] >= y+rh-1 && bottom[x+rw-1] >= y+rh-1) {
1026                         if (r && index == *n) {
1027                             r->x = x;
1028                             r->y = y;
1029                             r->w = rw;
1030                             r->h = rh;
1031                             return;
1032                         }
1033                         index++;
1034                     }
1035                 }
1036         }
1037
1038     assert(!r);
1039     *n = index;
1040 }
1041
1042 static void place_rect(game_params *params, int *grid, struct rect r)
1043 {
1044     int idx = INDEX(params, r.x, r.y);
1045     int x, y;
1046
1047     for (x = r.x; x < r.x+r.w; x++)
1048         for (y = r.y; y < r.y+r.h; y++) {
1049             index(params, grid, x, y) = idx;
1050         }
1051 #ifdef GENERATION_DIAGNOSTICS
1052     printf("    placing rectangle at (%d,%d) size %d x %d\n",
1053            r.x, r.y, r.w, r.h);
1054 #endif
1055 }
1056
1057 static struct rect find_rect(game_params *params, int *grid, int x, int y)
1058 {
1059     int idx, w, h;
1060     struct rect r;
1061
1062     /*
1063      * Find the top left of the rectangle.
1064      */
1065     idx = index(params, grid, x, y);
1066
1067     if (idx < 0) {
1068         r.x = x;
1069         r.y = y;
1070         r.w = r.h = 1;
1071         return r;                      /* 1x1 singleton here */
1072     }
1073
1074     y = idx / params->w;
1075     x = idx % params->w;
1076
1077     /*
1078      * Find the width and height of the rectangle.
1079      */
1080     for (w = 1;
1081          (x+w < params->w && index(params,grid,x+w,y)==idx);
1082          w++);
1083     for (h = 1;
1084          (y+h < params->h && index(params,grid,x,y+h)==idx);
1085          h++);
1086
1087     r.x = x;
1088     r.y = y;
1089     r.w = w;
1090     r.h = h;
1091
1092     return r;
1093 }
1094
1095 #ifdef GENERATION_DIAGNOSTICS
1096 static void display_grid(game_params *params, int *grid, int *numbers, int all)
1097 {
1098     unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
1099                                  unsigned char);
1100     int x, y;
1101     int r = (params->w*2+3);
1102
1103     memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
1104
1105     for (x = 0; x < params->w; x++)
1106         for (y = 0; y < params->h; y++) {
1107             int i = index(params, grid, x, y);
1108             if (x == 0 || index(params, grid, x-1, y) != i)
1109                 egrid[(2*y+2) * r + (2*x+1)] = 1;
1110             if (x == params->w-1 || index(params, grid, x+1, y) != i)
1111                 egrid[(2*y+2) * r + (2*x+3)] = 1;
1112             if (y == 0 || index(params, grid, x, y-1) != i)
1113                 egrid[(2*y+1) * r + (2*x+2)] = 1;
1114             if (y == params->h-1 || index(params, grid, x, y+1) != i)
1115                 egrid[(2*y+3) * r + (2*x+2)] = 1;
1116         }
1117
1118     for (y = 1; y < 2*params->h+2; y++) {
1119         for (x = 1; x < 2*params->w+2; x++) {
1120             if (!((y|x)&1)) {
1121                 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
1122                 if (k || (all && numbers)) printf("%2d", k); else printf("  ");
1123             } else if (!((y&x)&1)) {
1124                 int v = egrid[y*r+x];
1125                 if ((y&1) && v) v = '-';
1126                 if ((x&1) && v) v = '|';
1127                 if (!v) v = ' ';
1128                 putchar(v);
1129                 if (!(x&1)) putchar(v);
1130             } else {
1131                 int c, d = 0;
1132                 if (egrid[y*r+(x+1)]) d |= 1;
1133                 if (egrid[(y-1)*r+x]) d |= 2;
1134                 if (egrid[y*r+(x-1)]) d |= 4;
1135                 if (egrid[(y+1)*r+x]) d |= 8;
1136                 c = " ??+?-++?+|+++++"[d];
1137                 putchar(c);
1138                 if (!(x&1)) putchar(c);
1139             }
1140         }
1141         putchar('\n');
1142     }
1143
1144     sfree(egrid);
1145 }
1146 #endif
1147
1148 static char *new_game_desc(game_params *params, random_state *rs,
1149                            char **aux, int interactive)
1150 {
1151     int *grid, *numbers = NULL;
1152     int x, y, y2, y2last, yx, run, i, nsquares;
1153     char *desc, *p;
1154     int *enum_rects_scratch;
1155     game_params params2real, *params2 = &params2real;
1156
1157     while (1) {
1158         /*
1159          * Set up the smaller width and height which we will use to
1160          * generate the base grid.
1161          */
1162         params2->w = params->w / (1.0F + params->expandfactor);
1163         if (params2->w < 2 && params->w >= 2) params2->w = 2;
1164         params2->h = params->h / (1.0F + params->expandfactor);
1165         if (params2->h < 2 && params->h >= 2) params2->h = 2;
1166
1167         grid = snewn(params2->w * params2->h, int);
1168
1169         enum_rects_scratch = snewn(2 * params2->w, int);
1170
1171         nsquares = 0;
1172         for (y = 0; y < params2->h; y++)
1173             for (x = 0; x < params2->w; x++) {
1174                 index(params2, grid, x, y) = -1;
1175                 nsquares++;
1176             }
1177
1178         /*
1179          * Place rectangles until we can't any more. We do this by
1180          * finding a square we haven't yet covered, and randomly
1181          * choosing a rectangle to cover it.
1182          */
1183         
1184         while (nsquares > 0) {
1185             int square = random_upto(rs, nsquares);
1186             int n;
1187             struct rect r;
1188
1189             x = params2->w;
1190             y = params2->h;
1191             for (y = 0; y < params2->h; y++) {
1192                 for (x = 0; x < params2->w; x++) {
1193                     if (index(params2, grid, x, y) == -1 && square-- == 0)
1194                         break;
1195                 }
1196                 if (x < params2->w)
1197                     break;
1198             }
1199             assert(x < params2->w && y < params2->h);
1200
1201             /*
1202              * Now see how many rectangles fit around this one.
1203              */
1204             enum_rects(params2, grid, NULL, &n, x, y, enum_rects_scratch);
1205
1206             if (!n) {
1207                 /*
1208                  * There are no possible rectangles covering this
1209                  * square, meaning it must be a singleton. Mark it
1210                  * -2 so we know not to keep trying.
1211                  */
1212                 index(params2, grid, x, y) = -2;
1213                 nsquares--;
1214             } else {
1215                 /*
1216                  * Pick one at random.
1217                  */
1218                 n = random_upto(rs, n);
1219                 enum_rects(params2, grid, &r, &n, x, y, enum_rects_scratch);
1220
1221                 /*
1222                  * Place it.
1223                  */
1224                 place_rect(params2, grid, r);
1225                 nsquares -= r.w * r.h;
1226             }
1227         }
1228
1229         sfree(enum_rects_scratch);
1230
1231         /*
1232          * Deal with singleton spaces remaining in the grid, one by
1233          * one.
1234          *
1235          * We do this by making a local change to the layout. There are
1236          * several possibilities:
1237          *
1238          *     +-----+-----+    Here, we can remove the singleton by
1239          *     |     |     |    extending the 1x2 rectangle below it
1240          *     +--+--+-----+    into a 1x3.
1241          *     |  |  |     |
1242          *     |  +--+     |
1243          *     |  |  |     |
1244          *     |  |  |     |
1245          *     |  |  |     |
1246          *     +--+--+-----+
1247          *
1248          *     +--+--+--+       Here, that trick doesn't work: there's no
1249          *     |     |  |       1 x n rectangle with the singleton at one
1250          *     |     |  |       end. Instead, we extend a 1 x n rectangle
1251          *     |     |  |       _out_ from the singleton, shaving a layer
1252          *     +--+--+  |       off the end of another rectangle. So if we
1253          *     |  |  |  |       extended up, we'd make our singleton part
1254          *     |  +--+--+       of a 1x3 and generate a 1x2 where the 2x2
1255          *     |  |     |       used to be; or we could extend right into
1256          *     +--+-----+       a 2x1, turning the 1x3 into a 1x2.
1257          *
1258          *     +-----+--+       Here, we can't even do _that_, since any
1259          *     |     |  |       direction we choose to extend the singleton
1260          *     +--+--+  |       will produce a new singleton as a result of
1261          *     |  |  |  |       truncating one of the size-2 rectangles.
1262          *     |  +--+--+       Fortunately, this case can _only_ occur when
1263          *     |  |     |       a singleton is surrounded by four size-2s
1264          *     +--+-----+       in this fashion; so instead we can simply
1265          *                      replace the whole section with a single 3x3.
1266          */
1267         for (x = 0; x < params2->w; x++) {
1268             for (y = 0; y < params2->h; y++) {
1269                 if (index(params2, grid, x, y) < 0) {
1270                     int dirs[4], ndirs;
1271
1272 #ifdef GENERATION_DIAGNOSTICS
1273                     display_grid(params2, grid, NULL, FALSE);
1274                     printf("singleton at %d,%d\n", x, y);
1275 #endif
1276
1277                     /*
1278                      * Check in which directions we can feasibly extend
1279                      * the singleton. We can extend in a particular
1280                      * direction iff either:
1281                      *
1282                      *  - the rectangle on that side of the singleton
1283                      *    is not 2x1, and we are at one end of the edge
1284                      *    of it we are touching
1285                      *
1286                      *  - it is 2x1 but we are on its short side.
1287                      *
1288                      * FIXME: we could plausibly choose between these
1289                      * based on the sizes of the rectangles they would
1290                      * create?
1291                      */
1292                     ndirs = 0;
1293                     if (x < params2->w-1) {
1294                         struct rect r = find_rect(params2, grid, x+1, y);
1295                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1296                             dirs[ndirs++] = 1;   /* right */
1297                     }
1298                     if (y > 0) {
1299                         struct rect r = find_rect(params2, grid, x, y-1);
1300                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1301                             dirs[ndirs++] = 2;   /* up */
1302                     }
1303                     if (x > 0) {
1304                         struct rect r = find_rect(params2, grid, x-1, y);
1305                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1306                             dirs[ndirs++] = 4;   /* left */
1307                     }
1308                     if (y < params2->h-1) {
1309                         struct rect r = find_rect(params2, grid, x, y+1);
1310                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1311                             dirs[ndirs++] = 8;   /* down */
1312                     }
1313
1314                     if (ndirs > 0) {
1315                         int which, dir;
1316                         struct rect r1, r2;
1317
1318                         which = random_upto(rs, ndirs);
1319                         dir = dirs[which];
1320
1321                         switch (dir) {
1322                           case 1:          /* right */
1323                             assert(x < params2->w+1);
1324 #ifdef GENERATION_DIAGNOSTICS
1325                             printf("extending right\n");
1326 #endif
1327                             r1 = find_rect(params2, grid, x+1, y);
1328                             r2.x = x;
1329                             r2.y = y;
1330                             r2.w = 1 + r1.w;
1331                             r2.h = 1;
1332                             if (r1.y == y)
1333                                 r1.y++;
1334                             r1.h--;
1335                             break;
1336                           case 2:          /* up */
1337                             assert(y > 0);
1338 #ifdef GENERATION_DIAGNOSTICS
1339                             printf("extending up\n");
1340 #endif
1341                             r1 = find_rect(params2, grid, x, y-1);
1342                             r2.x = x;
1343                             r2.y = r1.y;
1344                             r2.w = 1;
1345                             r2.h = 1 + r1.h;
1346                             if (r1.x == x)
1347                                 r1.x++;
1348                             r1.w--;
1349                             break;
1350                           case 4:          /* left */
1351                             assert(x > 0);
1352 #ifdef GENERATION_DIAGNOSTICS
1353                             printf("extending left\n");
1354 #endif
1355                             r1 = find_rect(params2, grid, x-1, y);
1356                             r2.x = r1.x;
1357                             r2.y = y;
1358                             r2.w = 1 + r1.w;
1359                             r2.h = 1;
1360                             if (r1.y == y)
1361                                 r1.y++;
1362                             r1.h--;
1363                             break;
1364                           case 8:          /* down */
1365                             assert(y < params2->h+1);
1366 #ifdef GENERATION_DIAGNOSTICS
1367                             printf("extending down\n");
1368 #endif
1369                             r1 = find_rect(params2, grid, x, y+1);
1370                             r2.x = x;
1371                             r2.y = y;
1372                             r2.w = 1;
1373                             r2.h = 1 + r1.h;
1374                             if (r1.x == x)
1375                                 r1.x++;
1376                             r1.w--;
1377                             break;
1378                           default:     /* should never happen */
1379                             assert(!"invalid direction");
1380                         }
1381                         if (r1.h > 0 && r1.w > 0)
1382                             place_rect(params2, grid, r1);
1383                         place_rect(params2, grid, r2);
1384                     } else {
1385 #ifndef NDEBUG
1386                         /*
1387                          * Sanity-check that there really is a 3x3
1388                          * rectangle surrounding this singleton and it
1389                          * contains absolutely everything we could
1390                          * possibly need.
1391                          */
1392                         {
1393                             int xx, yy;
1394                             assert(x > 0 && x < params2->w-1);
1395                             assert(y > 0 && y < params2->h-1);
1396
1397                             for (xx = x-1; xx <= x+1; xx++)
1398                                 for (yy = y-1; yy <= y+1; yy++) {
1399                                     struct rect r = find_rect(params2,grid,xx,yy);
1400                                     assert(r.x >= x-1);
1401                                     assert(r.y >= y-1);
1402                                     assert(r.x+r.w-1 <= x+1);
1403                                     assert(r.y+r.h-1 <= y+1);
1404                                 }
1405                         }
1406 #endif
1407
1408 #ifdef GENERATION_DIAGNOSTICS
1409                         printf("need the 3x3 trick\n");
1410 #endif
1411
1412                         /*
1413                          * FIXME: If the maximum rectangle area for
1414                          * this grid is less than 9, we ought to
1415                          * subdivide the 3x3 in some fashion. There are
1416                          * five other possibilities:
1417                          *
1418                          *  - a 6 and a 3
1419                          *  - a 4, a 3 and a 2
1420                          *  - three 3s
1421                          *  - a 3 and three 2s (two different arrangements).
1422                          */
1423
1424                         {
1425                             struct rect r;
1426                             r.x = x-1;
1427                             r.y = y-1;
1428                             r.w = r.h = 3;
1429                             place_rect(params2, grid, r);
1430                         }
1431                     }
1432                 }
1433             }
1434         }
1435
1436         /*
1437          * We have now constructed a grid of the size specified in
1438          * params2. Now we extend it into a grid of the size specified
1439          * in params. We do this in two passes: we extend it vertically
1440          * until it's the right height, then we transpose it, then
1441          * extend it vertically again (getting it effectively the right
1442          * width), then finally transpose again.
1443          */
1444         for (i = 0; i < 2; i++) {
1445             int *grid2, *expand, *where;
1446             game_params params3real, *params3 = &params3real;
1447
1448 #ifdef GENERATION_DIAGNOSTICS
1449             printf("before expansion:\n");
1450             display_grid(params2, grid, NULL, TRUE);
1451 #endif
1452
1453             /*
1454              * Set up the new grid.
1455              */
1456             grid2 = snewn(params2->w * params->h, int);
1457             expand = snewn(params2->h-1, int);
1458             where = snewn(params2->w, int);
1459             params3->w = params2->w;
1460             params3->h = params->h;
1461
1462             /*
1463              * Decide which horizontal edges are going to get expanded,
1464              * and by how much.
1465              */
1466             for (y = 0; y < params2->h-1; y++)
1467                 expand[y] = 0;
1468             for (y = params2->h; y < params->h; y++) {
1469                 x = random_upto(rs, params2->h-1);
1470                 expand[x]++;
1471             }
1472
1473 #ifdef GENERATION_DIAGNOSTICS
1474             printf("expand[] = {");
1475             for (y = 0; y < params2->h-1; y++)
1476                 printf(" %d", expand[y]);
1477             printf(" }\n");
1478 #endif
1479
1480             /*
1481              * Perform the expansion. The way this works is that we
1482              * alternately:
1483              *
1484              *  - copy a row from grid into grid2
1485              *
1486              *  - invent some number of additional rows in grid2 where
1487              *    there was previously only a horizontal line between
1488              *    rows in grid, and make random decisions about where
1489              *    among these to place each rectangle edge that ran
1490              *    along this line.
1491              */
1492             for (y = y2 = y2last = 0; y < params2->h; y++) {
1493                 /*
1494                  * Copy a single line from row y of grid into row y2 of
1495                  * grid2.
1496                  */
1497                 for (x = 0; x < params2->w; x++) {
1498                     int val = index(params2, grid, x, y);
1499                     if (val / params2->w == y &&   /* rect starts on this line */
1500                         (y2 == 0 ||            /* we're at the very top, or... */
1501                          index(params3, grid2, x, y2-1) / params3->w < y2last
1502                          /* this rect isn't already started */))
1503                         index(params3, grid2, x, y2) =
1504                         INDEX(params3, val % params2->w, y2);
1505                     else
1506                         index(params3, grid2, x, y2) =
1507                         index(params3, grid2, x, y2-1);
1508                 }
1509
1510                 /*
1511                  * If that was the last line, terminate the loop early.
1512                  */
1513                 if (++y2 == params3->h)
1514                     break;
1515
1516                 y2last = y2;
1517
1518                 /*
1519                  * Invent some number of additional lines. First walk
1520                  * along this line working out where to put all the
1521                  * edges that coincide with it.
1522                  */
1523                 yx = -1;
1524                 for (x = 0; x < params2->w; x++) {
1525                     if (index(params2, grid, x, y) !=
1526                         index(params2, grid, x, y+1)) {
1527                         /*
1528                          * This is a horizontal edge, so it needs
1529                          * placing.
1530                          */
1531                         if (x == 0 ||
1532                             (index(params2, grid, x-1, y) !=
1533                              index(params2, grid, x, y) &&
1534                              index(params2, grid, x-1, y+1) !=
1535                              index(params2, grid, x, y+1))) {
1536                             /*
1537                              * Here we have the chance to make a new
1538                              * decision.
1539                              */
1540                             yx = random_upto(rs, expand[y]+1);
1541                         } else {
1542                             /*
1543                              * Here we just reuse the previous value of
1544                              * yx.
1545                              */
1546                         }
1547                     } else
1548                         yx = -1;
1549                     where[x] = yx;
1550                 }
1551
1552                 for (yx = 0; yx < expand[y]; yx++) {
1553                     /*
1554                      * Invent a single row. For each square in the row,
1555                      * we copy the grid entry from the square above it,
1556                      * unless we're starting the new rectangle here.
1557                      */
1558                     for (x = 0; x < params2->w; x++) {
1559                         if (yx == where[x]) {
1560                             int val = index(params2, grid, x, y+1);
1561                             val %= params2->w;
1562                             val = INDEX(params3, val, y2);
1563                             index(params3, grid2, x, y2) = val;
1564                         } else
1565                             index(params3, grid2, x, y2) =
1566                             index(params3, grid2, x, y2-1);
1567                     }
1568
1569                     y2++;
1570                 }
1571             }
1572
1573             sfree(expand);
1574             sfree(where);
1575
1576 #ifdef GENERATION_DIAGNOSTICS
1577             printf("after expansion:\n");
1578             display_grid(params3, grid2, NULL, TRUE);
1579 #endif
1580             /*
1581              * Transpose.
1582              */
1583             params2->w = params3->h;
1584             params2->h = params3->w;
1585             sfree(grid);
1586             grid = snewn(params2->w * params2->h, int);
1587             for (x = 0; x < params2->w; x++)
1588                 for (y = 0; y < params2->h; y++) {
1589                     int idx1 = INDEX(params2, x, y);
1590                     int idx2 = INDEX(params3, y, x);
1591                     int tmp;
1592
1593                     tmp = grid2[idx2];
1594                     tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
1595                     grid[idx1] = tmp;
1596                 }
1597
1598             sfree(grid2);
1599
1600             {
1601                 int tmp;
1602                 tmp = params->w;
1603                 params->w = params->h;
1604                 params->h = tmp;
1605             }
1606
1607 #ifdef GENERATION_DIAGNOSTICS
1608             printf("after transposition:\n");
1609             display_grid(params2, grid, NULL, TRUE);
1610 #endif
1611         }
1612
1613         /*
1614          * Run the solver to narrow down the possible number
1615          * placements.
1616          */
1617         {
1618             struct numberdata *nd;
1619             int nnumbers, i, ret;
1620
1621             /* Count the rectangles. */
1622             nnumbers = 0;
1623             for (y = 0; y < params->h; y++) {
1624                 for (x = 0; x < params->w; x++) {
1625                     int idx = INDEX(params, x, y);
1626                     if (index(params, grid, x, y) == idx)
1627                         nnumbers++;
1628                 }
1629             }
1630
1631             nd = snewn(nnumbers, struct numberdata);
1632
1633             /* Now set up each number's candidate position list. */
1634             i = 0;
1635             for (y = 0; y < params->h; y++) {
1636                 for (x = 0; x < params->w; x++) {
1637                     int idx = INDEX(params, x, y);
1638                     if (index(params, grid, x, y) == idx) {
1639                         struct rect r = find_rect(params, grid, x, y);
1640                         int j, k, m;
1641
1642                         nd[i].area = r.w * r.h;
1643                         nd[i].npoints = nd[i].area;
1644                         nd[i].points = snewn(nd[i].npoints, struct point);
1645                         m = 0;
1646                         for (j = 0; j < r.h; j++)
1647                             for (k = 0; k < r.w; k++) {
1648                                 nd[i].points[m].x = k + r.x;
1649                                 nd[i].points[m].y = j + r.y;
1650                                 m++;
1651                             }
1652                         assert(m == nd[i].npoints);
1653
1654                         i++;
1655                     }
1656                 }
1657             }
1658
1659             if (params->unique)
1660                 ret = rect_solver(params->w, params->h, nnumbers, nd,
1661                                   NULL, NULL, rs);
1662             else
1663                 ret = 1;               /* allow any number placement at all */
1664
1665             if (ret == 1) {
1666                 /*
1667                  * Now place the numbers according to the solver's
1668                  * recommendations.
1669                  */
1670                 numbers = snewn(params->w * params->h, int);
1671
1672                 for (y = 0; y < params->h; y++)
1673                     for (x = 0; x < params->w; x++) {
1674                         index(params, numbers, x, y) = 0;
1675                     }
1676
1677                 for (i = 0; i < nnumbers; i++) {
1678                     int idx = random_upto(rs, nd[i].npoints);
1679                     int x = nd[i].points[idx].x;
1680                     int y = nd[i].points[idx].y;
1681                     index(params,numbers,x,y) = nd[i].area;
1682                 }
1683             }
1684
1685             /*
1686              * Clean up.
1687              */
1688             for (i = 0; i < nnumbers; i++)
1689                 sfree(nd[i].points);
1690             sfree(nd);
1691
1692             /*
1693              * If we've succeeded, then terminate the loop.
1694              */
1695             if (ret == 1)
1696                 break;
1697         }
1698
1699         /*
1700          * Give up and go round again.
1701          */
1702         sfree(grid);
1703     }
1704
1705     /*
1706      * Store the solution in aux.
1707      */
1708     {
1709         char *ai;
1710         int len;
1711
1712         len = 2 + (params->w-1)*params->h + (params->h-1)*params->w;
1713         ai = snewn(len, char);
1714
1715         ai[0] = 'S';
1716
1717         p = ai+1;
1718
1719         for (y = 0; y < params->h; y++)
1720             for (x = 1; x < params->w; x++)
1721                 *p++ = (index(params, grid, x, y) !=
1722                         index(params, grid, x-1, y) ? '1' : '0');
1723
1724         for (y = 1; y < params->h; y++)
1725             for (x = 0; x < params->w; x++)
1726                 *p++ = (index(params, grid, x, y) !=
1727                         index(params, grid, x, y-1) ? '1' : '0');
1728
1729         assert(p - ai == len-1);
1730         *p = '\0';
1731
1732         *aux = ai;
1733     }
1734
1735 #ifdef GENERATION_DIAGNOSTICS
1736     display_grid(params, grid, numbers, FALSE);
1737 #endif
1738
1739     desc = snewn(11 * params->w * params->h, char);
1740     p = desc;
1741     run = 0;
1742     for (i = 0; i <= params->w * params->h; i++) {
1743         int n = (i < params->w * params->h ? numbers[i] : -1);
1744
1745         if (!n)
1746             run++;
1747         else {
1748             if (run) {
1749                 while (run > 0) {
1750                     int c = 'a' - 1 + run;
1751                     if (run > 26)
1752                         c = 'z';
1753                     *p++ = c;
1754                     run -= c - ('a' - 1);
1755                 }
1756             } else {
1757                 /*
1758                  * If there's a number in the very top left or
1759                  * bottom right, there's no point putting an
1760                  * unnecessary _ before or after it.
1761                  */
1762                 if (p > desc && n > 0)
1763                     *p++ = '_';
1764             }
1765             if (n > 0)
1766                 p += sprintf(p, "%d", n);
1767             run = 0;
1768         }
1769     }
1770     *p = '\0';
1771
1772     sfree(grid);
1773     sfree(numbers);
1774
1775     return desc;
1776 }
1777
1778 static char *validate_desc(game_params *params, char *desc)
1779 {
1780     int area = params->w * params->h;
1781     int squares = 0;
1782
1783     while (*desc) {
1784         int n = *desc++;
1785         if (n >= 'a' && n <= 'z') {
1786             squares += n - 'a' + 1;
1787         } else if (n == '_') {
1788             /* do nothing */;
1789         } else if (n > '0' && n <= '9') {
1790             squares++;
1791             while (*desc >= '0' && *desc <= '9')
1792                 desc++;
1793         } else
1794             return "Invalid character in game description";
1795     }
1796
1797     if (squares < area)
1798         return "Not enough data to fill grid";
1799
1800     if (squares > area)
1801         return "Too much data to fit in grid";
1802
1803     return NULL;
1804 }
1805
1806 static unsigned char *get_correct(game_state *state)
1807 {
1808     unsigned char *ret;
1809     int x, y;
1810
1811     ret = snewn(state->w * state->h, unsigned char);
1812     memset(ret, 0xFF, state->w * state->h);
1813
1814     for (x = 0; x < state->w; x++)
1815         for (y = 0; y < state->h; y++)
1816             if (index(state,ret,x,y) == 0xFF) {
1817                 int rw, rh;
1818                 int xx, yy;
1819                 int num, area, valid;
1820
1821                 /*
1822                  * Find a rectangle starting at this point.
1823                  */
1824                 rw = 1;
1825                 while (x+rw < state->w && !vedge(state,x+rw,y))
1826                     rw++;
1827                 rh = 1;
1828                 while (y+rh < state->h && !hedge(state,x,y+rh))
1829                     rh++;
1830
1831                 /*
1832                  * We know what the dimensions of the rectangle
1833                  * should be if it's there at all. Find out if we
1834                  * really have a valid rectangle.
1835                  */
1836                 valid = TRUE;
1837                 /* Check the horizontal edges. */
1838                 for (xx = x; xx < x+rw; xx++) {
1839                     for (yy = y; yy <= y+rh; yy++) {
1840                         int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
1841                         int ec = (yy == y || yy == y+rh);
1842                         if (e != ec)
1843                             valid = FALSE;
1844                     }
1845                 }
1846                 /* Check the vertical edges. */
1847                 for (yy = y; yy < y+rh; yy++) {
1848                     for (xx = x; xx <= x+rw; xx++) {
1849                         int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
1850                         int ec = (xx == x || xx == x+rw);
1851                         if (e != ec)
1852                             valid = FALSE;
1853                     }
1854                 }
1855
1856                 /*
1857                  * If this is not a valid rectangle with no other
1858                  * edges inside it, we just mark this square as not
1859                  * complete and proceed to the next square.
1860                  */
1861                 if (!valid) {
1862                     index(state, ret, x, y) = 0;
1863                     continue;
1864                 }
1865
1866                 /*
1867                  * We have a rectangle. Now see what its area is,
1868                  * and how many numbers are in it.
1869                  */
1870                 num = 0;
1871                 area = 0;
1872                 for (xx = x; xx < x+rw; xx++) {
1873                     for (yy = y; yy < y+rh; yy++) {
1874                         area++;
1875                         if (grid(state,xx,yy)) {
1876                             if (num > 0)
1877                                 valid = FALSE;   /* two numbers */
1878                             num = grid(state,xx,yy);
1879                         }
1880                     }
1881                 }
1882                 if (num != area)
1883                     valid = FALSE;
1884
1885                 /*
1886                  * Now fill in the whole rectangle based on the
1887                  * value of `valid'.
1888                  */
1889                 for (xx = x; xx < x+rw; xx++) {
1890                     for (yy = y; yy < y+rh; yy++) {
1891                         index(state, ret, xx, yy) = valid;
1892                     }
1893                 }
1894             }
1895
1896     return ret;
1897 }
1898
1899 static game_state *new_game(midend *me, game_params *params, char *desc)
1900 {
1901     game_state *state = snew(game_state);
1902     int x, y, i, area;
1903
1904     state->w = params->w;
1905     state->h = params->h;
1906
1907     area = state->w * state->h;
1908
1909     state->grid = snewn(area, int);
1910     state->vedge = snewn(area, unsigned char);
1911     state->hedge = snewn(area, unsigned char);
1912     state->completed = state->cheated = FALSE;
1913
1914     i = 0;
1915     while (*desc) {
1916         int n = *desc++;
1917         if (n >= 'a' && n <= 'z') {
1918             int run = n - 'a' + 1;
1919             assert(i + run <= area);
1920             while (run-- > 0)
1921                 state->grid[i++] = 0;
1922         } else if (n == '_') {
1923             /* do nothing */;
1924         } else if (n > '0' && n <= '9') {
1925             assert(i < area);
1926             state->grid[i++] = atoi(desc-1);
1927             while (*desc >= '0' && *desc <= '9')
1928                 desc++;
1929         } else {
1930             assert(!"We can't get here");
1931         }
1932     }
1933     assert(i == area);
1934
1935     for (y = 0; y < state->h; y++)
1936         for (x = 0; x < state->w; x++)
1937             vedge(state,x,y) = hedge(state,x,y) = 0;
1938
1939     state->correct = get_correct(state);
1940
1941     return state;
1942 }
1943
1944 static game_state *dup_game(game_state *state)
1945 {
1946     game_state *ret = snew(game_state);
1947
1948     ret->w = state->w;
1949     ret->h = state->h;
1950
1951     ret->vedge = snewn(state->w * state->h, unsigned char);
1952     ret->hedge = snewn(state->w * state->h, unsigned char);
1953     ret->grid = snewn(state->w * state->h, int);
1954     ret->correct = snewn(ret->w * ret->h, unsigned char);
1955
1956     ret->completed = state->completed;
1957     ret->cheated = state->cheated;
1958
1959     memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
1960     memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
1961     memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
1962
1963     memcpy(ret->correct, state->correct, state->w*state->h*sizeof(unsigned char));
1964
1965     return ret;
1966 }
1967
1968 static void free_game(game_state *state)
1969 {
1970     sfree(state->grid);
1971     sfree(state->vedge);
1972     sfree(state->hedge);
1973     sfree(state->correct);
1974     sfree(state);
1975 }
1976
1977 static char *solve_game(game_state *state, game_state *currstate,
1978                         char *ai, char **error)
1979 {
1980     unsigned char *vedge, *hedge;
1981     int x, y, len;
1982     char *ret, *p;
1983     int i, j, n;
1984     struct numberdata *nd;
1985
1986     if (ai)
1987         return dupstr(ai);
1988
1989     /*
1990      * Attempt the in-built solver.
1991      */
1992
1993     /* Set up each number's (very short) candidate position list. */
1994     for (i = n = 0; i < state->h * state->w; i++)
1995         if (state->grid[i])
1996             n++;
1997
1998     nd = snewn(n, struct numberdata);
1999
2000     for (i = j = 0; i < state->h * state->w; i++)
2001         if (state->grid[i]) {
2002             nd[j].area = state->grid[i];
2003             nd[j].npoints = 1;
2004             nd[j].points = snewn(1, struct point);
2005             nd[j].points[0].x = i % state->w;
2006             nd[j].points[0].y = i / state->w;
2007             j++;
2008         }
2009
2010     assert(j == n);
2011
2012     vedge = snewn(state->w * state->h, unsigned char);
2013     hedge = snewn(state->w * state->h, unsigned char);
2014     memset(vedge, 0, state->w * state->h);
2015     memset(hedge, 0, state->w * state->h);
2016
2017     rect_solver(state->w, state->h, n, nd, hedge, vedge, NULL);
2018
2019     /*
2020      * Clean up.
2021      */
2022     for (i = 0; i < n; i++)
2023         sfree(nd[i].points);
2024     sfree(nd);
2025
2026     len = 2 + (state->w-1)*state->h + (state->h-1)*state->w;
2027     ret = snewn(len, char);
2028
2029     p = ret;
2030     *p++ = 'S';
2031     for (y = 0; y < state->h; y++)
2032         for (x = 1; x < state->w; x++)
2033             *p++ = vedge[y*state->w+x] ? '1' : '0';
2034     for (y = 1; y < state->h; y++)
2035         for (x = 0; x < state->w; x++)
2036             *p++ = hedge[y*state->w+x] ? '1' : '0';
2037     *p++ = '\0';
2038     assert(p - ret == len);
2039
2040     sfree(vedge);
2041     sfree(hedge);
2042
2043     return ret;
2044 }
2045
2046 static int game_can_format_as_text_now(game_params *params)
2047 {
2048     return TRUE;
2049 }
2050
2051 static char *game_text_format(game_state *state)
2052 {
2053     char *ret, *p, buf[80];
2054     int i, x, y, col, maxlen;
2055
2056     /*
2057      * First determine the number of spaces required to display a
2058      * number. We'll use at least two, because one looks a bit
2059      * silly.
2060      */
2061     col = 2;
2062     for (i = 0; i < state->w * state->h; i++) {
2063         x = sprintf(buf, "%d", state->grid[i]);
2064         if (col < x) col = x;
2065     }
2066
2067     /*
2068      * Now we know the exact total size of the grid we're going to
2069      * produce: it's got 2*h+1 rows, each containing w lots of col,
2070      * w+1 boundary characters and a trailing newline.
2071      */
2072     maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
2073
2074     ret = snewn(maxlen+1, char);
2075     p = ret;
2076
2077     for (y = 0; y <= 2*state->h; y++) {
2078         for (x = 0; x <= 2*state->w; x++) {
2079             if (x & y & 1) {
2080                 /*
2081                  * Display a number.
2082                  */
2083                 int v = grid(state, x/2, y/2);
2084                 if (v)
2085                     sprintf(buf, "%*d", col, v);
2086                 else
2087                     sprintf(buf, "%*s", col, "");
2088                 memcpy(p, buf, col);
2089                 p += col;
2090             } else if (x & 1) {
2091                 /*
2092                  * Display a horizontal edge or nothing.
2093                  */
2094                 int h = (y==0 || y==2*state->h ? 1 :
2095                          HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
2096                 int i;
2097                 if (h)
2098                     h = '-';
2099                 else
2100                     h = ' ';
2101                 for (i = 0; i < col; i++)
2102                     *p++ = h;
2103             } else if (y & 1) {
2104                 /*
2105                  * Display a vertical edge or nothing.
2106                  */
2107                 int v = (x==0 || x==2*state->w ? 1 :
2108                          VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
2109                 if (v)
2110                     *p++ = '|';
2111                 else
2112                     *p++ = ' ';
2113             } else {
2114                 /*
2115                  * Display a corner, or a vertical edge, or a
2116                  * horizontal edge, or nothing.
2117                  */
2118                 int hl = (y==0 || y==2*state->h ? 1 :
2119                           HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
2120                 int hr = (y==0 || y==2*state->h ? 1 :
2121                           HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
2122                 int vu = (x==0 || x==2*state->w ? 1 :
2123                           VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
2124                 int vd = (x==0 || x==2*state->w ? 1 :
2125                           VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
2126                 if (!hl && !hr && !vu && !vd)
2127                     *p++ = ' ';
2128                 else if (hl && hr && !vu && !vd)
2129                     *p++ = '-';
2130                 else if (!hl && !hr && vu && vd)
2131                     *p++ = '|';
2132                 else
2133                     *p++ = '+';
2134             }
2135         }
2136         *p++ = '\n';
2137     }
2138
2139     assert(p - ret == maxlen);
2140     *p = '\0';
2141     return ret;
2142 }
2143
2144 struct game_ui {
2145     /*
2146      * These coordinates are 2 times the obvious grid coordinates.
2147      * Hence, the top left of the grid is (0,0), the grid point to
2148      * the right of that is (2,0), the one _below that_ is (2,2)
2149      * and so on. This is so that we can specify a drag start point
2150      * on an edge (one odd coordinate) or in the middle of a square
2151      * (two odd coordinates) rather than always at a corner.
2152      * 
2153      * -1,-1 means no drag is in progress.
2154      */
2155     int drag_start_x;
2156     int drag_start_y;
2157     int drag_end_x;
2158     int drag_end_y;
2159     /*
2160      * This flag is set as soon as a dragging action moves the
2161      * mouse pointer away from its starting point, so that even if
2162      * the pointer _returns_ to its starting point the action is
2163      * treated as a small drag rather than a click.
2164      */
2165     int dragged;
2166     /*
2167      * These are the co-ordinates of the top-left and bottom-right squares
2168      * in the drag box, respectively, or -1 otherwise.
2169      */
2170     int x1;
2171     int y1;
2172     int x2;
2173     int y2;
2174 };
2175
2176 static game_ui *new_ui(game_state *state)
2177 {
2178     game_ui *ui = snew(game_ui);
2179     ui->drag_start_x = -1;
2180     ui->drag_start_y = -1;
2181     ui->drag_end_x = -1;
2182     ui->drag_end_y = -1;
2183     ui->dragged = FALSE;
2184     ui->x1 = -1;
2185     ui->y1 = -1;
2186     ui->x2 = -1;
2187     ui->y2 = -1;
2188     return ui;
2189 }
2190
2191 static void free_ui(game_ui *ui)
2192 {
2193     sfree(ui);
2194 }
2195
2196 static char *encode_ui(game_ui *ui)
2197 {
2198     return NULL;
2199 }
2200
2201 static void decode_ui(game_ui *ui, char *encoding)
2202 {
2203 }
2204
2205 static void coord_round(float x, float y, int *xr, int *yr)
2206 {
2207     float xs, ys, xv, yv, dx, dy, dist;
2208
2209     /*
2210      * Find the nearest square-centre.
2211      */
2212     xs = (float)floor(x) + 0.5F;
2213     ys = (float)floor(y) + 0.5F;
2214
2215     /*
2216      * And find the nearest grid vertex.
2217      */
2218     xv = (float)floor(x + 0.5F);
2219     yv = (float)floor(y + 0.5F);
2220
2221     /*
2222      * We allocate clicks in parts of the grid square to either
2223      * corners, edges or square centres, as follows:
2224      * 
2225      *   +--+--------+--+
2226      *   |  |        |  |
2227      *   +--+        +--+
2228      *   |   `.    ,'   |
2229      *   |     +--+     |
2230      *   |     |  |     |
2231      *   |     +--+     |
2232      *   |   ,'    `.   |
2233      *   +--+        +--+
2234      *   |  |        |  |
2235      *   +--+--------+--+
2236      * 
2237      * (Not to scale!)
2238      * 
2239      * In other words: we measure the square distance (i.e.
2240      * max(dx,dy)) from the click to the nearest corner, and if
2241      * it's within CORNER_TOLERANCE then we return a corner click.
2242      * We measure the square distance from the click to the nearest
2243      * centre, and if that's within CENTRE_TOLERANCE we return a
2244      * centre click. Failing that, we find which of the two edge
2245      * centres is nearer to the click and return that edge.
2246      */
2247
2248     /*
2249      * Check for corner click.
2250      */
2251     dx = (float)fabs(x - xv);
2252     dy = (float)fabs(y - yv);
2253     dist = (dx > dy ? dx : dy);
2254     if (dist < CORNER_TOLERANCE) {
2255         *xr = 2 * (int)xv;
2256         *yr = 2 * (int)yv;
2257     } else {
2258         /*
2259          * Check for centre click.
2260          */
2261         dx = (float)fabs(x - xs);
2262         dy = (float)fabs(y - ys);
2263         dist = (dx > dy ? dx : dy);
2264         if (dist < CENTRE_TOLERANCE) {
2265             *xr = 1 + 2 * (int)xs;
2266             *yr = 1 + 2 * (int)ys;
2267         } else {
2268             /*
2269              * Failing both of those, see which edge we're closer to.
2270              * Conveniently, this is simply done by testing the relative
2271              * magnitude of dx and dy (which are currently distances from
2272              * the square centre).
2273              */
2274             if (dx > dy) {
2275                 /* Vertical edge: x-coord of corner,
2276                  * y-coord of square centre. */
2277                 *xr = 2 * (int)xv;
2278                 *yr = 1 + 2 * (int)floor(ys);
2279             } else {
2280                 /* Horizontal edge: x-coord of square centre,
2281                  * y-coord of corner. */
2282                 *xr = 1 + 2 * (int)floor(xs);
2283                 *yr = 2 * (int)yv;
2284             }
2285         }
2286     }
2287 }
2288
2289 /*
2290  * Returns TRUE if it has made any change to the grid.
2291  */
2292 static int grid_draw_rect(game_state *state,
2293                           unsigned char *hedge, unsigned char *vedge,
2294                           int c, int really,
2295                           int x1, int y1, int x2, int y2)
2296 {
2297     int x, y;
2298     int changed = FALSE;
2299
2300     /*
2301      * Draw horizontal edges of rectangles.
2302      */
2303     for (x = x1; x < x2; x++)
2304         for (y = y1; y <= y2; y++)
2305             if (HRANGE(state,x,y)) {
2306                 int val = index(state,hedge,x,y);
2307                 if (y == y1 || y == y2)
2308                     val = c;
2309                 else if (c == 1)
2310                     val = 0;
2311                 changed = changed || (index(state,hedge,x,y) != val);
2312                 if (really)
2313                     index(state,hedge,x,y) = val;
2314             }
2315
2316     /*
2317      * Draw vertical edges of rectangles.
2318      */
2319     for (y = y1; y < y2; y++)
2320         for (x = x1; x <= x2; x++)
2321             if (VRANGE(state,x,y)) {
2322                 int val = index(state,vedge,x,y);
2323                 if (x == x1 || x == x2)
2324                     val = c;
2325                 else if (c == 1)
2326                     val = 0;
2327                 changed = changed || (index(state,vedge,x,y) != val);
2328                 if (really)
2329                     index(state,vedge,x,y) = val;
2330             }
2331
2332     return changed;
2333 }
2334
2335 static int ui_draw_rect(game_state *state, game_ui *ui,
2336                         unsigned char *hedge, unsigned char *vedge, int c,
2337                         int really)
2338 {
2339     return grid_draw_rect(state, hedge, vedge, c, really,
2340                           ui->x1, ui->y1, ui->x2, ui->y2);
2341 }
2342
2343 static void game_changed_state(game_ui *ui, game_state *oldstate,
2344                                game_state *newstate)
2345 {
2346 }
2347
2348 struct game_drawstate {
2349     int started;
2350     int w, h, tilesize;
2351     unsigned long *visible;
2352 };
2353
2354 static char *interpret_move(game_state *from, game_ui *ui, game_drawstate *ds,
2355                             int x, int y, int button)
2356 {
2357     int xc, yc;
2358     int startdrag = FALSE, enddrag = FALSE, active = FALSE;
2359     char buf[80], *ret;
2360
2361     button &= ~MOD_MASK;
2362
2363     if (button == LEFT_BUTTON) {
2364         startdrag = TRUE;
2365     } else if (button == LEFT_RELEASE) {
2366         enddrag = TRUE;
2367     } else if (button != LEFT_DRAG) {
2368         return NULL;
2369     }
2370
2371     coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
2372
2373     if (startdrag &&
2374         xc >= 0 && xc <= 2*from->w &&
2375         yc >= 0 && yc <= 2*from->h) {
2376
2377         ui->drag_start_x = xc;
2378         ui->drag_start_y = yc;
2379         ui->drag_end_x = xc;
2380         ui->drag_end_y = yc;
2381         ui->dragged = FALSE;
2382         active = TRUE;
2383     }
2384
2385     if (ui->drag_start_x >= 0 &&
2386         (xc != ui->drag_end_x || yc != ui->drag_end_y)) {
2387         int t;
2388
2389         ui->drag_end_x = xc;
2390         ui->drag_end_y = yc;
2391         ui->dragged = TRUE;
2392         active = TRUE;
2393
2394         if (xc >= 0 && xc <= 2*from->w &&
2395             yc >= 0 && yc <= 2*from->h) {
2396             ui->x1 = ui->drag_start_x;
2397             ui->x2 = ui->drag_end_x;
2398             if (ui->x2 < ui->x1) { t = ui->x1; ui->x1 = ui->x2; ui->x2 = t; }
2399
2400             ui->y1 = ui->drag_start_y;
2401             ui->y2 = ui->drag_end_y;
2402             if (ui->y2 < ui->y1) { t = ui->y1; ui->y1 = ui->y2; ui->y2 = t; }
2403
2404             ui->x1 = ui->x1 / 2;               /* rounds down */
2405             ui->x2 = (ui->x2+1) / 2;           /* rounds up */
2406             ui->y1 = ui->y1 / 2;               /* rounds down */
2407             ui->y2 = (ui->y2+1) / 2;           /* rounds up */
2408         } else {
2409             ui->x1 = -1;
2410             ui->y1 = -1;
2411             ui->x2 = -1;
2412             ui->y2 = -1;
2413         }
2414     }
2415
2416     ret = NULL;
2417
2418     if (enddrag && (ui->drag_start_x >= 0)) {
2419         if (xc >= 0 && xc <= 2*from->w &&
2420             yc >= 0 && yc <= 2*from->h) {
2421
2422             if (ui->dragged) {
2423                 if (ui_draw_rect(from, ui, from->hedge,
2424                                  from->vedge, 1, FALSE)) {
2425                     sprintf(buf, "R%d,%d,%d,%d",
2426                             ui->x1, ui->y1, ui->x2 - ui->x1, ui->y2 - ui->y1);
2427                     ret = dupstr(buf);
2428                 }
2429             } else {
2430                 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
2431                     sprintf(buf, "H%d,%d", xc/2, yc/2);
2432                     ret = dupstr(buf);
2433                 }
2434                 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
2435                     sprintf(buf, "V%d,%d", xc/2, yc/2);
2436                     ret = dupstr(buf);
2437                 }
2438             }
2439         }
2440
2441         ui->drag_start_x = -1;
2442         ui->drag_start_y = -1;
2443         ui->drag_end_x = -1;
2444         ui->drag_end_y = -1;
2445         ui->x1 = -1;
2446         ui->y1 = -1;
2447         ui->x2 = -1;
2448         ui->y2 = -1;
2449         ui->dragged = FALSE;
2450         active = TRUE;
2451     }
2452
2453     if (ret)
2454         return ret;                    /* a move has been made */
2455     else if (active)
2456         return "";                     /* UI activity has occurred */
2457     else
2458         return NULL;
2459 }
2460
2461 static game_state *execute_move(game_state *from, char *move)
2462 {
2463     game_state *ret;
2464     int x1, y1, x2, y2, mode;
2465
2466     if (move[0] == 'S') {
2467         char *p = move+1;
2468         int x, y;
2469
2470         ret = dup_game(from);
2471         ret->cheated = TRUE;
2472
2473         for (y = 0; y < ret->h; y++)
2474             for (x = 1; x < ret->w; x++) {
2475                 vedge(ret, x, y) = (*p == '1');
2476                 if (*p) p++;
2477             }
2478         for (y = 1; y < ret->h; y++)
2479             for (x = 0; x < ret->w; x++) {
2480                 hedge(ret, x, y) = (*p == '1');
2481                 if (*p) p++;
2482             }
2483
2484         sfree(ret->correct);
2485         ret->correct = get_correct(ret);
2486
2487         return ret;
2488
2489     } else if (move[0] == 'R' &&
2490         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
2491         x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
2492         y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
2493         x2 += x1;
2494         y2 += y1;
2495         mode = move[0];
2496     } else if ((move[0] == 'H' || move[0] == 'V') &&
2497                sscanf(move+1, "%d,%d", &x1, &y1) == 2 &&
2498                (move[0] == 'H' ? HRANGE(from, x1, y1) :
2499                 VRANGE(from, x1, y1))) {
2500         mode = move[0];
2501     } else
2502         return NULL;                   /* can't parse move string */
2503
2504     ret = dup_game(from);
2505
2506     if (mode == 'R') {
2507         grid_draw_rect(ret, ret->hedge, ret->vedge, 1, TRUE, x1, y1, x2, y2);
2508     } else if (mode == 'H') {
2509         hedge(ret,x1,y1) = !hedge(ret,x1,y1);
2510     } else if (mode == 'V') {
2511         vedge(ret,x1,y1) = !vedge(ret,x1,y1);
2512     }
2513
2514     sfree(ret->correct);
2515     ret->correct = get_correct(ret);
2516
2517     /*
2518      * We've made a real change to the grid. Check to see
2519      * if the game has been completed.
2520      */
2521     if (!ret->completed) {
2522         int x, y, ok;
2523
2524         ok = TRUE;
2525         for (x = 0; x < ret->w; x++)
2526             for (y = 0; y < ret->h; y++)
2527                 if (!index(ret, ret->correct, x, y))
2528                     ok = FALSE;
2529
2530         if (ok)
2531             ret->completed = TRUE;
2532     }
2533
2534     return ret;
2535 }
2536
2537 /* ----------------------------------------------------------------------
2538  * Drawing routines.
2539  */
2540
2541 #define CORRECT (1L<<16)
2542
2543 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
2544 #define MAX4(x,y,z,w) ( max(max(x,y),max(z,w)) )
2545
2546 static void game_compute_size(game_params *params, int tilesize,
2547                               int *x, int *y)
2548 {
2549     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2550     struct { int tilesize; } ads, *ds = &ads;
2551     ads.tilesize = tilesize;
2552
2553     *x = params->w * TILE_SIZE + 2*BORDER + 1;
2554     *y = params->h * TILE_SIZE + 2*BORDER + 1;
2555 }
2556
2557 static void game_set_size(drawing *dr, game_drawstate *ds,
2558                           game_params *params, int tilesize)
2559 {
2560     ds->tilesize = tilesize;
2561 }
2562
2563 static float *game_colours(frontend *fe, int *ncolours)
2564 {
2565     float *ret = snewn(3 * NCOLOURS, float);
2566
2567     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2568
2569     ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2570     ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2571     ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2572
2573     ret[COL_DRAG * 3 + 0] = 1.0F;
2574     ret[COL_DRAG * 3 + 1] = 0.0F;
2575     ret[COL_DRAG * 3 + 2] = 0.0F;
2576
2577     ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2578     ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2579     ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2580
2581     ret[COL_LINE * 3 + 0] = 0.0F;
2582     ret[COL_LINE * 3 + 1] = 0.0F;
2583     ret[COL_LINE * 3 + 2] = 0.0F;
2584
2585     ret[COL_TEXT * 3 + 0] = 0.0F;
2586     ret[COL_TEXT * 3 + 1] = 0.0F;
2587     ret[COL_TEXT * 3 + 2] = 0.0F;
2588
2589     *ncolours = NCOLOURS;
2590     return ret;
2591 }
2592
2593 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2594 {
2595     struct game_drawstate *ds = snew(struct game_drawstate);
2596     int i;
2597
2598     ds->started = FALSE;
2599     ds->w = state->w;
2600     ds->h = state->h;
2601     ds->visible = snewn(ds->w * ds->h, unsigned long);
2602     ds->tilesize = 0;                  /* not decided yet */
2603     for (i = 0; i < ds->w * ds->h; i++)
2604         ds->visible[i] = 0xFFFF;
2605
2606     return ds;
2607 }
2608
2609 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2610 {
2611     sfree(ds->visible);
2612     sfree(ds);
2613 }
2614
2615 static void draw_tile(drawing *dr, game_drawstate *ds, game_state *state,
2616                       int x, int y, unsigned char *hedge, unsigned char *vedge,
2617                       unsigned char *corners, int correct)
2618 {
2619     int cx = COORD(x), cy = COORD(y);
2620     char str[80];
2621
2622     draw_rect(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
2623     draw_rect(dr, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
2624               correct ? COL_CORRECT : COL_BACKGROUND);
2625
2626     if (grid(state,x,y)) {
2627         sprintf(str, "%d", grid(state,x,y));
2628         draw_text(dr, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
2629                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
2630     }
2631
2632     /*
2633      * Draw edges.
2634      */
2635     if (!HRANGE(state,x,y) || index(state,hedge,x,y))
2636         draw_rect(dr, cx, cy, TILE_SIZE+1, 2,
2637                   HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
2638                   COL_LINE);
2639     if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
2640         draw_rect(dr, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
2641                   HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
2642                   COL_LINE);
2643     if (!VRANGE(state,x,y) || index(state,vedge,x,y))
2644         draw_rect(dr, cx, cy, 2, TILE_SIZE+1,
2645                   VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
2646                   COL_LINE);
2647     if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
2648         draw_rect(dr, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
2649                   VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
2650                   COL_LINE);
2651
2652     /*
2653      * Draw corners.
2654      */
2655     if (index(state,corners,x,y))
2656         draw_rect(dr, cx, cy, 2, 2,
2657                   COLOUR(index(state,corners,x,y)));
2658     if (x+1 < state->w && index(state,corners,x+1,y))
2659         draw_rect(dr, cx+TILE_SIZE-1, cy, 2, 2,
2660                   COLOUR(index(state,corners,x+1,y)));
2661     if (y+1 < state->h && index(state,corners,x,y+1))
2662         draw_rect(dr, cx, cy+TILE_SIZE-1, 2, 2,
2663                   COLOUR(index(state,corners,x,y+1)));
2664     if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
2665         draw_rect(dr, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
2666                   COLOUR(index(state,corners,x+1,y+1)));
2667
2668     draw_update(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
2669 }
2670
2671 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2672                  game_state *state, int dir, game_ui *ui,
2673                  float animtime, float flashtime)
2674 {
2675     int x, y;
2676     unsigned char *hedge, *vedge, *corners;
2677
2678     if (ui->dragged) {
2679         hedge = snewn(state->w*state->h, unsigned char);
2680         vedge = snewn(state->w*state->h, unsigned char);
2681         memcpy(hedge, state->hedge, state->w*state->h);
2682         memcpy(vedge, state->vedge, state->w*state->h);
2683         ui_draw_rect(state, ui, hedge, vedge, 2, TRUE);
2684     } else {
2685         hedge = state->hedge;
2686         vedge = state->vedge;
2687     }
2688
2689     corners = snewn(state->w * state->h, unsigned char);
2690     memset(corners, 0, state->w * state->h);
2691     for (x = 0; x < state->w; x++)
2692         for (y = 0; y < state->h; y++) {
2693             if (x > 0) {
2694                 int e = index(state, vedge, x, y);
2695                 if (index(state,corners,x,y) < e)
2696                     index(state,corners,x,y) = e;
2697                 if (y+1 < state->h &&
2698                     index(state,corners,x,y+1) < e)
2699                     index(state,corners,x,y+1) = e;
2700             }
2701             if (y > 0) {
2702                 int e = index(state, hedge, x, y);
2703                 if (index(state,corners,x,y) < e)
2704                     index(state,corners,x,y) = e;
2705                 if (x+1 < state->w &&
2706                     index(state,corners,x+1,y) < e)
2707                     index(state,corners,x+1,y) = e;
2708             }
2709         }
2710
2711     if (!ds->started) {
2712         draw_rect(dr, 0, 0,
2713                   state->w * TILE_SIZE + 2*BORDER + 1,
2714                   state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
2715         draw_rect(dr, COORD(0)-1, COORD(0)-1,
2716                   ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
2717         ds->started = TRUE;
2718         draw_update(dr, 0, 0,
2719                     state->w * TILE_SIZE + 2*BORDER + 1,
2720                     state->h * TILE_SIZE + 2*BORDER + 1);
2721     }
2722
2723     for (x = 0; x < state->w; x++)
2724         for (y = 0; y < state->h; y++) {
2725             unsigned long c = 0;
2726
2727             if (HRANGE(state,x,y))
2728                 c |= index(state,hedge,x,y);
2729             if (HRANGE(state,x,y+1))
2730                 c |= index(state,hedge,x,y+1) << 2;
2731             if (VRANGE(state,x,y))
2732                 c |= index(state,vedge,x,y) << 4;
2733             if (VRANGE(state,x+1,y))
2734                 c |= index(state,vedge,x+1,y) << 6;
2735             c |= index(state,corners,x,y) << 8;
2736             if (x+1 < state->w)
2737                 c |= index(state,corners,x+1,y) << 10;
2738             if (y+1 < state->h)
2739                 c |= index(state,corners,x,y+1) << 12;
2740             if (x+1 < state->w && y+1 < state->h)
2741                 /* cast to prevent 2<<14 sign-extending on promotion to long */
2742                 c |= (unsigned long)index(state,corners,x+1,y+1) << 14;
2743             if (index(state, state->correct, x, y) && !flashtime)
2744                 c |= CORRECT;
2745
2746             if (index(ds,ds->visible,x,y) != c) {
2747                 draw_tile(dr, ds, state, x, y, hedge, vedge, corners,
2748                           (c & CORRECT) ? 1 : 0);
2749                 index(ds,ds->visible,x,y) = c;
2750             }
2751         }
2752
2753     {
2754         char buf[256];
2755
2756         if (ui->x1 >= 0 && ui->y1 >= 0 &&
2757             ui->x2 >= 0 && ui->y2 >= 0) {
2758             sprintf(buf, "%dx%d ",
2759                     ui->x2-ui->x1,
2760                     ui->y2-ui->y1);
2761         } else {
2762             buf[0] = '\0';
2763         }
2764
2765         if (state->cheated)
2766             strcat(buf, "Auto-solved.");
2767         else if (state->completed)
2768             strcat(buf, "COMPLETED!");
2769
2770         status_bar(dr, buf);
2771     }
2772
2773     if (hedge != state->hedge) {
2774         sfree(hedge);
2775         sfree(vedge);
2776     }
2777
2778     sfree(corners);
2779 }
2780
2781 static float game_anim_length(game_state *oldstate,
2782                               game_state *newstate, int dir, game_ui *ui)
2783 {
2784     return 0.0F;
2785 }
2786
2787 static float game_flash_length(game_state *oldstate,
2788                                game_state *newstate, int dir, game_ui *ui)
2789 {
2790     if (!oldstate->completed && newstate->completed &&
2791         !oldstate->cheated && !newstate->cheated)
2792         return FLASH_TIME;
2793     return 0.0F;
2794 }
2795
2796 static int game_timing_state(game_state *state, game_ui *ui)
2797 {
2798     return TRUE;
2799 }
2800
2801 static void game_print_size(game_params *params, float *x, float *y)
2802 {
2803     int pw, ph;
2804
2805     /*
2806      * I'll use 5mm squares by default.
2807      */
2808     game_compute_size(params, 500, &pw, &ph);
2809     *x = pw / 100.0;
2810     *y = ph / 100.0;
2811 }
2812
2813 static void game_print(drawing *dr, game_state *state, int tilesize)
2814 {
2815     int w = state->w, h = state->h;
2816     int ink = print_mono_colour(dr, 0);
2817     int x, y;
2818
2819     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2820     game_drawstate ads, *ds = &ads;
2821     game_set_size(dr, ds, NULL, tilesize);
2822
2823     /*
2824      * Border.
2825      */
2826     print_line_width(dr, TILE_SIZE / 10);
2827     draw_rect_outline(dr, COORD(0), COORD(0), w*TILE_SIZE, h*TILE_SIZE, ink);
2828
2829     /*
2830      * Grid. We have to make the grid lines particularly thin,
2831      * because users will be drawing lines _along_ them and we want
2832      * those lines to be visible.
2833      */
2834     print_line_width(dr, TILE_SIZE / 256);
2835     for (x = 1; x < w; x++)
2836         draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), ink);
2837     for (y = 1; y < h; y++)
2838         draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), ink);
2839
2840     /*
2841      * Solution.
2842      */
2843     print_line_width(dr, TILE_SIZE / 10);
2844     for (y = 0; y <= h; y++)
2845         for (x = 0; x <= w; x++) {
2846             if (HRANGE(state,x,y) && hedge(state,x,y))
2847                 draw_line(dr, COORD(x), COORD(y), COORD(x+1), COORD(y), ink);
2848             if (VRANGE(state,x,y) && vedge(state,x,y))
2849                 draw_line(dr, COORD(x), COORD(y), COORD(x), COORD(y+1), ink);
2850         }
2851
2852     /*
2853      * Clues.
2854      */
2855     for (y = 0; y < h; y++)
2856         for (x = 0; x < w; x++)
2857             if (grid(state,x,y)) {
2858                 char str[80];
2859                 sprintf(str, "%d", grid(state,x,y));
2860                 draw_text(dr, COORD(x)+TILE_SIZE/2, COORD(y)+TILE_SIZE/2,
2861                           FONT_VARIABLE, TILE_SIZE/2,
2862                           ALIGN_HCENTRE | ALIGN_VCENTRE, ink, str);
2863             }
2864 }
2865
2866 #ifdef COMBINED
2867 #define thegame rect
2868 #endif
2869
2870 const struct game thegame = {
2871     "Rectangles", "games.rectangles", "rectangles",
2872     default_params,
2873     game_fetch_preset,
2874     decode_params,
2875     encode_params,
2876     free_params,
2877     dup_params,
2878     TRUE, game_configure, custom_params,
2879     validate_params,
2880     new_game_desc,
2881     validate_desc,
2882     new_game,
2883     dup_game,
2884     free_game,
2885     TRUE, solve_game,
2886     TRUE, game_can_format_as_text_now, game_text_format,
2887     new_ui,
2888     free_ui,
2889     encode_ui,
2890     decode_ui,
2891     game_changed_state,
2892     interpret_move,
2893     execute_move,
2894     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2895     game_colours,
2896     game_new_drawstate,
2897     game_free_drawstate,
2898     game_redraw,
2899     game_anim_length,
2900     game_flash_length,
2901     TRUE, FALSE, game_print_size, game_print,
2902     TRUE,                              /* wants_statusbar */
2903     FALSE, game_timing_state,
2904     0,                                 /* flags */
2905 };