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