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