chiark / gitweb /
Added an automatic `Solve' feature to most games. This is useful for
[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 on singleton removal by making an aesthetic choice
13  *    about which of the options to take.
14  * 
15  *  - When doing the 3x3 trick in singleton removal, limit the size
16  *    of the generated rectangles in accordance with the max
17  *    rectangle size.
18  * 
19  *  - It might be interesting to deliberately try to place
20  *    numbers so as to reduce alternative solution patterns. I
21  *    doubt we can do a perfect job of this, but we can make a
22  *    start by, for example, noticing pairs of 2-rects
23  *    alongside one another and _not_ putting their numbers at
24  *    opposite ends.
25  *
26  *  - If we start by sorting the rectlist in descending order
27  *    of area, we might be able to bias our random number
28  *    selection to produce a few large rectangles more often
29  *    than oodles of small ones? Unsure, but might be worth a
30  *    try.
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <assert.h>
37 #include <ctype.h>
38 #include <math.h>
39
40 #include "puzzles.h"
41
42 enum {
43     COL_BACKGROUND,
44     COL_CORRECT,
45     COL_LINE,
46     COL_TEXT,
47     COL_GRID,
48     COL_DRAG,
49     NCOLOURS
50 };
51
52 struct game_params {
53     int w, h;
54     float expandfactor;
55 };
56
57 #define INDEX(state, x, y)    (((y) * (state)->w) + (x))
58 #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
59 #define grid(state,x,y)       index(state, (state)->grid, x, y)
60 #define vedge(state,x,y)      index(state, (state)->vedge, x, y)
61 #define hedge(state,x,y)      index(state, (state)->hedge, x, y)
62
63 #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
64                                 (y) >= dy && (y) < (state)->h )
65 #define RANGE(state,x,y)  CRANGE(state,x,y,0,0)
66 #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
67 #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
68
69 #define TILE_SIZE 24
70 #define BORDER 18
71
72 #define CORNER_TOLERANCE 0.15F
73 #define CENTRE_TOLERANCE 0.15F
74
75 #define FLASH_TIME 0.13F
76
77 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
78 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
79
80 struct game_state {
81     int w, h;
82     int *grid;                         /* contains the numbers */
83     unsigned char *vedge;              /* (w+1) x h */
84     unsigned char *hedge;              /* w x (h+1) */
85     int completed, cheated;
86 };
87
88 static game_params *default_params(void)
89 {
90     game_params *ret = snew(game_params);
91
92     ret->w = ret->h = 7;
93     ret->expandfactor = 0.0F;
94
95     return ret;
96 }
97
98 static int game_fetch_preset(int i, char **name, game_params **params)
99 {
100     game_params *ret;
101     int w, h;
102     char buf[80];
103
104     switch (i) {
105       case 0: w = 7, h = 7; break;
106       case 1: w = 11, h = 11; break;
107       case 2: w = 15, h = 15; break;
108       case 3: w = 19, h = 19; break;
109       default: return FALSE;
110     }
111
112     sprintf(buf, "%dx%d", w, h);
113     *name = dupstr(buf);
114     *params = ret = snew(game_params);
115     ret->w = w;
116     ret->h = h;
117     ret->expandfactor = 0.0F;
118     return TRUE;
119 }
120
121 static void free_params(game_params *params)
122 {
123     sfree(params);
124 }
125
126 static game_params *dup_params(game_params *params)
127 {
128     game_params *ret = snew(game_params);
129     *ret = *params;                    /* structure copy */
130     return ret;
131 }
132
133 static game_params *decode_params(char const *string)
134 {
135     game_params *ret = default_params();
136
137     ret->w = ret->h = atoi(string);
138     ret->expandfactor = 0.0F;
139     while (*string && isdigit((unsigned char)*string)) string++;
140     if (*string == 'x') {
141         string++;
142         ret->h = atoi(string);
143         while (*string && isdigit((unsigned char)*string)) string++;
144     }
145     if (*string == 'e') {
146         string++;
147         ret->expandfactor = atof(string);
148     }
149
150     return ret;
151 }
152
153 static char *encode_params(game_params *params)
154 {
155     char data[256];
156
157     sprintf(data, "%dx%d", params->w, params->h);
158
159     return dupstr(data);
160 }
161
162 static config_item *game_configure(game_params *params)
163 {
164     config_item *ret;
165     char buf[80];
166
167     ret = snewn(5, config_item);
168
169     ret[0].name = "Width";
170     ret[0].type = C_STRING;
171     sprintf(buf, "%d", params->w);
172     ret[0].sval = dupstr(buf);
173     ret[0].ival = 0;
174
175     ret[1].name = "Height";
176     ret[1].type = C_STRING;
177     sprintf(buf, "%d", params->h);
178     ret[1].sval = dupstr(buf);
179     ret[1].ival = 0;
180
181     ret[2].name = "Expansion factor";
182     ret[2].type = C_STRING;
183     sprintf(buf, "%g", params->expandfactor);
184     ret[2].sval = dupstr(buf);
185     ret[2].ival = 0;
186
187     ret[3].name = NULL;
188     ret[3].type = C_END;
189     ret[3].sval = NULL;
190     ret[3].ival = 0;
191
192     return ret;
193 }
194
195 static game_params *custom_params(config_item *cfg)
196 {
197     game_params *ret = snew(game_params);
198
199     ret->w = atoi(cfg[0].sval);
200     ret->h = atoi(cfg[1].sval);
201     ret->expandfactor = atof(cfg[2].sval);
202
203     return ret;
204 }
205
206 static char *validate_params(game_params *params)
207 {
208     if (params->w <= 0 && params->h <= 0)
209         return "Width and height must both be greater than zero";
210     if (params->w < 2 && params->h < 2)
211         return "Grid area must be greater than one";
212     if (params->expandfactor < 0.0F)
213         return "Expansion factor may not be negative";
214     return NULL;
215 }
216
217 struct rect {
218     int x, y;
219     int w, h;
220 };
221
222 struct rectlist {
223     struct rect *rects;
224     int n;
225 };
226
227 static struct rectlist *get_rectlist(game_params *params, int *grid)
228 {
229     int rw, rh;
230     int x, y;
231     int maxarea;
232     struct rect *rects = NULL;
233     int nrects = 0, rectsize = 0;
234
235     /*
236      * Maximum rectangle area is 1/6 of total grid size, unless
237      * this means we can't place any rectangles at all in which
238      * case we set it to 2 at minimum.
239      */
240     maxarea = params->w * params->h / 6;
241     if (maxarea < 2)
242         maxarea = 2;
243
244     for (rw = 1; rw <= params->w; rw++)
245         for (rh = 1; rh <= params->h; rh++) {
246             if (rw * rh > maxarea)
247                 continue;
248             if (rw * rh == 1)
249                 continue;
250             for (x = 0; x <= params->w - rw; x++)
251                 for (y = 0; y <= params->h - rh; y++) {
252                     if (nrects >= rectsize) {
253                         rectsize = nrects + 256;
254                         rects = sresize(rects, rectsize, struct rect);
255                     }
256
257                     rects[nrects].x = x;
258                     rects[nrects].y = y;
259                     rects[nrects].w = rw;
260                     rects[nrects].h = rh;
261                     nrects++;
262                 }
263         }
264
265     if (nrects > 0) {
266         struct rectlist *ret;
267         ret = snew(struct rectlist);
268         ret->rects = rects;
269         ret->n = nrects;
270         return ret;
271     } else {
272         assert(rects == NULL);         /* hence no need to free */
273         return NULL;
274     }
275 }
276
277 static void free_rectlist(struct rectlist *list)
278 {
279     sfree(list->rects);
280     sfree(list);
281 }
282
283 static void place_rect(game_params *params, int *grid, struct rect r)
284 {
285     int idx = INDEX(params, r.x, r.y);
286     int x, y;
287
288     for (x = r.x; x < r.x+r.w; x++)
289         for (y = r.y; y < r.y+r.h; y++) {
290             index(params, grid, x, y) = idx;
291         }
292 #ifdef GENERATION_DIAGNOSTICS
293     printf("    placing rectangle at (%d,%d) size %d x %d\n",
294            r.x, r.y, r.w, r.h);
295 #endif
296 }
297
298 static struct rect find_rect(game_params *params, int *grid, int x, int y)
299 {
300     int idx, w, h;
301     struct rect r;
302
303     /*
304      * Find the top left of the rectangle.
305      */
306     idx = index(params, grid, x, y);
307
308     if (idx < 0) {
309         r.x = x;
310         r.y = y;
311         r.w = r.h = 1;
312         return r;                      /* 1x1 singleton here */
313     }
314
315     y = idx / params->w;
316     x = idx % params->w;
317
318     /*
319      * Find the width and height of the rectangle.
320      */
321     for (w = 1;
322          (x+w < params->w && index(params,grid,x+w,y)==idx);
323          w++);
324     for (h = 1;
325          (y+h < params->h && index(params,grid,x,y+h)==idx);
326          h++);
327
328     r.x = x;
329     r.y = y;
330     r.w = w;
331     r.h = h;
332
333     return r;
334 }
335
336 #ifdef GENERATION_DIAGNOSTICS
337 static void display_grid(game_params *params, int *grid, int *numbers, int all)
338 {
339     unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
340                                  unsigned char);
341     int x, y;
342     int r = (params->w*2+3);
343
344     memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
345
346     for (x = 0; x < params->w; x++)
347         for (y = 0; y < params->h; y++) {
348             int i = index(params, grid, x, y);
349             if (x == 0 || index(params, grid, x-1, y) != i)
350                 egrid[(2*y+2) * r + (2*x+1)] = 1;
351             if (x == params->w-1 || index(params, grid, x+1, y) != i)
352                 egrid[(2*y+2) * r + (2*x+3)] = 1;
353             if (y == 0 || index(params, grid, x, y-1) != i)
354                 egrid[(2*y+1) * r + (2*x+2)] = 1;
355             if (y == params->h-1 || index(params, grid, x, y+1) != i)
356                 egrid[(2*y+3) * r + (2*x+2)] = 1;
357         }
358
359     for (y = 1; y < 2*params->h+2; y++) {
360         for (x = 1; x < 2*params->w+2; x++) {
361             if (!((y|x)&1)) {
362                 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
363                 if (k || (all && numbers)) printf("%2d", k); else printf("  ");
364             } else if (!((y&x)&1)) {
365                 int v = egrid[y*r+x];
366                 if ((y&1) && v) v = '-';
367                 if ((x&1) && v) v = '|';
368                 if (!v) v = ' ';
369                 putchar(v);
370                 if (!(x&1)) putchar(v);
371             } else {
372                 int c, d = 0;
373                 if (egrid[y*r+(x+1)]) d |= 1;
374                 if (egrid[(y-1)*r+x]) d |= 2;
375                 if (egrid[y*r+(x-1)]) d |= 4;
376                 if (egrid[(y+1)*r+x]) d |= 8;
377                 c = " ??+?-++?+|+++++"[d];
378                 putchar(c);
379                 if (!(x&1)) putchar(c);
380             }
381         }
382         putchar('\n');
383     }
384
385     sfree(egrid);
386 }
387 #endif
388
389 struct game_aux_info {
390     int w, h;
391     unsigned char *vedge;              /* (w+1) x h */
392     unsigned char *hedge;              /* w x (h+1) */
393 };
394
395 static char *new_game_seed(game_params *params, random_state *rs,
396                            game_aux_info **aux)
397 {
398     int *grid, *numbers;
399     struct rectlist *list;
400     int x, y, y2, y2last, yx, run, i;
401     char *seed, *p;
402     game_params params2real, *params2 = &params2real;
403
404     /*
405      * Set up the smaller width and height which we will use to
406      * generate the base grid.
407      */
408     params2->w = params->w / (1.0F + params->expandfactor);
409     if (params2->w < 2 && params->w >= 2) params2->w = 2;
410     params2->h = params->h / (1.0F + params->expandfactor);
411     if (params2->h < 2 && params->h >= 2) params2->h = 2;
412
413     grid = snewn(params2->w * params2->h, int);
414
415     for (y = 0; y < params2->h; y++)
416         for (x = 0; x < params2->w; x++) {
417             index(params2, grid, x, y) = -1;
418         }
419
420     list = get_rectlist(params2, grid);
421     assert(list != NULL);
422
423     /*
424      * Place rectangles until we can't any more.
425      */
426     while (list->n > 0) {
427         int i, m;
428         struct rect r;
429
430         /*
431          * Pick a random rectangle.
432          */
433         i = random_upto(rs, list->n);
434         r = list->rects[i];
435
436         /*
437          * Place it.
438          */
439         place_rect(params2, grid, r);
440
441         /*
442          * Winnow the list by removing any rectangles which
443          * overlap this one.
444          */
445         m = 0;
446         for (i = 0; i < list->n; i++) {
447             struct rect s = list->rects[i];
448             if (s.x+s.w <= r.x || r.x+r.w <= s.x ||
449                 s.y+s.h <= r.y || r.y+r.h <= s.y)
450                 list->rects[m++] = s;
451         }
452         list->n = m;
453     }
454
455     free_rectlist(list);
456
457     /*
458      * Deal with singleton spaces remaining in the grid, one by
459      * one.
460      * 
461      * We do this by making a local change to the layout. There are
462      * several possibilities:
463      * 
464      *     +-----+-----+    Here, we can remove the singleton by
465      *     |     |     |    extending the 1x2 rectangle below it
466      *     +--+--+-----+    into a 1x3.
467      *     |  |  |     |
468      *     |  +--+     |
469      *     |  |  |     |
470      *     |  |  |     |
471      *     |  |  |     |
472      *     +--+--+-----+
473      * 
474      *     +--+--+--+       Here, that trick doesn't work: there's no
475      *     |     |  |       1 x n rectangle with the singleton at one
476      *     |     |  |       end. Instead, we extend a 1 x n rectangle
477      *     |     |  |       _out_ from the singleton, shaving a layer
478      *     +--+--+  |       off the end of another rectangle. So if we
479      *     |  |  |  |       extended up, we'd make our singleton part
480      *     |  +--+--+       of a 1x3 and generate a 1x2 where the 2x2
481      *     |  |     |       used to be; or we could extend right into
482      *     +--+-----+       a 2x1, turning the 1x3 into a 1x2.
483      * 
484      *     +-----+--+       Here, we can't even do _that_, since any
485      *     |     |  |       direction we choose to extend the singleton
486      *     +--+--+  |       will produce a new singleton as a result of
487      *     |  |  |  |       truncating one of the size-2 rectangles.
488      *     |  +--+--+       Fortunately, this case can _only_ occur when
489      *     |  |     |       a singleton is surrounded by four size-2s
490      *     +--+-----+       in this fashion; so instead we can simply
491      *                      replace the whole section with a single 3x3.
492      */
493     for (x = 0; x < params2->w; x++) {
494         for (y = 0; y < params2->h; y++) {
495             if (index(params2, grid, x, y) < 0) {
496                 int dirs[4], ndirs;
497
498 #ifdef GENERATION_DIAGNOSTICS
499                 display_grid(params2, grid, NULL, FALSE);
500                 printf("singleton at %d,%d\n", x, y);
501 #endif
502
503                 /*
504                  * Check in which directions we can feasibly extend
505                  * the singleton. We can extend in a particular
506                  * direction iff either:
507                  * 
508                  *  - the rectangle on that side of the singleton
509                  *    is not 2x1, and we are at one end of the edge
510                  *    of it we are touching
511                  * 
512                  *  - it is 2x1 but we are on its short side.
513                  * 
514                  * FIXME: we could plausibly choose between these
515                  * based on the sizes of the rectangles they would
516                  * create?
517                  */
518                 ndirs = 0;
519                 if (x < params2->w-1) {
520                     struct rect r = find_rect(params2, grid, x+1, y);
521                     if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
522                         dirs[ndirs++] = 1;   /* right */
523                 }
524                 if (y > 0) {
525                     struct rect r = find_rect(params2, grid, x, y-1);
526                     if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
527                         dirs[ndirs++] = 2;   /* up */
528                 }
529                 if (x > 0) {
530                     struct rect r = find_rect(params2, grid, x-1, y);
531                     if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
532                         dirs[ndirs++] = 4;   /* left */
533                 }
534                 if (y < params2->h-1) {
535                     struct rect r = find_rect(params2, grid, x, y+1);
536                     if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
537                         dirs[ndirs++] = 8;   /* down */
538                 }
539
540                 if (ndirs > 0) {
541                     int which, dir;
542                     struct rect r1, r2;
543
544                     which = random_upto(rs, ndirs);
545                     dir = dirs[which];
546
547                     switch (dir) {
548                       case 1:          /* right */
549                         assert(x < params2->w+1);
550 #ifdef GENERATION_DIAGNOSTICS
551                         printf("extending right\n");
552 #endif
553                         r1 = find_rect(params2, grid, x+1, y);
554                         r2.x = x;
555                         r2.y = y;
556                         r2.w = 1 + r1.w;
557                         r2.h = 1;
558                         if (r1.y == y)
559                             r1.y++;
560                         r1.h--;
561                         break;
562                       case 2:          /* up */
563                         assert(y > 0);
564 #ifdef GENERATION_DIAGNOSTICS
565                         printf("extending up\n");
566 #endif
567                         r1 = find_rect(params2, grid, x, y-1);
568                         r2.x = x;
569                         r2.y = r1.y;
570                         r2.w = 1;
571                         r2.h = 1 + r1.h;
572                         if (r1.x == x)
573                             r1.x++;
574                         r1.w--;
575                         break;
576                       case 4:          /* left */
577                         assert(x > 0);
578 #ifdef GENERATION_DIAGNOSTICS
579                         printf("extending left\n");
580 #endif
581                         r1 = find_rect(params2, grid, x-1, y);
582                         r2.x = r1.x;
583                         r2.y = y;
584                         r2.w = 1 + r1.w;
585                         r2.h = 1;
586                         if (r1.y == y)
587                             r1.y++;
588                         r1.h--;
589                         break;
590                       case 8:          /* down */
591                         assert(y < params2->h+1);
592 #ifdef GENERATION_DIAGNOSTICS
593                         printf("extending down\n");
594 #endif
595                         r1 = find_rect(params2, grid, x, y+1);
596                         r2.x = x;
597                         r2.y = y;
598                         r2.w = 1;
599                         r2.h = 1 + r1.h;
600                         if (r1.x == x)
601                             r1.x++;
602                         r1.w--;
603                         break;
604                     }
605                     if (r1.h > 0 && r1.w > 0)
606                         place_rect(params2, grid, r1);
607                     place_rect(params2, grid, r2);
608                 } else {
609 #ifndef NDEBUG
610                     /*
611                      * Sanity-check that there really is a 3x3
612                      * rectangle surrounding this singleton and it
613                      * contains absolutely everything we could
614                      * possibly need.
615                      */
616                     {
617                         int xx, yy;
618                         assert(x > 0 && x < params2->w-1);
619                         assert(y > 0 && y < params2->h-1);
620
621                         for (xx = x-1; xx <= x+1; xx++)
622                             for (yy = y-1; yy <= y+1; yy++) {
623                                 struct rect r = find_rect(params2,grid,xx,yy);
624                                 assert(r.x >= x-1);
625                                 assert(r.y >= y-1);
626                                 assert(r.x+r.w-1 <= x+1);
627                                 assert(r.y+r.h-1 <= y+1);
628                             }
629                     }
630 #endif
631                     
632 #ifdef GENERATION_DIAGNOSTICS
633                     printf("need the 3x3 trick\n");
634 #endif
635
636                     /*
637                      * FIXME: If the maximum rectangle area for
638                      * this grid is less than 9, we ought to
639                      * subdivide the 3x3 in some fashion. There are
640                      * five other possibilities:
641                      * 
642                      *  - a 6 and a 3
643                      *  - a 4, a 3 and a 2
644                      *  - three 3s
645                      *  - a 3 and three 2s (two different arrangements).
646                      */
647
648                     {
649                         struct rect r;
650                         r.x = x-1;
651                         r.y = y-1;
652                         r.w = r.h = 3;
653                         place_rect(params2, grid, r);
654                     }
655                 }
656             }
657         }
658     }
659
660     /*
661      * We have now constructed a grid of the size specified in
662      * params2. Now we extend it into a grid of the size specified
663      * in params. We do this in two passes: we extend it vertically
664      * until it's the right height, then we transpose it, then
665      * extend it vertically again (getting it effectively the right
666      * width), then finally transpose again.
667      */
668     for (i = 0; i < 2; i++) {
669         int *grid2, *expand, *where;
670         game_params params3real, *params3 = &params3real;
671
672 #ifdef GENERATION_DIAGNOSTICS
673         printf("before expansion:\n");
674         display_grid(params2, grid, NULL, TRUE);
675 #endif
676
677         /*
678          * Set up the new grid.
679          */
680         grid2 = snewn(params2->w * params->h, int);
681         expand = snewn(params2->h-1, int);
682         where = snewn(params2->w, int);
683         params3->w = params2->w;
684         params3->h = params->h;
685
686         /*
687          * Decide which horizontal edges are going to get expanded,
688          * and by how much.
689          */
690         for (y = 0; y < params2->h-1; y++)
691             expand[y] = 0;
692         for (y = params2->h; y < params->h; y++) {
693             x = random_upto(rs, params2->h-1);
694             expand[x]++;
695         }
696
697 #ifdef GENERATION_DIAGNOSTICS
698         printf("expand[] = {");
699         for (y = 0; y < params2->h-1; y++)
700             printf(" %d", expand[y]);
701         printf(" }\n");
702 #endif
703
704         /*
705          * Perform the expansion. The way this works is that we
706          * alternately:
707          * 
708          *  - copy a row from grid into grid2
709          * 
710          *  - invent some number of additional rows in grid2 where
711          *    there was previously only a horizontal line between
712          *    rows in grid, and make random decisions about where
713          *    among these to place each rectangle edge that ran
714          *    along this line.
715          */
716         for (y = y2 = y2last = 0; y < params2->h; y++) {
717             /*
718              * Copy a single line from row y of grid into row y2 of
719              * grid2.
720              */
721             for (x = 0; x < params2->w; x++) {
722                 int val = index(params2, grid, x, y);
723                 if (val / params2->w == y &&   /* rect starts on this line */
724                     (y2 == 0 ||        /* we're at the very top, or... */
725                      index(params3, grid2, x, y2-1) / params3->w < y2last
726                                        /* this rect isn't already started */))
727                     index(params3, grid2, x, y2) =
728                     INDEX(params3, val % params2->w, y2);
729                 else
730                     index(params3, grid2, x, y2) =
731                     index(params3, grid2, x, y2-1);
732             }
733
734             /*
735              * If that was the last line, terminate the loop early.
736              */
737             if (++y2 == params3->h)
738                 break;
739
740             y2last = y2;
741
742             /*
743              * Invent some number of additional lines. First walk
744              * along this line working out where to put all the
745              * edges that coincide with it.
746              */
747             yx = -1;
748             for (x = 0; x < params2->w; x++) {
749                 if (index(params2, grid, x, y) !=
750                     index(params2, grid, x, y+1)) {
751                     /*
752                      * This is a horizontal edge, so it needs
753                      * placing.
754                      */
755                     if (x == 0 ||
756                         (index(params2, grid, x-1, y) !=
757                          index(params2, grid, x, y) &&
758                          index(params2, grid, x-1, y+1) !=
759                          index(params2, grid, x, y+1))) {
760                         /*
761                          * Here we have the chance to make a new
762                          * decision.
763                          */
764                         yx = random_upto(rs, expand[y]+1);
765                     } else {
766                         /*
767                          * Here we just reuse the previous value of
768                          * yx.
769                          */
770                     }
771                 } else
772                     yx = -1;
773                 where[x] = yx;
774             }
775
776             for (yx = 0; yx < expand[y]; yx++) {
777                 /*
778                  * Invent a single row. For each square in the row,
779                  * we copy the grid entry from the square above it,
780                  * unless we're starting the new rectangle here.
781                  */
782                 for (x = 0; x < params2->w; x++) {
783                     if (yx == where[x]) {
784                         int val = index(params2, grid, x, y+1);
785                         val %= params2->w;
786                         val = INDEX(params3, val, y2);
787                         index(params3, grid2, x, y2) = val;
788                     } else
789                         index(params3, grid2, x, y2) = 
790                         index(params3, grid2, x, y2-1);
791                 }
792
793                 y2++;
794             }
795         }
796
797         sfree(expand);
798         sfree(where);
799
800 #ifdef GENERATION_DIAGNOSTICS
801         printf("after expansion:\n");
802         display_grid(params3, grid2, NULL, TRUE);
803 #endif
804         /*
805          * Transpose.
806          */
807         params2->w = params3->h;
808         params2->h = params3->w;
809         sfree(grid);
810         grid = snewn(params2->w * params2->h, int);
811         for (x = 0; x < params2->w; x++)
812             for (y = 0; y < params2->h; y++) {
813                 int idx1 = INDEX(params2, x, y);
814                 int idx2 = INDEX(params3, y, x);
815                 int tmp;
816
817                 tmp = grid2[idx2];
818                 tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
819                 grid[idx1] = tmp;
820             }
821
822         sfree(grid2);
823
824         {
825             int tmp;
826             tmp = params->w;
827             params->w = params->h;
828             params->h = tmp;
829         }
830
831 #ifdef GENERATION_DIAGNOSTICS
832         printf("after transposition:\n");
833         display_grid(params2, grid, NULL, TRUE);
834 #endif
835     }
836
837     /*
838      * Store the rectangle data in the game_aux_info.
839      */
840     {
841         game_aux_info *ai = snew(game_aux_info);
842
843         ai->w = params->w;
844         ai->h = params->h;
845         ai->vedge = snewn(ai->w * ai->h, unsigned char);
846         ai->hedge = snewn(ai->w * ai->h, unsigned char);
847
848         for (y = 0; y < params->h; y++)
849             for (x = 1; x < params->w; x++) {
850                 vedge(ai, x, y) =
851                     index(params, grid, x, y) != index(params, grid, x-1, y);
852             }
853         for (y = 1; y < params->h; y++)
854             for (x = 0; x < params->w; x++) {
855                 hedge(ai, x, y) =
856                     index(params, grid, x, y) != index(params, grid, x, y-1);
857             }
858
859         *aux = ai;
860     }
861
862     /*
863      * Place numbers.
864      */
865     numbers = snewn(params->w * params->h, int);
866
867     for (y = 0; y < params->h; y++)
868         for (x = 0; x < params->w; x++) {
869             index(params, numbers, x, y) = 0;
870         }
871
872     for (x = 0; x < params->w; x++) {
873         for (y = 0; y < params->h; y++) {
874             int idx = INDEX(params, x, y);
875             if (index(params, grid, x, y) == idx) {
876                 struct rect r = find_rect(params, grid, x, y);
877                 int n, xx, yy;
878
879                 /*
880                  * Decide where to put the number.
881                  */
882                 n = random_upto(rs, r.w*r.h);
883                 yy = n / r.w;
884                 xx = n % r.w;
885                 index(params,numbers,x+xx,y+yy) = r.w*r.h;
886             }
887         }
888     }
889
890 #ifdef GENERATION_DIAGNOSTICS
891     display_grid(params, grid, numbers, FALSE);
892 #endif
893
894     seed = snewn(11 * params->w * params->h, char);
895     p = seed;
896     run = 0;
897     for (i = 0; i <= params->w * params->h; i++) {
898         int n = (i < params->w * params->h ? numbers[i] : -1);
899
900         if (!n)
901             run++;
902         else {
903             if (run) {
904                 while (run > 0) {
905                     int c = 'a' - 1 + run;
906                     if (run > 26)
907                         c = 'z';
908                     *p++ = c;
909                     run -= c - ('a' - 1);
910                 }
911             } else {
912                 /*
913                  * If there's a number in the very top left or
914                  * bottom right, there's no point putting an
915                  * unnecessary _ before or after it.
916                  */
917                 if (p > seed && n > 0)
918                     *p++ = '_';
919             }
920             if (n > 0)
921                 p += sprintf(p, "%d", n);
922             run = 0;
923         }
924     }
925     *p = '\0';
926
927     sfree(grid);
928     sfree(numbers);
929
930     return seed;
931 }
932
933 static void game_free_aux_info(game_aux_info *ai)
934 {
935     sfree(ai->vedge);
936     sfree(ai->hedge);
937     sfree(ai);
938 }
939
940 static char *validate_seed(game_params *params, char *seed)
941 {
942     int area = params->w * params->h;
943     int squares = 0;
944
945     while (*seed) {
946         int n = *seed++;
947         if (n >= 'a' && n <= 'z') {
948             squares += n - 'a' + 1;
949         } else if (n == '_') {
950             /* do nothing */;
951         } else if (n > '0' && n <= '9') {
952             squares++;
953             while (*seed >= '0' && *seed <= '9')
954                 seed++;
955         } else
956             return "Invalid character in game specification";
957     }
958
959     if (squares < area)
960         return "Not enough data to fill grid";
961
962     if (squares > area)
963         return "Too much data to fit in grid";
964
965     return NULL;
966 }
967
968 static game_state *new_game(game_params *params, char *seed)
969 {
970     game_state *state = snew(game_state);
971     int x, y, i, area;
972
973     state->w = params->w;
974     state->h = params->h;
975
976     area = state->w * state->h;
977
978     state->grid = snewn(area, int);
979     state->vedge = snewn(area, unsigned char);
980     state->hedge = snewn(area, unsigned char);
981     state->completed = state->cheated = FALSE;
982
983     i = 0;
984     while (*seed) {
985         int n = *seed++;
986         if (n >= 'a' && n <= 'z') {
987             int run = n - 'a' + 1;
988             assert(i + run <= area);
989             while (run-- > 0)
990                 state->grid[i++] = 0;
991         } else if (n == '_') {
992             /* do nothing */;
993         } else if (n > '0' && n <= '9') {
994             assert(i < area);
995             state->grid[i++] = atoi(seed-1);
996             while (*seed >= '0' && *seed <= '9')
997                 seed++;
998         } else {
999             assert(!"We can't get here");
1000         }
1001     }
1002     assert(i == area);
1003
1004     for (y = 0; y < state->h; y++)
1005         for (x = 0; x < state->w; x++)
1006             vedge(state,x,y) = hedge(state,x,y) = 0;
1007
1008     return state;
1009 }
1010
1011 static game_state *dup_game(game_state *state)
1012 {
1013     game_state *ret = snew(game_state);
1014
1015     ret->w = state->w;
1016     ret->h = state->h;
1017
1018     ret->vedge = snewn(state->w * state->h, unsigned char);
1019     ret->hedge = snewn(state->w * state->h, unsigned char);
1020     ret->grid = snewn(state->w * state->h, int);
1021
1022     ret->completed = state->completed;
1023     ret->cheated = state->cheated;
1024
1025     memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
1026     memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
1027     memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
1028
1029     return ret;
1030 }
1031
1032 static void free_game(game_state *state)
1033 {
1034     sfree(state->grid);
1035     sfree(state->vedge);
1036     sfree(state->hedge);
1037     sfree(state);
1038 }
1039
1040 static game_state *solve_game(game_state *state, game_aux_info *ai,
1041                               char **error)
1042 {
1043     game_state *ret;
1044
1045     if (!ai) {
1046         *error = "Solution not known for this puzzle";
1047         return NULL;
1048     }
1049
1050     assert(state->w == ai->w);
1051     assert(state->h == ai->h);
1052
1053     ret = dup_game(state);
1054     memcpy(ret->vedge, ai->vedge, ai->w * ai->h * sizeof(unsigned char));
1055     memcpy(ret->hedge, ai->hedge, ai->w * ai->h * sizeof(unsigned char));
1056     ret->cheated = TRUE;
1057
1058     return ret;
1059 }
1060
1061 static char *game_text_format(game_state *state)
1062 {
1063     char *ret, *p, buf[80];
1064     int i, x, y, col, maxlen;
1065
1066     /*
1067      * First determine the number of spaces required to display a
1068      * number. We'll use at least two, because one looks a bit
1069      * silly.
1070      */
1071     col = 2;
1072     for (i = 0; i < state->w * state->h; i++) {
1073         x = sprintf(buf, "%d", state->grid[i]);
1074         if (col < x) col = x;
1075     }
1076
1077     /*
1078      * Now we know the exact total size of the grid we're going to
1079      * produce: it's got 2*h+1 rows, each containing w lots of col,
1080      * w+1 boundary characters and a trailing newline.
1081      */
1082     maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
1083
1084     ret = snewn(maxlen, char);
1085     p = ret;
1086
1087     for (y = 0; y <= 2*state->h; y++) {
1088         for (x = 0; x <= 2*state->w; x++) {
1089             if (x & y & 1) {
1090                 /*
1091                  * Display a number.
1092                  */
1093                 int v = grid(state, x/2, y/2);
1094                 if (v)
1095                     sprintf(buf, "%*d", col, v);
1096                 else
1097                     sprintf(buf, "%*s", col, "");
1098                 memcpy(p, buf, col);
1099                 p += col;
1100             } else if (x & 1) {
1101                 /*
1102                  * Display a horizontal edge or nothing.
1103                  */
1104                 int h = (y==0 || y==2*state->h ? 1 :
1105                          HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
1106                 int i;
1107                 if (h)
1108                     h = '-';
1109                 else
1110                     h = ' ';
1111                 for (i = 0; i < col; i++)
1112                     *p++ = h;
1113             } else if (y & 1) {
1114                 /*
1115                  * Display a vertical edge or nothing.
1116                  */
1117                 int v = (x==0 || x==2*state->w ? 1 :
1118                          VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
1119                 if (v)
1120                     *p++ = '|';
1121                 else
1122                     *p++ = ' ';
1123             } else {
1124                 /*
1125                  * Display a corner, or a vertical edge, or a
1126                  * horizontal edge, or nothing.
1127                  */
1128                 int hl = (y==0 || y==2*state->h ? 1 :
1129                           HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
1130                 int hr = (y==0 || y==2*state->h ? 1 :
1131                           HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
1132                 int vu = (x==0 || x==2*state->w ? 1 :
1133                           VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
1134                 int vd = (x==0 || x==2*state->w ? 1 :
1135                           VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
1136                 if (!hl && !hr && !vu && !vd)
1137                     *p++ = ' ';
1138                 else if (hl && hr && !vu && !vd)
1139                     *p++ = '-';
1140                 else if (!hl && !hr && vu && vd)
1141                     *p++ = '|';
1142                 else
1143                     *p++ = '+';
1144             }
1145         }
1146         *p++ = '\n';
1147     }
1148
1149     assert(p - ret == maxlen);
1150     *p = '\0';
1151     return ret;
1152 }
1153
1154 static unsigned char *get_correct(game_state *state)
1155 {
1156     unsigned char *ret;
1157     int x, y;
1158
1159     ret = snewn(state->w * state->h, unsigned char);
1160     memset(ret, 0xFF, state->w * state->h);
1161
1162     for (x = 0; x < state->w; x++)
1163         for (y = 0; y < state->h; y++)
1164             if (index(state,ret,x,y) == 0xFF) {
1165                 int rw, rh;
1166                 int xx, yy;
1167                 int num, area, valid;
1168
1169                 /*
1170                  * Find a rectangle starting at this point.
1171                  */
1172                 rw = 1;
1173                 while (x+rw < state->w && !vedge(state,x+rw,y))
1174                     rw++;
1175                 rh = 1;
1176                 while (y+rh < state->h && !hedge(state,x,y+rh))
1177                     rh++;
1178
1179                 /*
1180                  * We know what the dimensions of the rectangle
1181                  * should be if it's there at all. Find out if we
1182                  * really have a valid rectangle.
1183                  */
1184                 valid = TRUE;
1185                 /* Check the horizontal edges. */
1186                 for (xx = x; xx < x+rw; xx++) {
1187                     for (yy = y; yy <= y+rh; yy++) {
1188                         int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
1189                         int ec = (yy == y || yy == y+rh);
1190                         if (e != ec)
1191                             valid = FALSE;
1192                     }
1193                 }
1194                 /* Check the vertical edges. */
1195                 for (yy = y; yy < y+rh; yy++) {
1196                     for (xx = x; xx <= x+rw; xx++) {
1197                         int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
1198                         int ec = (xx == x || xx == x+rw);
1199                         if (e != ec)
1200                             valid = FALSE;
1201                     }
1202                 }
1203
1204                 /*
1205                  * If this is not a valid rectangle with no other
1206                  * edges inside it, we just mark this square as not
1207                  * complete and proceed to the next square.
1208                  */
1209                 if (!valid) {
1210                     index(state, ret, x, y) = 0;
1211                     continue;
1212                 }
1213
1214                 /*
1215                  * We have a rectangle. Now see what its area is,
1216                  * and how many numbers are in it.
1217                  */
1218                 num = 0;
1219                 area = 0;
1220                 for (xx = x; xx < x+rw; xx++) {
1221                     for (yy = y; yy < y+rh; yy++) {
1222                         area++;
1223                         if (grid(state,xx,yy)) {
1224                             if (num > 0)
1225                                 valid = FALSE;   /* two numbers */
1226                             num = grid(state,xx,yy);
1227                         }
1228                     }
1229                 }
1230                 if (num != area)
1231                     valid = FALSE;
1232
1233                 /*
1234                  * Now fill in the whole rectangle based on the
1235                  * value of `valid'.
1236                  */
1237                 for (xx = x; xx < x+rw; xx++) {
1238                     for (yy = y; yy < y+rh; yy++) {
1239                         index(state, ret, xx, yy) = valid;
1240                     }
1241                 }
1242             }
1243
1244     return ret;
1245 }
1246
1247 struct game_ui {
1248     /*
1249      * These coordinates are 2 times the obvious grid coordinates.
1250      * Hence, the top left of the grid is (0,0), the grid point to
1251      * the right of that is (2,0), the one _below that_ is (2,2)
1252      * and so on. This is so that we can specify a drag start point
1253      * on an edge (one odd coordinate) or in the middle of a square
1254      * (two odd coordinates) rather than always at a corner.
1255      * 
1256      * -1,-1 means no drag is in progress.
1257      */
1258     int drag_start_x;
1259     int drag_start_y;
1260     int drag_end_x;
1261     int drag_end_y;
1262     /*
1263      * This flag is set as soon as a dragging action moves the
1264      * mouse pointer away from its starting point, so that even if
1265      * the pointer _returns_ to its starting point the action is
1266      * treated as a small drag rather than a click.
1267      */
1268     int dragged;
1269 };
1270
1271 static game_ui *new_ui(game_state *state)
1272 {
1273     game_ui *ui = snew(game_ui);
1274     ui->drag_start_x = -1;
1275     ui->drag_start_y = -1;
1276     ui->drag_end_x = -1;
1277     ui->drag_end_y = -1;
1278     ui->dragged = FALSE;
1279     return ui;
1280 }
1281
1282 static void free_ui(game_ui *ui)
1283 {
1284     sfree(ui);
1285 }
1286
1287 static void coord_round(float x, float y, int *xr, int *yr)
1288 {
1289     float xs, ys, xv, yv, dx, dy, dist;
1290
1291     /*
1292      * Find the nearest square-centre.
1293      */
1294     xs = (float)floor(x) + 0.5F;
1295     ys = (float)floor(y) + 0.5F;
1296
1297     /*
1298      * And find the nearest grid vertex.
1299      */
1300     xv = (float)floor(x + 0.5F);
1301     yv = (float)floor(y + 0.5F);
1302
1303     /*
1304      * We allocate clicks in parts of the grid square to either
1305      * corners, edges or square centres, as follows:
1306      * 
1307      *   +--+--------+--+
1308      *   |  |        |  |
1309      *   +--+        +--+
1310      *   |   `.    ,'   |
1311      *   |     +--+     |
1312      *   |     |  |     |
1313      *   |     +--+     |
1314      *   |   ,'    `.   |
1315      *   +--+        +--+
1316      *   |  |        |  |
1317      *   +--+--------+--+
1318      * 
1319      * (Not to scale!)
1320      * 
1321      * In other words: we measure the square distance (i.e.
1322      * max(dx,dy)) from the click to the nearest corner, and if
1323      * it's within CORNER_TOLERANCE then we return a corner click.
1324      * We measure the square distance from the click to the nearest
1325      * centre, and if that's within CENTRE_TOLERANCE we return a
1326      * centre click. Failing that, we find which of the two edge
1327      * centres is nearer to the click and return that edge.
1328      */
1329
1330     /*
1331      * Check for corner click.
1332      */
1333     dx = (float)fabs(x - xv);
1334     dy = (float)fabs(y - yv);
1335     dist = (dx > dy ? dx : dy);
1336     if (dist < CORNER_TOLERANCE) {
1337         *xr = 2 * (int)xv;
1338         *yr = 2 * (int)yv;
1339     } else {
1340         /*
1341          * Check for centre click.
1342          */
1343         dx = (float)fabs(x - xs);
1344         dy = (float)fabs(y - ys);
1345         dist = (dx > dy ? dx : dy);
1346         if (dist < CENTRE_TOLERANCE) {
1347             *xr = 1 + 2 * (int)xs;
1348             *yr = 1 + 2 * (int)ys;
1349         } else {
1350             /*
1351              * Failing both of those, see which edge we're closer to.
1352              * Conveniently, this is simply done by testing the relative
1353              * magnitude of dx and dy (which are currently distances from
1354              * the square centre).
1355              */
1356             if (dx > dy) {
1357                 /* Vertical edge: x-coord of corner,
1358                  * y-coord of square centre. */
1359                 *xr = 2 * (int)xv;
1360                 *yr = 1 + 2 * (int)ys;
1361             } else {
1362                 /* Horizontal edge: x-coord of square centre,
1363                  * y-coord of corner. */
1364                 *xr = 1 + 2 * (int)xs;
1365                 *yr = 2 * (int)yv;
1366             }
1367         }
1368     }
1369 }
1370
1371 static void ui_draw_rect(game_state *state, game_ui *ui,
1372                          unsigned char *hedge, unsigned char *vedge, int c)
1373 {
1374     int x1, x2, y1, y2, x, y, t;
1375
1376     x1 = ui->drag_start_x;
1377     x2 = ui->drag_end_x;
1378     if (x2 < x1) { t = x1; x1 = x2; x2 = t; }
1379
1380     y1 = ui->drag_start_y;
1381     y2 = ui->drag_end_y;
1382     if (y2 < y1) { t = y1; y1 = y2; y2 = t; }
1383
1384     x1 = x1 / 2;               /* rounds down */
1385     x2 = (x2+1) / 2;           /* rounds up */
1386     y1 = y1 / 2;               /* rounds down */
1387     y2 = (y2+1) / 2;           /* rounds up */
1388
1389     /*
1390      * Draw horizontal edges of rectangles.
1391      */
1392     for (x = x1; x < x2; x++)
1393         for (y = y1; y <= y2; y++)
1394             if (HRANGE(state,x,y)) {
1395                 int val = index(state,hedge,x,y);
1396                 if (y == y1 || y == y2)
1397                     val = c;
1398                 else if (c == 1)
1399                     val = 0;
1400                 index(state,hedge,x,y) = val;
1401             }
1402
1403     /*
1404      * Draw vertical edges of rectangles.
1405      */
1406     for (y = y1; y < y2; y++)
1407         for (x = x1; x <= x2; x++)
1408             if (VRANGE(state,x,y)) {
1409                 int val = index(state,vedge,x,y);
1410                 if (x == x1 || x == x2)
1411                     val = c;
1412                 else if (c == 1)
1413                     val = 0;
1414                 index(state,vedge,x,y) = val;
1415             }
1416 }
1417
1418 static game_state *make_move(game_state *from, game_ui *ui,
1419                              int x, int y, int button)
1420 {
1421     int xc, yc;
1422     int startdrag = FALSE, enddrag = FALSE, active = FALSE;
1423     game_state *ret;
1424
1425     if (button == LEFT_BUTTON) {
1426         startdrag = TRUE;
1427     } else if (button == LEFT_RELEASE) {
1428         enddrag = TRUE;
1429     } else if (button != LEFT_DRAG) {
1430         return NULL;
1431     }
1432
1433     coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
1434
1435     if (startdrag) {
1436         ui->drag_start_x = xc;
1437         ui->drag_start_y = yc;
1438         ui->drag_end_x = xc;
1439         ui->drag_end_y = yc;
1440         ui->dragged = FALSE;
1441         active = TRUE;
1442     }
1443
1444     if (xc != ui->drag_end_x || yc != ui->drag_end_y) {
1445         ui->drag_end_x = xc;
1446         ui->drag_end_y = yc;
1447         ui->dragged = TRUE;
1448         active = TRUE;
1449     }
1450
1451     ret = NULL;
1452
1453     if (enddrag) {
1454         if (xc >= 0 && xc <= 2*from->w &&
1455             yc >= 0 && yc <= 2*from->h) {
1456             ret = dup_game(from);
1457
1458             if (ui->dragged) {
1459                 ui_draw_rect(ret, ui, ret->hedge, ret->vedge, 1);
1460             } else {
1461                 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
1462                     hedge(ret,xc/2,yc/2) = !hedge(ret,xc/2,yc/2);
1463                 }
1464                 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
1465                     vedge(ret,xc/2,yc/2) = !vedge(ret,xc/2,yc/2);
1466                 }
1467             }
1468
1469             if (!memcmp(ret->hedge, from->hedge, from->w*from->h) &&
1470                 !memcmp(ret->vedge, from->vedge, from->w*from->h)) {
1471                 free_game(ret);
1472                 ret = NULL;
1473             }
1474
1475             /*
1476              * We've made a real change to the grid. Check to see
1477              * if the game has been completed.
1478              */
1479             if (ret && !ret->completed) {
1480                 int x, y, ok;
1481                 unsigned char *correct = get_correct(ret);
1482
1483                 ok = TRUE;
1484                 for (x = 0; x < ret->w; x++)
1485                     for (y = 0; y < ret->h; y++)
1486                         if (!index(ret, correct, x, y))
1487                             ok = FALSE;
1488
1489                 sfree(correct);
1490
1491                 if (ok)
1492                     ret->completed = TRUE;
1493             }
1494         }
1495
1496         ui->drag_start_x = -1;
1497         ui->drag_start_y = -1;
1498         ui->drag_end_x = -1;
1499         ui->drag_end_y = -1;
1500         ui->dragged = FALSE;
1501         active = TRUE;
1502     }
1503
1504     if (ret)
1505         return ret;                    /* a move has been made */
1506     else if (active)
1507         return from;                   /* UI activity has occurred */
1508     else
1509         return NULL;
1510 }
1511
1512 /* ----------------------------------------------------------------------
1513  * Drawing routines.
1514  */
1515
1516 #define CORRECT 65536
1517
1518 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
1519 #define MAX(x,y) ( (x)>(y) ? (x) : (y) )
1520 #define MAX4(x,y,z,w) ( MAX(MAX(x,y),MAX(z,w)) )
1521
1522 struct game_drawstate {
1523     int started;
1524     int w, h;
1525     unsigned int *visible;
1526 };
1527
1528 static void game_size(game_params *params, int *x, int *y)
1529 {
1530     *x = params->w * TILE_SIZE + 2*BORDER + 1;
1531     *y = params->h * TILE_SIZE + 2*BORDER + 1;
1532 }
1533
1534 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1535 {
1536     float *ret = snewn(3 * NCOLOURS, float);
1537
1538     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1539
1540     ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1541     ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1542     ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1543
1544     ret[COL_DRAG * 3 + 0] = 1.0F;
1545     ret[COL_DRAG * 3 + 1] = 0.0F;
1546     ret[COL_DRAG * 3 + 2] = 0.0F;
1547
1548     ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
1549     ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
1550     ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
1551
1552     ret[COL_LINE * 3 + 0] = 0.0F;
1553     ret[COL_LINE * 3 + 1] = 0.0F;
1554     ret[COL_LINE * 3 + 2] = 0.0F;
1555
1556     ret[COL_TEXT * 3 + 0] = 0.0F;
1557     ret[COL_TEXT * 3 + 1] = 0.0F;
1558     ret[COL_TEXT * 3 + 2] = 0.0F;
1559
1560     *ncolours = NCOLOURS;
1561     return ret;
1562 }
1563
1564 static game_drawstate *game_new_drawstate(game_state *state)
1565 {
1566     struct game_drawstate *ds = snew(struct game_drawstate);
1567     int i;
1568
1569     ds->started = FALSE;
1570     ds->w = state->w;
1571     ds->h = state->h;
1572     ds->visible = snewn(ds->w * ds->h, unsigned int);
1573     for (i = 0; i < ds->w * ds->h; i++)
1574         ds->visible[i] = 0xFFFF;
1575
1576     return ds;
1577 }
1578
1579 static void game_free_drawstate(game_drawstate *ds)
1580 {
1581     sfree(ds->visible);
1582     sfree(ds);
1583 }
1584
1585 static void draw_tile(frontend *fe, game_state *state, int x, int y,
1586                unsigned char *hedge, unsigned char *vedge,
1587                unsigned char *corners, int correct)
1588 {
1589     int cx = COORD(x), cy = COORD(y);
1590     char str[80];
1591
1592     draw_rect(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
1593     draw_rect(fe, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
1594               correct ? COL_CORRECT : COL_BACKGROUND);
1595
1596     if (grid(state,x,y)) {
1597         sprintf(str, "%d", grid(state,x,y));
1598         draw_text(fe, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
1599                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
1600     }
1601
1602     /*
1603      * Draw edges.
1604      */
1605     if (!HRANGE(state,x,y) || index(state,hedge,x,y))
1606         draw_rect(fe, cx, cy, TILE_SIZE+1, 2,
1607                   HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
1608                   COL_LINE);
1609     if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
1610         draw_rect(fe, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
1611                   HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
1612                   COL_LINE);
1613     if (!VRANGE(state,x,y) || index(state,vedge,x,y))
1614         draw_rect(fe, cx, cy, 2, TILE_SIZE+1,
1615                   VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
1616                   COL_LINE);
1617     if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
1618         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
1619                   VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
1620                   COL_LINE);
1621
1622     /*
1623      * Draw corners.
1624      */
1625     if (index(state,corners,x,y))
1626         draw_rect(fe, cx, cy, 2, 2,
1627                   COLOUR(index(state,corners,x,y)));
1628     if (x+1 < state->w && index(state,corners,x+1,y))
1629         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, 2,
1630                   COLOUR(index(state,corners,x+1,y)));
1631     if (y+1 < state->h && index(state,corners,x,y+1))
1632         draw_rect(fe, cx, cy+TILE_SIZE-1, 2, 2,
1633                   COLOUR(index(state,corners,x,y+1)));
1634     if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
1635         draw_rect(fe, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
1636                   COLOUR(index(state,corners,x+1,y+1)));
1637
1638     draw_update(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
1639 }
1640
1641 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1642                  game_state *state, int dir, game_ui *ui,
1643                  float animtime, float flashtime)
1644 {
1645     int x, y;
1646     unsigned char *correct;
1647     unsigned char *hedge, *vedge, *corners;
1648
1649     correct = get_correct(state);
1650
1651     if (ui->dragged) {
1652         hedge = snewn(state->w*state->h, unsigned char);
1653         vedge = snewn(state->w*state->h, unsigned char);
1654         memcpy(hedge, state->hedge, state->w*state->h);
1655         memcpy(vedge, state->vedge, state->w*state->h);
1656         ui_draw_rect(state, ui, hedge, vedge, 2);
1657     } else {
1658         hedge = state->hedge;
1659         vedge = state->vedge;
1660     }
1661
1662     corners = snewn(state->w * state->h, unsigned char);
1663     memset(corners, 0, state->w * state->h);
1664     for (x = 0; x < state->w; x++)
1665         for (y = 0; y < state->h; y++) {
1666             if (x > 0) {
1667                 int e = index(state, vedge, x, y);
1668                 if (index(state,corners,x,y) < e)
1669                     index(state,corners,x,y) = e;
1670                 if (y+1 < state->h &&
1671                     index(state,corners,x,y+1) < e)
1672                     index(state,corners,x,y+1) = e;
1673             }
1674             if (y > 0) {
1675                 int e = index(state, hedge, x, y);
1676                 if (index(state,corners,x,y) < e)
1677                     index(state,corners,x,y) = e;
1678                 if (x+1 < state->w &&
1679                     index(state,corners,x+1,y) < e)
1680                     index(state,corners,x+1,y) = e;
1681             }
1682         }
1683
1684     if (!ds->started) {
1685         draw_rect(fe, 0, 0,
1686                   state->w * TILE_SIZE + 2*BORDER + 1,
1687                   state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
1688         draw_rect(fe, COORD(0)-1, COORD(0)-1,
1689                   ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
1690         ds->started = TRUE;
1691         draw_update(fe, 0, 0,
1692                     state->w * TILE_SIZE + 2*BORDER + 1,
1693                     state->h * TILE_SIZE + 2*BORDER + 1);
1694     }
1695
1696     for (x = 0; x < state->w; x++)
1697         for (y = 0; y < state->h; y++) {
1698             unsigned int c = 0;
1699
1700             if (HRANGE(state,x,y))
1701                 c |= index(state,hedge,x,y);
1702             if (HRANGE(state,x,y+1))
1703                 c |= index(state,hedge,x,y+1) << 2;
1704             if (VRANGE(state,x,y))
1705                 c |= index(state,vedge,x,y) << 4;
1706             if (VRANGE(state,x+1,y))
1707                 c |= index(state,vedge,x+1,y) << 6;
1708             c |= index(state,corners,x,y) << 8;
1709             if (x+1 < state->w)
1710                 c |= index(state,corners,x+1,y) << 10;
1711             if (y+1 < state->h)
1712                 c |= index(state,corners,x,y+1) << 12;
1713             if (x+1 < state->w && y+1 < state->h)
1714                 c |= index(state,corners,x+1,y+1) << 14;
1715             if (index(state, correct, x, y) && !flashtime)
1716                 c |= CORRECT;
1717
1718             if (index(ds,ds->visible,x,y) != c) {
1719                 draw_tile(fe, state, x, y, hedge, vedge, corners, c & CORRECT);
1720                 index(ds,ds->visible,x,y) = c;
1721             }
1722         }
1723
1724     if (hedge != state->hedge) {
1725         sfree(hedge);
1726         sfree(vedge);
1727    }
1728
1729     sfree(corners);
1730     sfree(correct);
1731 }
1732
1733 static float game_anim_length(game_state *oldstate,
1734                               game_state *newstate, int dir)
1735 {
1736     return 0.0F;
1737 }
1738
1739 static float game_flash_length(game_state *oldstate,
1740                                game_state *newstate, int dir)
1741 {
1742     if (!oldstate->completed && newstate->completed &&
1743         !oldstate->cheated && !newstate->cheated)
1744         return FLASH_TIME;
1745     return 0.0F;
1746 }
1747
1748 static int game_wants_statusbar(void)
1749 {
1750     return FALSE;
1751 }
1752
1753 #ifdef COMBINED
1754 #define thegame rect
1755 #endif
1756
1757 const struct game thegame = {
1758     "Rectangles", "games.rectangles",
1759     default_params,
1760     game_fetch_preset,
1761     decode_params,
1762     encode_params,
1763     free_params,
1764     dup_params,
1765     TRUE, game_configure, custom_params,
1766     validate_params,
1767     new_game_seed,
1768     game_free_aux_info,
1769     validate_seed,
1770     new_game,
1771     dup_game,
1772     free_game,
1773     TRUE, solve_game,
1774     TRUE, game_text_format,
1775     new_ui,
1776     free_ui,
1777     make_move,
1778     game_size,
1779     game_colours,
1780     game_new_drawstate,
1781     game_free_drawstate,
1782     game_redraw,
1783     game_anim_length,
1784     game_flash_length,
1785     game_wants_statusbar,
1786 };