chiark / gitweb /
Fixes in grid generation for pedantic special cases when one or both
[sgt-puzzles.git] / pattern.c
1 /*
2  * pattern.c: the pattern-reconstruction game known as `nonograms'.
3  * 
4  * TODO before checkin:
5  * 
6  *  - make some sort of stab at number-of-numbers judgment
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <math.h>
15
16 #include "puzzles.h"
17
18 #define max(x,y) ( (x)>(y) ? (x):(y) )
19 #define min(x,y) ( (x)<(y) ? (x):(y) )
20
21 enum {
22     COL_BACKGROUND,
23     COL_EMPTY,
24     COL_FULL,
25     COL_UNKNOWN,
26     COL_GRID,
27     NCOLOURS
28 };
29
30 #define BORDER 18
31 #define TLBORDER(d) ( (d) / 5 + 2 )
32 #define GUTTER 12
33 #define TILE_SIZE 24
34
35 #define FROMCOORD(d, x) \
36         ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
37
38 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
39
40 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
41
42 struct game_params {
43     int w, h;
44 };
45
46 #define GRID_UNKNOWN 2
47 #define GRID_FULL 1
48 #define GRID_EMPTY 0
49
50 struct game_state {
51     int w, h;
52     unsigned char *grid;
53     int rowsize;
54     int *rowdata, *rowlen;
55     int completed;
56 };
57
58 #define FLASH_TIME 0.13F
59
60 static game_params *default_params(void)
61 {
62     game_params *ret = snew(game_params);
63
64     ret->w = ret->h = 15;
65
66     return ret;
67 }
68
69 static int game_fetch_preset(int i, char **name, game_params **params)
70 {
71     game_params *ret;
72     char str[80];
73     static const struct { int x, y; } values[] = {
74         {10, 10},
75         {15, 15},
76         {20, 20},
77         {25, 25},
78         {30, 30},
79     };
80
81     if (i < 0 || i >= lenof(values))
82         return FALSE;
83
84     ret = snew(game_params);
85     ret->w = values[i].x;
86     ret->h = values[i].y;
87
88     sprintf(str, "%dx%d", ret->w, ret->h);
89
90     *name = dupstr(str);
91     *params = ret;
92     return TRUE;
93 }
94
95 static void free_params(game_params *params)
96 {
97     sfree(params);
98 }
99
100 static game_params *dup_params(game_params *params)
101 {
102     game_params *ret = snew(game_params);
103     *ret = *params;                    /* structure copy */
104     return ret;
105 }
106
107 static game_params *decode_params(char const *string)
108 {
109     game_params *ret = default_params();
110     char const *p = string;
111
112     ret->w = atoi(p);
113     while (*p && isdigit(*p)) p++;
114     if (*p == 'x') {
115         p++;
116         ret->h = atoi(p);
117         while (*p && isdigit(*p)) p++;
118     } else {
119         ret->h = ret->w;
120     }
121
122     return ret;
123 }
124
125 static char *encode_params(game_params *params)
126 {
127     char ret[400];
128     int len;
129
130     len = sprintf(ret, "%dx%d", params->w, params->h);
131     assert(len < lenof(ret));
132     ret[len] = '\0';
133
134     return dupstr(ret);
135 }
136
137 static config_item *game_configure(game_params *params)
138 {
139     config_item *ret;
140     char buf[80];
141
142     ret = snewn(3, config_item);
143
144     ret[0].name = "Width";
145     ret[0].type = C_STRING;
146     sprintf(buf, "%d", params->w);
147     ret[0].sval = dupstr(buf);
148     ret[0].ival = 0;
149
150     ret[1].name = "Height";
151     ret[1].type = C_STRING;
152     sprintf(buf, "%d", params->h);
153     ret[1].sval = dupstr(buf);
154     ret[1].ival = 0;
155
156     ret[2].name = NULL;
157     ret[2].type = C_END;
158     ret[2].sval = NULL;
159     ret[2].ival = 0;
160
161     return ret;
162 }
163
164 static game_params *custom_params(config_item *cfg)
165 {
166     game_params *ret = snew(game_params);
167
168     ret->w = atoi(cfg[0].sval);
169     ret->h = atoi(cfg[1].sval);
170
171     return ret;
172 }
173
174 static char *validate_params(game_params *params)
175 {
176     if (params->w <= 0 && params->h <= 0)
177         return "Width and height must both be greater than zero";
178     if (params->w <= 0)
179         return "Width must be greater than zero";
180     if (params->h <= 0)
181         return "Height must be greater than zero";
182     return NULL;
183 }
184
185 /* ----------------------------------------------------------------------
186  * Puzzle generation code.
187  * 
188  * For this particular puzzle, it seemed important to me to ensure
189  * a unique solution. I do this the brute-force way, by having a
190  * solver algorithm alongside the generator, and repeatedly
191  * generating a random grid until I find one whose solution is
192  * unique. It turns out that this isn't too onerous on a modern PC
193  * provided you keep grid size below around 30. Any offers of
194  * better algorithms, however, will be very gratefully received.
195  * 
196  * Another annoyance of this approach is that it limits the
197  * available puzzles to those solvable by the algorithm I've used.
198  * My algorithm only ever considers a single row or column at any
199  * one time, which means it's incapable of solving the following
200  * difficult example (found by Bella Image around 1995/6, when she
201  * and I were both doing maths degrees):
202  * 
203  *        2  1  2  1 
204  *
205  *      +--+--+--+--+
206  * 1 1  |  |  |  |  |
207  *      +--+--+--+--+
208  *   2  |  |  |  |  |
209  *      +--+--+--+--+
210  *   1  |  |  |  |  |
211  *      +--+--+--+--+
212  *   1  |  |  |  |  |
213  *      +--+--+--+--+
214  * 
215  * Obviously this cannot be solved by a one-row-or-column-at-a-time
216  * algorithm (it would require at least one row or column reading
217  * `2 1', `1 2', `3' or `4' to get started). However, it can be
218  * proved to have a unique solution: if the top left square were
219  * empty, then the only option for the top row would be to fill the
220  * two squares in the 1 columns, which would imply the squares
221  * below those were empty, leaving no place for the 2 in the second
222  * row. Contradiction. Hence the top left square is full, and the
223  * unique solution follows easily from that starting point.
224  * 
225  * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
226  * it's useful to anyone.)
227  */
228
229 static int float_compare(const void *av, const void *bv)
230 {
231     const float *a = (const float *)av;
232     const float *b = (const float *)bv;
233     if (*a < *b)
234         return -1;
235     else if (*a > *b)
236         return +1;
237     else
238         return 0;
239 }
240
241 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
242 {
243     float *fgrid;
244     float *fgrid2;
245     int step, i, j;
246     float threshold;
247
248     fgrid = snewn(w*h, float);
249
250     for (i = 0; i < h; i++) {
251         for (j = 0; j < w; j++) {
252             fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
253         }
254     }
255
256     /*
257      * The above gives a completely random splattering of black and
258      * white cells. We want to gently bias this in favour of _some_
259      * reasonably thick areas of white and black, while retaining
260      * some randomness and fine detail.
261      * 
262      * So we evolve the starting grid using a cellular automaton.
263      * Currently, I'm doing something very simple indeed, which is
264      * to set each square to the average of the surrounding nine
265      * cells (or the average of fewer, if we're on a corner).
266      */
267     for (step = 0; step < 1; step++) {
268         fgrid2 = snewn(w*h, float);
269
270         for (i = 0; i < h; i++) {
271             for (j = 0; j < w; j++) {
272                 float sx, xbar;
273                 int n, p, q;
274
275                 /*
276                  * Compute the average of the surrounding cells.
277                  */
278                 n = 0;
279                 sx = 0.F;
280                 for (p = -1; p <= +1; p++) {
281                     for (q = -1; q <= +1; q++) {
282                         if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
283                             continue;
284                         /*
285                          * An additional special case not mentioned
286                          * above: if a grid dimension is 2xn then
287                          * we do not average across that dimension
288                          * at all. Otherwise a 2x2 grid would
289                          * contain four identical squares.
290                          */
291                         if ((h==2 && p!=0) || (w==2 && q!=0))
292                             continue;
293                         n++;
294                         sx += fgrid[(i+p)*w+(j+q)];
295                     }
296                 }
297                 xbar = sx / n;
298
299                 fgrid2[i*w+j] = xbar;
300             }
301         }
302
303         sfree(fgrid);
304         fgrid = fgrid2;
305     }
306
307     fgrid2 = snewn(w*h, float);
308     memcpy(fgrid2, fgrid, w*h*sizeof(float));
309     qsort(fgrid2, w*h, sizeof(float), float_compare);
310     threshold = fgrid2[w*h/2];
311     sfree(fgrid2);
312
313     for (i = 0; i < h; i++) {
314         for (j = 0; j < w; j++) {
315             retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
316                               GRID_EMPTY);
317         }
318     }
319
320     sfree(fgrid);
321 }
322
323 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
324 {
325     int i, n;
326
327     n = 0;
328
329     for (i = 0; i < len; i++) {
330         if (start[i*step] == GRID_FULL) {
331             int runlen = 1;
332             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
333                 runlen++;
334             ret[n++] = runlen;
335             i += runlen;
336         }
337
338         if (i < len && start[i*step] == GRID_UNKNOWN)
339             return -1;
340     }
341
342     return n;
343 }
344
345 #define UNKNOWN 0
346 #define BLOCK 1
347 #define DOT 2
348 #define STILL_UNKNOWN 3
349
350 static void do_recurse(unsigned char *known, unsigned char *deduced,
351                        unsigned char *row, int *data, int len,
352                        int freespace, int ndone, int lowest)
353 {
354     int i, j, k;
355
356     if (data[ndone]) {
357         for (i=0; i<=freespace; i++) {
358             j = lowest;
359             for (k=0; k<i; k++) row[j++] = DOT;
360             for (k=0; k<data[ndone]; k++) row[j++] = BLOCK;
361             if (j < len) row[j++] = DOT;
362             do_recurse(known, deduced, row, data, len,
363                        freespace-i, ndone+1, j);
364         }
365     } else {
366         for (i=lowest; i<len; i++)
367             row[i] = DOT;
368         for (i=0; i<len; i++)
369             if (known[i] && known[i] != row[i])
370                 return;
371         for (i=0; i<len; i++)
372             deduced[i] |= row[i];
373     }
374 }
375
376 static int do_row(unsigned char *known, unsigned char *deduced,
377                   unsigned char *row,
378                   unsigned char *start, int len, int step, int *data)
379 {
380     int rowlen, i, freespace, done_any;
381
382     freespace = len+1;
383     for (rowlen = 0; data[rowlen]; rowlen++)
384         freespace -= data[rowlen]+1;
385
386     for (i = 0; i < len; i++) {
387         known[i] = start[i*step];
388         deduced[i] = 0;
389     }
390
391     do_recurse(known, deduced, row, data, len, freespace, 0, 0);
392     done_any = FALSE;
393     for (i=0; i<len; i++)
394         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
395             start[i*step] = deduced[i];
396             done_any = TRUE;
397         }
398     return done_any;
399 }
400
401 static unsigned char *generate_soluble(random_state *rs, int w, int h)
402 {
403     int i, j, done_any, ok, ntries, max;
404     unsigned char *grid, *matrix, *workspace;
405     int *rowdata;
406
407     grid = snewn(w*h, unsigned char);
408     matrix = snewn(w*h, unsigned char);
409     max = max(w, h);
410     workspace = snewn(max*3, unsigned char);
411     rowdata = snewn(max+1, int);
412
413     ntries = 0;
414
415     do {
416         ntries++;
417
418         generate(rs, w, h, grid);
419
420         memset(matrix, 0, w*h);
421
422         do {
423             done_any = 0;
424             for (i=0; i<h; i++) {
425                 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
426                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
427                                    matrix+i*w, w, 1, rowdata);
428             }
429             for (i=0; i<w; i++) {
430                 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
431                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
432                                    matrix+i, h, w, rowdata);
433             }
434         } while (done_any);
435
436         ok = TRUE;
437         for (i=0; i<h; i++) {
438             for (j=0; j<w; j++) {
439                 if (matrix[i*w+j] == UNKNOWN)
440                     ok = FALSE;
441             }
442         }
443     } while (!ok);
444
445     sfree(matrix);
446     sfree(workspace);
447     sfree(rowdata);
448     return grid;
449 }
450
451 static char *new_game_seed(game_params *params, random_state *rs)
452 {
453     unsigned char *grid;
454     int i, j, max, rowlen, *rowdata;
455     char intbuf[80], *seed;
456     int seedlen, seedpos;
457
458     grid = generate_soluble(rs, params->w, params->h);
459     max = max(params->w, params->h);
460     rowdata = snewn(max, int);
461
462     /*
463      * Seed is a slash-separated list of row contents; each row
464      * contents section is a dot-separated list of integers. Row
465      * contents are listed in the order (columns left to right,
466      * then rows top to bottom).
467      * 
468      * Simplest way to handle memory allocation is to make two
469      * passes, first computing the seed size and then writing it
470      * out.
471      */
472     seedlen = 0;
473     for (i = 0; i < params->w + params->h; i++) {
474         if (i < params->w)
475             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
476         else
477             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
478                                      params->w, 1);
479         if (rowlen > 0) {
480             for (j = 0; j < rowlen; j++) {
481                 seedlen += 1 + sprintf(intbuf, "%d", rowdata[j]);
482             }
483         } else {
484             seedlen++;
485         }
486     }
487     seed = snewn(seedlen, char);
488     seedpos = 0;
489     for (i = 0; i < params->w + params->h; i++) {
490         if (i < params->w)
491             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
492         else
493             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
494                                      params->w, 1);
495         if (rowlen > 0) {
496             for (j = 0; j < rowlen; j++) {
497                 int len = sprintf(seed+seedpos, "%d", rowdata[j]);
498                 if (j+1 < rowlen)
499                     seed[seedpos + len] = '.';
500                 else
501                     seed[seedpos + len] = '/';
502                 seedpos += len+1;
503             }
504         } else {
505             seed[seedpos++] = '/';
506         }
507     }
508     assert(seedpos == seedlen);
509     assert(seed[seedlen-1] == '/');
510     seed[seedlen-1] = '\0';
511     sfree(rowdata);
512     return seed;
513 }
514
515 static char *validate_seed(game_params *params, char *seed)
516 {
517     int i, n, rowspace;
518     char *p;
519
520     for (i = 0; i < params->w + params->h; i++) {
521         if (i < params->w)
522             rowspace = params->h + 1;
523         else
524             rowspace = params->w + 1;
525
526         if (*seed && isdigit((unsigned char)*seed)) {
527             do {
528                 p = seed;
529                 while (seed && isdigit((unsigned char)*seed)) seed++;
530                 n = atoi(p);
531                 rowspace -= n+1;
532
533                 if (rowspace < 0) {
534                     if (i < params->w)
535                         return "at least one column contains more numbers than will fit";
536                     else
537                         return "at least one row contains more numbers than will fit";
538                 }
539             } while (*seed++ == '.');
540         } else {
541             seed++;                    /* expect a slash immediately */
542         }
543
544         if (seed[-1] == '/') {
545             if (i+1 == params->w + params->h)
546                 return "too many row/column specifications";
547         } else if (seed[-1] == '\0') {
548             if (i+1 < params->w + params->h)
549                 return "too few row/column specifications";
550         } else
551             return "unrecognised character in game specification";
552     }
553
554     return NULL;
555 }
556
557 static game_state *new_game(game_params *params, char *seed)
558 {
559     int i;
560     char *p;
561     game_state *state = snew(game_state);
562
563     state->w = params->w;
564     state->h = params->h;
565
566     state->grid = snewn(state->w * state->h, unsigned char);
567     memset(state->grid, GRID_UNKNOWN, state->w * state->h);
568
569     state->rowsize = max(state->w, state->h);
570     state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
571     state->rowlen = snewn(state->w + state->h, int);
572
573     state->completed = FALSE;
574
575     for (i = 0; i < params->w + params->h; i++) {
576         state->rowlen[i] = 0;
577         if (*seed && isdigit((unsigned char)*seed)) {
578             do {
579                 p = seed;
580                 while (seed && isdigit((unsigned char)*seed)) seed++;
581                 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
582                     atoi(p);
583             } while (*seed++ == '.');
584         } else {
585             seed++;                    /* expect a slash immediately */
586         }
587     }
588
589     return state;
590 }
591
592 static game_state *dup_game(game_state *state)
593 {
594     game_state *ret = snew(game_state);
595
596     ret->w = state->w;
597     ret->h = state->h;
598
599     ret->grid = snewn(ret->w * ret->h, unsigned char);
600     memcpy(ret->grid, state->grid, ret->w * ret->h);
601
602     ret->rowsize = state->rowsize;
603     ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
604     ret->rowlen = snewn(ret->w + ret->h, int);
605     memcpy(ret->rowdata, state->rowdata,
606            ret->rowsize * (ret->w + ret->h) * sizeof(int));
607     memcpy(ret->rowlen, state->rowlen,
608            (ret->w + ret->h) * sizeof(int));
609
610     ret->completed = state->completed;
611
612     return ret;
613 }
614
615 static void free_game(game_state *state)
616 {
617     sfree(state->rowdata);
618     sfree(state->rowlen);
619     sfree(state->grid);
620     sfree(state);
621 }
622
623 struct game_ui {
624     int dragging;
625     int drag_start_x;
626     int drag_start_y;
627     int drag_end_x;
628     int drag_end_y;
629     int drag, release, state;
630 };
631
632 static game_ui *new_ui(game_state *state)
633 {
634     game_ui *ret;
635
636     ret = snew(game_ui);
637     ret->dragging = FALSE;
638
639     return ret;
640 }
641
642 static void free_ui(game_ui *ui)
643 {
644     sfree(ui);
645 }
646
647 static game_state *make_move(game_state *from, game_ui *ui,
648                              int x, int y, int button)
649 {
650     game_state *ret;
651
652     x = FROMCOORD(from->w, x);
653     y = FROMCOORD(from->h, y);
654
655     if (x >= 0 && x < from->w && y >= 0 && y < from->h &&
656         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
657          button == MIDDLE_BUTTON)) {
658
659         ui->dragging = TRUE;
660
661         if (button == LEFT_BUTTON) {
662             ui->drag = LEFT_DRAG;
663             ui->release = LEFT_RELEASE;
664             ui->state = GRID_FULL;
665         } else if (button == RIGHT_BUTTON) {
666             ui->drag = RIGHT_DRAG;
667             ui->release = RIGHT_RELEASE;
668             ui->state = GRID_EMPTY;
669         } else /* if (button == MIDDLE_BUTTON) */ {
670             ui->drag = MIDDLE_DRAG;
671             ui->release = MIDDLE_RELEASE;
672             ui->state = GRID_UNKNOWN;
673         }
674
675         ui->drag_start_x = ui->drag_end_x = x;
676         ui->drag_start_y = ui->drag_end_y = y;
677
678         return from;                   /* UI activity occurred */
679     }
680
681     if (ui->dragging && button == ui->drag) {
682         /*
683          * There doesn't seem much point in allowing a rectangle
684          * drag; people will generally only want to drag a single
685          * horizontal or vertical line, so we make that easy by
686          * snapping to it.
687          * 
688          * Exception: if we're _middle_-button dragging to tag
689          * things as UNKNOWN, we may well want to trash an entire
690          * area and start over!
691          */
692         if (ui->state != GRID_UNKNOWN) {
693             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
694                 y = ui->drag_start_y;
695             else
696                 x = ui->drag_start_x;
697         }
698
699         if (x < 0) x = 0;
700         if (y < 0) y = 0;
701         if (x >= from->w) x = from->w - 1;
702         if (y >= from->h) y = from->h - 1;
703
704         ui->drag_end_x = x;
705         ui->drag_end_y = y;
706
707         return from;                   /* UI activity occurred */
708     }
709
710     if (ui->dragging && button == ui->release) {
711         int x1, x2, y1, y2, xx, yy;
712         int move_needed = FALSE;
713
714         x1 = min(ui->drag_start_x, ui->drag_end_x);
715         x2 = max(ui->drag_start_x, ui->drag_end_x);
716         y1 = min(ui->drag_start_y, ui->drag_end_y);
717         y2 = max(ui->drag_start_y, ui->drag_end_y);
718
719         for (yy = y1; yy <= y2; yy++)
720             for (xx = x1; xx <= x2; xx++)
721                 if (from->grid[yy * from->w + xx] != ui->state)
722                     move_needed = TRUE;
723
724         ui->dragging = FALSE;
725
726         if (move_needed) {
727             ret = dup_game(from);
728             for (yy = y1; yy <= y2; yy++)
729                 for (xx = x1; xx <= x2; xx++)
730                     ret->grid[yy * ret->w + xx] = ui->state;
731
732             /*
733              * An actual change, so check to see if we've completed
734              * the game.
735              */
736             if (!ret->completed) {
737                 int *rowdata = snewn(ret->rowsize, int);
738                 int i, len;
739
740                 ret->completed = TRUE;
741
742                 for (i=0; i<ret->w; i++) {
743                     len = compute_rowdata(rowdata,
744                                           ret->grid+i, ret->h, ret->w);
745                     if (len != ret->rowlen[i] ||
746                         memcmp(ret->rowdata+i*ret->rowsize, rowdata,
747                                len * sizeof(int))) {
748                         ret->completed = FALSE;
749                         break;
750                     }
751                 }
752                 for (i=0; i<ret->h; i++) {
753                     len = compute_rowdata(rowdata,
754                                           ret->grid+i*ret->w, ret->w, 1);
755                     if (len != ret->rowlen[i+ret->w] ||
756                         memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
757                                len * sizeof(int))) {
758                         ret->completed = FALSE;
759                         break;
760                     }
761                 }
762
763                 sfree(rowdata);
764             }
765
766             return ret;
767         } else
768             return from;               /* UI activity occurred */
769     }
770
771     return NULL;
772 }
773
774 /* ----------------------------------------------------------------------
775  * Drawing routines.
776  */
777
778 struct game_drawstate {
779     int started;
780     int w, h;
781     unsigned char *visible;
782 };
783
784 static void game_size(game_params *params, int *x, int *y)
785 {
786     *x = SIZE(params->w);
787     *y = SIZE(params->h);
788 }
789
790 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
791 {
792     float *ret = snewn(3 * NCOLOURS, float);
793
794     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
795
796     ret[COL_GRID * 3 + 0] = 0.3F;
797     ret[COL_GRID * 3 + 1] = 0.3F;
798     ret[COL_GRID * 3 + 2] = 0.3F;
799
800     ret[COL_UNKNOWN * 3 + 0] = 0.5F;
801     ret[COL_UNKNOWN * 3 + 1] = 0.5F;
802     ret[COL_UNKNOWN * 3 + 2] = 0.5F;
803
804     ret[COL_FULL * 3 + 0] = 0.0F;
805     ret[COL_FULL * 3 + 1] = 0.0F;
806     ret[COL_FULL * 3 + 2] = 0.0F;
807
808     ret[COL_EMPTY * 3 + 0] = 1.0F;
809     ret[COL_EMPTY * 3 + 1] = 1.0F;
810     ret[COL_EMPTY * 3 + 2] = 1.0F;
811
812     *ncolours = NCOLOURS;
813     return ret;
814 }
815
816 static game_drawstate *game_new_drawstate(game_state *state)
817 {
818     struct game_drawstate *ds = snew(struct game_drawstate);
819
820     ds->started = FALSE;
821     ds->w = state->w;
822     ds->h = state->h;
823     ds->visible = snewn(ds->w * ds->h, unsigned char);
824     memset(ds->visible, 255, ds->w * ds->h);
825
826     return ds;
827 }
828
829 static void game_free_drawstate(game_drawstate *ds)
830 {
831     sfree(ds->visible);
832     sfree(ds);
833 }
834
835 static void grid_square(frontend *fe, game_drawstate *ds,
836                         int y, int x, int state)
837 {
838     int xl, xr, yt, yb;
839
840     draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
841               TILE_SIZE, TILE_SIZE, COL_GRID);
842
843     xl = (x % 5 == 0 ? 1 : 0);
844     yt = (y % 5 == 0 ? 1 : 0);
845     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
846     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
847
848     draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
849               TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
850               (state == GRID_FULL ? COL_FULL :
851                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
852
853     draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
854                 TILE_SIZE, TILE_SIZE);
855 }
856
857 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
858                  game_state *state, int dir, game_ui *ui,
859                  float animtime, float flashtime)
860 {
861     int i, j;
862     int x1, x2, y1, y2;
863
864     if (!ds->started) {
865         /*
866          * The initial contents of the window are not guaranteed
867          * and can vary with front ends. To be on the safe side,
868          * all games should start by drawing a big background-
869          * colour rectangle covering the whole window.
870          */
871         draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
872
873         /*
874          * Draw the numbers.
875          */
876         for (i = 0; i < ds->w + ds->h; i++) {
877             int rowlen = state->rowlen[i];
878             int *rowdata = state->rowdata + state->rowsize * i;
879             int nfit;
880
881             /*
882              * Normally I space the numbers out by the same
883              * distance as the tile size. However, if there are
884              * more numbers than available spaces, I have to squash
885              * them up a bit.
886              */
887             nfit = max(rowlen, TLBORDER(ds->h))-1;
888             assert(nfit > 0);
889
890             for (j = 0; j < rowlen; j++) {
891                 int x, y;
892                 char str[80];
893
894                 if (i < ds->w) {
895                     x = TOCOORD(ds->w, i);
896                     y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
897                     y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
898                 } else {
899                     y = TOCOORD(ds->h, i - ds->w);
900                     x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
901                     x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
902                 }
903
904                 sprintf(str, "%d", rowdata[j]);
905                 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
906                           TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
907                           COL_FULL, str);   /* FIXME: COL_TEXT */
908             }
909         }
910
911         /*
912          * Draw the grid outline.
913          */
914         draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
915                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
916                   COL_GRID);
917
918         ds->started = TRUE;
919
920         draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
921     }
922
923     if (ui->dragging) {
924         x1 = min(ui->drag_start_x, ui->drag_end_x);
925         x2 = max(ui->drag_start_x, ui->drag_end_x);
926         y1 = min(ui->drag_start_y, ui->drag_end_y);
927         y2 = max(ui->drag_start_y, ui->drag_end_y);
928     } else {
929         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
930     }
931
932     /*
933      * Now draw any grid squares which have changed since last
934      * redraw.
935      */
936     for (i = 0; i < ds->h; i++) {
937         for (j = 0; j < ds->w; j++) {
938             int val;
939
940             /*
941              * Work out what state this square should be drawn in,
942              * taking any current drag operation into account.
943              */
944             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
945                 val = ui->state;
946             else
947                 val = state->grid[i * state->w + j];
948
949             /*
950              * Briefly invert everything twice during a completion
951              * flash.
952              */
953             if (flashtime > 0 &&
954                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
955                 val != GRID_UNKNOWN)
956                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
957
958             if (ds->visible[i * ds->w + j] != val) {
959                 grid_square(fe, ds, i, j, val);
960                 ds->visible[i * ds->w + j] = val;
961             }
962         }
963     }
964 }
965
966 static float game_anim_length(game_state *oldstate,
967                               game_state *newstate, int dir)
968 {
969     return 0.0F;
970 }
971
972 static float game_flash_length(game_state *oldstate,
973                                game_state *newstate, int dir)
974 {
975     if (!oldstate->completed && newstate->completed)
976         return FLASH_TIME;
977     return 0.0F;
978 }
979
980 static int game_wants_statusbar(void)
981 {
982     return FALSE;
983 }
984
985 #ifdef COMBINED
986 #define thegame pattern
987 #endif
988
989 const struct game thegame = {
990     "Pattern", "games.pattern", TRUE,
991     default_params,
992     game_fetch_preset,
993     decode_params,
994     encode_params,
995     free_params,
996     dup_params,
997     game_configure,
998     custom_params,
999     validate_params,
1000     new_game_seed,
1001     validate_seed,
1002     new_game,
1003     dup_game,
1004     free_game,
1005     new_ui,
1006     free_ui,
1007     make_move,
1008     game_size,
1009     game_colours,
1010     game_new_drawstate,
1011     game_free_drawstate,
1012     game_redraw,
1013     game_anim_length,
1014     game_flash_length,
1015     game_wants_statusbar,
1016 };