chiark / gitweb /
The main grid outline in Pattern was asymmetric between the top/left
[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                         n++;
285                         sx += fgrid[(i+p)*w+(j+q)];
286                     }
287                 }
288                 xbar = sx / n;
289
290                 fgrid2[i*w+j] = xbar;
291             }
292         }
293
294         sfree(fgrid);
295         fgrid = fgrid2;
296     }
297
298     fgrid2 = snewn(w*h, float);
299     memcpy(fgrid2, fgrid, w*h*sizeof(float));
300     qsort(fgrid2, w*h, sizeof(float), float_compare);
301     threshold = fgrid2[w*h/2];
302     sfree(fgrid2);
303
304     for (i = 0; i < h; i++) {
305         for (j = 0; j < w; j++) {
306             retgrid[i*w+j] = (fgrid[i*w+j] > threshold ? GRID_FULL :
307                               GRID_EMPTY);
308         }
309     }
310
311     sfree(fgrid);
312 }
313
314 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
315 {
316     int i, n;
317
318     n = 0;
319
320     for (i = 0; i < len; i++) {
321         if (start[i*step] == GRID_FULL) {
322             int runlen = 1;
323             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
324                 runlen++;
325             ret[n++] = runlen;
326             i += runlen;
327         }
328
329         if (i < len && start[i*step] == GRID_UNKNOWN)
330             return -1;
331     }
332
333     return n;
334 }
335
336 #define UNKNOWN 0
337 #define BLOCK 1
338 #define DOT 2
339 #define STILL_UNKNOWN 3
340
341 static void do_recurse(unsigned char *known, unsigned char *deduced,
342                        unsigned char *row, int *data, int len,
343                        int freespace, int ndone, int lowest)
344 {
345     int i, j, k;
346
347     if (data[ndone]) {
348         for (i=0; i<=freespace; i++) {
349             j = lowest;
350             for (k=0; k<i; k++) row[j++] = DOT;
351             for (k=0; k<data[ndone]; k++) row[j++] = BLOCK;
352             if (j < len) row[j++] = DOT;
353             do_recurse(known, deduced, row, data, len,
354                        freespace-i, ndone+1, j);
355         }
356     } else {
357         for (i=lowest; i<len; i++)
358             row[i] = DOT;
359         for (i=0; i<len; i++)
360             if (known[i] && known[i] != row[i])
361                 return;
362         for (i=0; i<len; i++)
363             deduced[i] |= row[i];
364     }
365 }
366
367 static int do_row(unsigned char *known, unsigned char *deduced,
368                   unsigned char *row,
369                   unsigned char *start, int len, int step, int *data)
370 {
371     int rowlen, i, freespace, done_any;
372
373     freespace = len+1;
374     for (rowlen = 0; data[rowlen]; rowlen++)
375         freespace -= data[rowlen]+1;
376
377     for (i = 0; i < len; i++) {
378         known[i] = start[i*step];
379         deduced[i] = 0;
380     }
381
382     do_recurse(known, deduced, row, data, len, freespace, 0, 0);
383     done_any = FALSE;
384     for (i=0; i<len; i++)
385         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
386             start[i*step] = deduced[i];
387             done_any = TRUE;
388         }
389     return done_any;
390 }
391
392 static unsigned char *generate_soluble(random_state *rs, int w, int h)
393 {
394     int i, j, done_any, ok, ntries, max;
395     unsigned char *grid, *matrix, *workspace;
396     int *rowdata;
397
398     grid = snewn(w*h, unsigned char);
399     matrix = snewn(w*h, unsigned char);
400     max = max(w, h);
401     workspace = snewn(max*3, unsigned char);
402     rowdata = snewn(max+1, int);
403
404     ntries = 0;
405
406     do {
407         ntries++;
408
409         generate(rs, w, h, grid);
410
411         memset(matrix, 0, w*h);
412
413         do {
414             done_any = 0;
415             for (i=0; i<h; i++) {
416                 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
417                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
418                                    matrix+i*w, w, 1, rowdata);
419             }
420             for (i=0; i<w; i++) {
421                 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
422                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
423                                    matrix+i, h, w, rowdata);
424             }
425         } while (done_any);
426
427         ok = TRUE;
428         for (i=0; i<h; i++) {
429             for (j=0; j<w; j++) {
430                 if (matrix[i*w+j] == UNKNOWN)
431                     ok = FALSE;
432             }
433         }
434     } while (!ok);
435
436     sfree(matrix);
437     sfree(workspace);
438     sfree(rowdata);
439     return grid;
440 }
441
442 static char *new_game_seed(game_params *params, random_state *rs)
443 {
444     unsigned char *grid;
445     int i, j, max, rowlen, *rowdata;
446     char intbuf[80], *seed;
447     int seedlen, seedpos;
448
449     grid = generate_soluble(rs, params->w, params->h);
450     max = max(params->w, params->h);
451     rowdata = snewn(max, int);
452
453     /*
454      * Seed is a slash-separated list of row contents; each row
455      * contents section is a dot-separated list of integers. Row
456      * contents are listed in the order (columns left to right,
457      * then rows top to bottom).
458      * 
459      * Simplest way to handle memory allocation is to make two
460      * passes, first computing the seed size and then writing it
461      * out.
462      */
463     seedlen = 0;
464     for (i = 0; i < params->w + params->h; i++) {
465         if (i < params->w)
466             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
467         else
468             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
469                                      params->w, 1);
470         if (rowlen > 0) {
471             for (j = 0; j < rowlen; j++) {
472                 seedlen += 1 + sprintf(intbuf, "%d", rowdata[j]);
473             }
474         } else {
475             seedlen++;
476         }
477     }
478     seed = snewn(seedlen, char);
479     seedpos = 0;
480     for (i = 0; i < params->w + params->h; i++) {
481         if (i < params->w)
482             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
483         else
484             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
485                                      params->w, 1);
486         if (rowlen > 0) {
487             for (j = 0; j < rowlen; j++) {
488                 int len = sprintf(seed+seedpos, "%d", rowdata[j]);
489                 if (j+1 < rowlen)
490                     seed[seedpos + len] = '.';
491                 else
492                     seed[seedpos + len] = '/';
493                 seedpos += len+1;
494             }
495         } else {
496             seed[seedpos++] = '/';
497         }
498     }
499     assert(seedpos == seedlen);
500     assert(seed[seedlen-1] == '/');
501     seed[seedlen-1] = '\0';
502     sfree(rowdata);
503     return seed;
504 }
505
506 static char *validate_seed(game_params *params, char *seed)
507 {
508     int i, n, rowspace;
509     char *p;
510
511     for (i = 0; i < params->w + params->h; i++) {
512         if (i < params->w)
513             rowspace = params->h + 1;
514         else
515             rowspace = params->w + 1;
516
517         if (*seed && isdigit((unsigned char)*seed)) {
518             do {
519                 p = seed;
520                 while (seed && isdigit((unsigned char)*seed)) seed++;
521                 n = atoi(p);
522                 rowspace -= n+1;
523
524                 if (rowspace < 0) {
525                     if (i < params->w)
526                         return "at least one column contains more numbers than will fit";
527                     else
528                         return "at least one row contains more numbers than will fit";
529                 }
530             } while (*seed++ == '.');
531         } else {
532             seed++;                    /* expect a slash immediately */
533         }
534
535         if (seed[-1] == '/') {
536             if (i+1 == params->w + params->h)
537                 return "too many row/column specifications";
538         } else if (seed[-1] == '\0') {
539             if (i+1 < params->w + params->h)
540                 return "too few row/column specifications";
541         } else
542             return "unrecognised character in game specification";
543     }
544
545     return NULL;
546 }
547
548 static game_state *new_game(game_params *params, char *seed)
549 {
550     int i;
551     char *p;
552     game_state *state = snew(game_state);
553
554     state->w = params->w;
555     state->h = params->h;
556
557     state->grid = snewn(state->w * state->h, unsigned char);
558     memset(state->grid, GRID_UNKNOWN, state->w * state->h);
559
560     state->rowsize = max(state->w, state->h);
561     state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
562     state->rowlen = snewn(state->w + state->h, int);
563
564     state->completed = FALSE;
565
566     for (i = 0; i < params->w + params->h; i++) {
567         state->rowlen[i] = 0;
568         if (*seed && isdigit((unsigned char)*seed)) {
569             do {
570                 p = seed;
571                 while (seed && isdigit((unsigned char)*seed)) seed++;
572                 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
573                     atoi(p);
574             } while (*seed++ == '.');
575         } else {
576             seed++;                    /* expect a slash immediately */
577         }
578     }
579
580     return state;
581 }
582
583 static game_state *dup_game(game_state *state)
584 {
585     game_state *ret = snew(game_state);
586
587     ret->w = state->w;
588     ret->h = state->h;
589
590     ret->grid = snewn(ret->w * ret->h, unsigned char);
591     memcpy(ret->grid, state->grid, ret->w * ret->h);
592
593     ret->rowsize = state->rowsize;
594     ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
595     ret->rowlen = snewn(ret->w + ret->h, int);
596     memcpy(ret->rowdata, state->rowdata,
597            ret->rowsize * (ret->w + ret->h) * sizeof(int));
598     memcpy(ret->rowlen, state->rowlen,
599            (ret->w + ret->h) * sizeof(int));
600
601     ret->completed = state->completed;
602
603     return ret;
604 }
605
606 static void free_game(game_state *state)
607 {
608     sfree(state->rowdata);
609     sfree(state->rowlen);
610     sfree(state->grid);
611     sfree(state);
612 }
613
614 struct game_ui {
615     int dragging;
616     int drag_start_x;
617     int drag_start_y;
618     int drag_end_x;
619     int drag_end_y;
620     int drag, release, state;
621 };
622
623 static game_ui *new_ui(game_state *state)
624 {
625     game_ui *ret;
626
627     ret = snew(game_ui);
628     ret->dragging = FALSE;
629
630     return ret;
631 }
632
633 static void free_ui(game_ui *ui)
634 {
635     sfree(ui);
636 }
637
638 static game_state *make_move(game_state *from, game_ui *ui,
639                              int x, int y, int button)
640 {
641     game_state *ret;
642
643     x = FROMCOORD(from->w, x);
644     y = FROMCOORD(from->h, y);
645
646     if (x >= 0 && x < from->w && y >= 0 && y < from->h &&
647         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
648          button == MIDDLE_BUTTON)) {
649
650         ui->dragging = TRUE;
651
652         if (button == LEFT_BUTTON) {
653             ui->drag = LEFT_DRAG;
654             ui->release = LEFT_RELEASE;
655             ui->state = GRID_FULL;
656         } else if (button == RIGHT_BUTTON) {
657             ui->drag = RIGHT_DRAG;
658             ui->release = RIGHT_RELEASE;
659             ui->state = GRID_EMPTY;
660         } else /* if (button == MIDDLE_BUTTON) */ {
661             ui->drag = MIDDLE_DRAG;
662             ui->release = MIDDLE_RELEASE;
663             ui->state = GRID_UNKNOWN;
664         }
665
666         ui->drag_start_x = ui->drag_end_x = x;
667         ui->drag_start_y = ui->drag_end_y = y;
668
669         return from;                   /* UI activity occurred */
670     }
671
672     if (ui->dragging && button == ui->drag) {
673         /*
674          * There doesn't seem much point in allowing a rectangle
675          * drag; people will generally only want to drag a single
676          * horizontal or vertical line, so we make that easy by
677          * snapping to it.
678          * 
679          * Exception: if we're _middle_-button dragging to tag
680          * things as UNKNOWN, we may well want to trash an entire
681          * area and start over!
682          */
683         if (ui->state != GRID_UNKNOWN) {
684             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
685                 y = ui->drag_start_y;
686             else
687                 x = ui->drag_start_x;
688         }
689
690         if (x < 0) x = 0;
691         if (y < 0) y = 0;
692         if (x >= from->w) x = from->w - 1;
693         if (y >= from->h) y = from->h - 1;
694
695         ui->drag_end_x = x;
696         ui->drag_end_y = y;
697
698         return from;                   /* UI activity occurred */
699     }
700
701     if (ui->dragging && button == ui->release) {
702         int x1, x2, y1, y2, xx, yy;
703         int move_needed = FALSE;
704
705         x1 = min(ui->drag_start_x, ui->drag_end_x);
706         x2 = max(ui->drag_start_x, ui->drag_end_x);
707         y1 = min(ui->drag_start_y, ui->drag_end_y);
708         y2 = max(ui->drag_start_y, ui->drag_end_y);
709
710         for (yy = y1; yy <= y2; yy++)
711             for (xx = x1; xx <= x2; xx++)
712                 if (from->grid[yy * from->w + xx] != ui->state)
713                     move_needed = TRUE;
714
715         ui->dragging = FALSE;
716
717         if (move_needed) {
718             ret = dup_game(from);
719             for (yy = y1; yy <= y2; yy++)
720                 for (xx = x1; xx <= x2; xx++)
721                     ret->grid[yy * ret->w + xx] = ui->state;
722
723             /*
724              * An actual change, so check to see if we've completed
725              * the game.
726              */
727             if (!ret->completed) {
728                 int *rowdata = snewn(ret->rowsize, int);
729                 int i, len;
730
731                 ret->completed = TRUE;
732
733                 for (i=0; i<ret->w; i++) {
734                     len = compute_rowdata(rowdata,
735                                           ret->grid+i, ret->h, ret->w);
736                     if (len != ret->rowlen[i] ||
737                         memcmp(ret->rowdata+i*ret->rowsize, rowdata,
738                                len * sizeof(int))) {
739                         ret->completed = FALSE;
740                         break;
741                     }
742                 }
743                 for (i=0; i<ret->h; i++) {
744                     len = compute_rowdata(rowdata,
745                                           ret->grid+i*ret->w, ret->w, 1);
746                     if (len != ret->rowlen[i+ret->w] ||
747                         memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
748                                len * sizeof(int))) {
749                         ret->completed = FALSE;
750                         break;
751                     }
752                 }
753
754                 sfree(rowdata);
755             }
756
757             return ret;
758         } else
759             return from;               /* UI activity occurred */
760     }
761
762     return NULL;
763 }
764
765 /* ----------------------------------------------------------------------
766  * Drawing routines.
767  */
768
769 struct game_drawstate {
770     int started;
771     int w, h;
772     unsigned char *visible;
773 };
774
775 static void game_size(game_params *params, int *x, int *y)
776 {
777     *x = SIZE(params->w);
778     *y = SIZE(params->h);
779 }
780
781 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
782 {
783     float *ret = snewn(3 * NCOLOURS, float);
784
785     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
786
787     ret[COL_GRID * 3 + 0] = 0.3F;
788     ret[COL_GRID * 3 + 1] = 0.3F;
789     ret[COL_GRID * 3 + 2] = 0.3F;
790
791     ret[COL_UNKNOWN * 3 + 0] = 0.5F;
792     ret[COL_UNKNOWN * 3 + 1] = 0.5F;
793     ret[COL_UNKNOWN * 3 + 2] = 0.5F;
794
795     ret[COL_FULL * 3 + 0] = 0.0F;
796     ret[COL_FULL * 3 + 1] = 0.0F;
797     ret[COL_FULL * 3 + 2] = 0.0F;
798
799     ret[COL_EMPTY * 3 + 0] = 1.0F;
800     ret[COL_EMPTY * 3 + 1] = 1.0F;
801     ret[COL_EMPTY * 3 + 2] = 1.0F;
802
803     *ncolours = NCOLOURS;
804     return ret;
805 }
806
807 static game_drawstate *game_new_drawstate(game_state *state)
808 {
809     struct game_drawstate *ds = snew(struct game_drawstate);
810
811     ds->started = FALSE;
812     ds->w = state->w;
813     ds->h = state->h;
814     ds->visible = snewn(ds->w * ds->h, unsigned char);
815     memset(ds->visible, 255, ds->w * ds->h);
816
817     return ds;
818 }
819
820 static void game_free_drawstate(game_drawstate *ds)
821 {
822     sfree(ds->visible);
823     sfree(ds);
824 }
825
826 static void grid_square(frontend *fe, game_drawstate *ds,
827                         int y, int x, int state)
828 {
829     int xl, xr, yt, yb;
830
831     draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
832               TILE_SIZE, TILE_SIZE, COL_GRID);
833
834     xl = (x % 5 == 0 ? 1 : 0);
835     yt = (y % 5 == 0 ? 1 : 0);
836     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
837     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
838
839     draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
840               TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
841               (state == GRID_FULL ? COL_FULL :
842                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
843
844     draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
845                 TILE_SIZE, TILE_SIZE);
846 }
847
848 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
849                  game_state *state, int dir, game_ui *ui,
850                  float animtime, float flashtime)
851 {
852     int i, j;
853     int x1, x2, y1, y2;
854
855     if (!ds->started) {
856         /*
857          * The initial contents of the window are not guaranteed
858          * and can vary with front ends. To be on the safe side,
859          * all games should start by drawing a big background-
860          * colour rectangle covering the whole window.
861          */
862         draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
863
864         /*
865          * Draw the numbers.
866          */
867         for (i = 0; i < ds->w + ds->h; i++) {
868             int rowlen = state->rowlen[i];
869             int *rowdata = state->rowdata + state->rowsize * i;
870             int nfit;
871
872             /*
873              * Normally I space the numbers out by the same
874              * distance as the tile size. However, if there are
875              * more numbers than available spaces, I have to squash
876              * them up a bit.
877              */
878             nfit = max(rowlen, TLBORDER(ds->h))-1;
879             assert(nfit > 0);
880
881             for (j = 0; j < rowlen; j++) {
882                 int x, y;
883                 char str[80];
884
885                 if (i < ds->w) {
886                     x = TOCOORD(ds->w, i);
887                     y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
888                     y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
889                 } else {
890                     y = TOCOORD(ds->h, i - ds->w);
891                     x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
892                     x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
893                 }
894
895                 sprintf(str, "%d", rowdata[j]);
896                 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
897                           TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
898                           COL_FULL, str);   /* FIXME: COL_TEXT */
899             }
900         }
901
902         /*
903          * Draw the grid outline.
904          */
905         draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
906                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
907                   COL_GRID);
908
909         ds->started = TRUE;
910
911         draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
912     }
913
914     if (ui->dragging) {
915         x1 = min(ui->drag_start_x, ui->drag_end_x);
916         x2 = max(ui->drag_start_x, ui->drag_end_x);
917         y1 = min(ui->drag_start_y, ui->drag_end_y);
918         y2 = max(ui->drag_start_y, ui->drag_end_y);
919     } else {
920         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
921     }
922
923     /*
924      * Now draw any grid squares which have changed since last
925      * redraw.
926      */
927     for (i = 0; i < ds->h; i++) {
928         for (j = 0; j < ds->w; j++) {
929             int val;
930
931             /*
932              * Work out what state this square should be drawn in,
933              * taking any current drag operation into account.
934              */
935             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
936                 val = ui->state;
937             else
938                 val = state->grid[i * state->w + j];
939
940             /*
941              * Briefly invert everything twice during a completion
942              * flash.
943              */
944             if (flashtime > 0 &&
945                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
946                 val != GRID_UNKNOWN)
947                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
948
949             if (ds->visible[i * ds->w + j] != val) {
950                 grid_square(fe, ds, i, j, val);
951                 ds->visible[i * ds->w + j] = val;
952             }
953         }
954     }
955 }
956
957 static float game_anim_length(game_state *oldstate,
958                               game_state *newstate, int dir)
959 {
960     return 0.0F;
961 }
962
963 static float game_flash_length(game_state *oldstate,
964                                game_state *newstate, int dir)
965 {
966     if (!oldstate->completed && newstate->completed)
967         return FLASH_TIME;
968     return 0.0F;
969 }
970
971 static int game_wants_statusbar(void)
972 {
973     return FALSE;
974 }
975
976 #ifdef COMBINED
977 #define thegame pattern
978 #endif
979
980 const struct game thegame = {
981     "Pattern", "games.pattern", TRUE,
982     default_params,
983     game_fetch_preset,
984     decode_params,
985     encode_params,
986     free_params,
987     dup_params,
988     game_configure,
989     custom_params,
990     validate_params,
991     new_game_seed,
992     validate_seed,
993     new_game,
994     dup_game,
995     free_game,
996     new_ui,
997     free_ui,
998     make_move,
999     game_size,
1000     game_colours,
1001     game_new_drawstate,
1002     game_free_drawstate,
1003     game_redraw,
1004     game_anim_length,
1005     game_flash_length,
1006     game_wants_statusbar,
1007 };