chiark / gitweb /
Introduced a new function in every game which formats a game_state
[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         /*
421          * The game is a bit too easy if any row or column is
422          * completely black or completely white. An exception is
423          * made for rows/columns that are under 3 squares,
424          * otherwise nothing will ever be successfully generated.
425          */
426         ok = TRUE;
427         if (w > 2) {
428             for (i = 0; i < h; i++) {
429                 int colours = 0;
430                 for (j = 0; j < w; j++)
431                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
432                 if (colours != 3)
433                     ok = FALSE;
434             }
435         }
436         if (h > 2) {
437             for (j = 0; j < w; j++) {
438                 int colours = 0;
439                 for (i = 0; i < h; i++)
440                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
441                 if (colours != 3)
442                     ok = FALSE;
443             }
444         }
445         if (!ok)
446             continue;
447
448         memset(matrix, 0, w*h);
449
450         do {
451             done_any = 0;
452             for (i=0; i<h; i++) {
453                 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
454                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
455                                    matrix+i*w, w, 1, rowdata);
456             }
457             for (i=0; i<w; i++) {
458                 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
459                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
460                                    matrix+i, h, w, rowdata);
461             }
462         } while (done_any);
463
464         ok = TRUE;
465         for (i=0; i<h; i++) {
466             for (j=0; j<w; j++) {
467                 if (matrix[i*w+j] == UNKNOWN)
468                     ok = FALSE;
469             }
470         }
471     } while (!ok);
472
473     sfree(matrix);
474     sfree(workspace);
475     sfree(rowdata);
476     return grid;
477 }
478
479 static char *new_game_seed(game_params *params, random_state *rs)
480 {
481     unsigned char *grid;
482     int i, j, max, rowlen, *rowdata;
483     char intbuf[80], *seed;
484     int seedlen, seedpos;
485
486     grid = generate_soluble(rs, params->w, params->h);
487     max = max(params->w, params->h);
488     rowdata = snewn(max, int);
489
490     /*
491      * Seed is a slash-separated list of row contents; each row
492      * contents section is a dot-separated list of integers. Row
493      * contents are listed in the order (columns left to right,
494      * then rows top to bottom).
495      * 
496      * Simplest way to handle memory allocation is to make two
497      * passes, first computing the seed size and then writing it
498      * out.
499      */
500     seedlen = 0;
501     for (i = 0; i < params->w + params->h; i++) {
502         if (i < params->w)
503             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
504         else
505             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
506                                      params->w, 1);
507         if (rowlen > 0) {
508             for (j = 0; j < rowlen; j++) {
509                 seedlen += 1 + sprintf(intbuf, "%d", rowdata[j]);
510             }
511         } else {
512             seedlen++;
513         }
514     }
515     seed = snewn(seedlen, char);
516     seedpos = 0;
517     for (i = 0; i < params->w + params->h; i++) {
518         if (i < params->w)
519             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
520         else
521             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
522                                      params->w, 1);
523         if (rowlen > 0) {
524             for (j = 0; j < rowlen; j++) {
525                 int len = sprintf(seed+seedpos, "%d", rowdata[j]);
526                 if (j+1 < rowlen)
527                     seed[seedpos + len] = '.';
528                 else
529                     seed[seedpos + len] = '/';
530                 seedpos += len+1;
531             }
532         } else {
533             seed[seedpos++] = '/';
534         }
535     }
536     assert(seedpos == seedlen);
537     assert(seed[seedlen-1] == '/');
538     seed[seedlen-1] = '\0';
539     sfree(rowdata);
540     return seed;
541 }
542
543 static char *validate_seed(game_params *params, char *seed)
544 {
545     int i, n, rowspace;
546     char *p;
547
548     for (i = 0; i < params->w + params->h; i++) {
549         if (i < params->w)
550             rowspace = params->h + 1;
551         else
552             rowspace = params->w + 1;
553
554         if (*seed && isdigit((unsigned char)*seed)) {
555             do {
556                 p = seed;
557                 while (seed && isdigit((unsigned char)*seed)) seed++;
558                 n = atoi(p);
559                 rowspace -= n+1;
560
561                 if (rowspace < 0) {
562                     if (i < params->w)
563                         return "at least one column contains more numbers than will fit";
564                     else
565                         return "at least one row contains more numbers than will fit";
566                 }
567             } while (*seed++ == '.');
568         } else {
569             seed++;                    /* expect a slash immediately */
570         }
571
572         if (seed[-1] == '/') {
573             if (i+1 == params->w + params->h)
574                 return "too many row/column specifications";
575         } else if (seed[-1] == '\0') {
576             if (i+1 < params->w + params->h)
577                 return "too few row/column specifications";
578         } else
579             return "unrecognised character in game specification";
580     }
581
582     return NULL;
583 }
584
585 static game_state *new_game(game_params *params, char *seed)
586 {
587     int i;
588     char *p;
589     game_state *state = snew(game_state);
590
591     state->w = params->w;
592     state->h = params->h;
593
594     state->grid = snewn(state->w * state->h, unsigned char);
595     memset(state->grid, GRID_UNKNOWN, state->w * state->h);
596
597     state->rowsize = max(state->w, state->h);
598     state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
599     state->rowlen = snewn(state->w + state->h, int);
600
601     state->completed = FALSE;
602
603     for (i = 0; i < params->w + params->h; i++) {
604         state->rowlen[i] = 0;
605         if (*seed && isdigit((unsigned char)*seed)) {
606             do {
607                 p = seed;
608                 while (seed && isdigit((unsigned char)*seed)) seed++;
609                 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
610                     atoi(p);
611             } while (*seed++ == '.');
612         } else {
613             seed++;                    /* expect a slash immediately */
614         }
615     }
616
617     return state;
618 }
619
620 static game_state *dup_game(game_state *state)
621 {
622     game_state *ret = snew(game_state);
623
624     ret->w = state->w;
625     ret->h = state->h;
626
627     ret->grid = snewn(ret->w * ret->h, unsigned char);
628     memcpy(ret->grid, state->grid, ret->w * ret->h);
629
630     ret->rowsize = state->rowsize;
631     ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
632     ret->rowlen = snewn(ret->w + ret->h, int);
633     memcpy(ret->rowdata, state->rowdata,
634            ret->rowsize * (ret->w + ret->h) * sizeof(int));
635     memcpy(ret->rowlen, state->rowlen,
636            (ret->w + ret->h) * sizeof(int));
637
638     ret->completed = state->completed;
639
640     return ret;
641 }
642
643 static void free_game(game_state *state)
644 {
645     sfree(state->rowdata);
646     sfree(state->rowlen);
647     sfree(state->grid);
648     sfree(state);
649 }
650
651 static char *game_text_format(game_state *state)
652 {
653     return NULL;
654 }
655
656 struct game_ui {
657     int dragging;
658     int drag_start_x;
659     int drag_start_y;
660     int drag_end_x;
661     int drag_end_y;
662     int drag, release, state;
663 };
664
665 static game_ui *new_ui(game_state *state)
666 {
667     game_ui *ret;
668
669     ret = snew(game_ui);
670     ret->dragging = FALSE;
671
672     return ret;
673 }
674
675 static void free_ui(game_ui *ui)
676 {
677     sfree(ui);
678 }
679
680 static game_state *make_move(game_state *from, game_ui *ui,
681                              int x, int y, int button)
682 {
683     game_state *ret;
684
685     x = FROMCOORD(from->w, x);
686     y = FROMCOORD(from->h, y);
687
688     if (x >= 0 && x < from->w && y >= 0 && y < from->h &&
689         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
690          button == MIDDLE_BUTTON)) {
691
692         ui->dragging = TRUE;
693
694         if (button == LEFT_BUTTON) {
695             ui->drag = LEFT_DRAG;
696             ui->release = LEFT_RELEASE;
697             ui->state = GRID_FULL;
698         } else if (button == RIGHT_BUTTON) {
699             ui->drag = RIGHT_DRAG;
700             ui->release = RIGHT_RELEASE;
701             ui->state = GRID_EMPTY;
702         } else /* if (button == MIDDLE_BUTTON) */ {
703             ui->drag = MIDDLE_DRAG;
704             ui->release = MIDDLE_RELEASE;
705             ui->state = GRID_UNKNOWN;
706         }
707
708         ui->drag_start_x = ui->drag_end_x = x;
709         ui->drag_start_y = ui->drag_end_y = y;
710
711         return from;                   /* UI activity occurred */
712     }
713
714     if (ui->dragging && button == ui->drag) {
715         /*
716          * There doesn't seem much point in allowing a rectangle
717          * drag; people will generally only want to drag a single
718          * horizontal or vertical line, so we make that easy by
719          * snapping to it.
720          * 
721          * Exception: if we're _middle_-button dragging to tag
722          * things as UNKNOWN, we may well want to trash an entire
723          * area and start over!
724          */
725         if (ui->state != GRID_UNKNOWN) {
726             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
727                 y = ui->drag_start_y;
728             else
729                 x = ui->drag_start_x;
730         }
731
732         if (x < 0) x = 0;
733         if (y < 0) y = 0;
734         if (x >= from->w) x = from->w - 1;
735         if (y >= from->h) y = from->h - 1;
736
737         ui->drag_end_x = x;
738         ui->drag_end_y = y;
739
740         return from;                   /* UI activity occurred */
741     }
742
743     if (ui->dragging && button == ui->release) {
744         int x1, x2, y1, y2, xx, yy;
745         int move_needed = FALSE;
746
747         x1 = min(ui->drag_start_x, ui->drag_end_x);
748         x2 = max(ui->drag_start_x, ui->drag_end_x);
749         y1 = min(ui->drag_start_y, ui->drag_end_y);
750         y2 = max(ui->drag_start_y, ui->drag_end_y);
751
752         for (yy = y1; yy <= y2; yy++)
753             for (xx = x1; xx <= x2; xx++)
754                 if (from->grid[yy * from->w + xx] != ui->state)
755                     move_needed = TRUE;
756
757         ui->dragging = FALSE;
758
759         if (move_needed) {
760             ret = dup_game(from);
761             for (yy = y1; yy <= y2; yy++)
762                 for (xx = x1; xx <= x2; xx++)
763                     ret->grid[yy * ret->w + xx] = ui->state;
764
765             /*
766              * An actual change, so check to see if we've completed
767              * the game.
768              */
769             if (!ret->completed) {
770                 int *rowdata = snewn(ret->rowsize, int);
771                 int i, len;
772
773                 ret->completed = TRUE;
774
775                 for (i=0; i<ret->w; i++) {
776                     len = compute_rowdata(rowdata,
777                                           ret->grid+i, ret->h, ret->w);
778                     if (len != ret->rowlen[i] ||
779                         memcmp(ret->rowdata+i*ret->rowsize, rowdata,
780                                len * sizeof(int))) {
781                         ret->completed = FALSE;
782                         break;
783                     }
784                 }
785                 for (i=0; i<ret->h; i++) {
786                     len = compute_rowdata(rowdata,
787                                           ret->grid+i*ret->w, ret->w, 1);
788                     if (len != ret->rowlen[i+ret->w] ||
789                         memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
790                                len * sizeof(int))) {
791                         ret->completed = FALSE;
792                         break;
793                     }
794                 }
795
796                 sfree(rowdata);
797             }
798
799             return ret;
800         } else
801             return from;               /* UI activity occurred */
802     }
803
804     return NULL;
805 }
806
807 /* ----------------------------------------------------------------------
808  * Drawing routines.
809  */
810
811 struct game_drawstate {
812     int started;
813     int w, h;
814     unsigned char *visible;
815 };
816
817 static void game_size(game_params *params, int *x, int *y)
818 {
819     *x = SIZE(params->w);
820     *y = SIZE(params->h);
821 }
822
823 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
824 {
825     float *ret = snewn(3 * NCOLOURS, float);
826
827     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
828
829     ret[COL_GRID * 3 + 0] = 0.3F;
830     ret[COL_GRID * 3 + 1] = 0.3F;
831     ret[COL_GRID * 3 + 2] = 0.3F;
832
833     ret[COL_UNKNOWN * 3 + 0] = 0.5F;
834     ret[COL_UNKNOWN * 3 + 1] = 0.5F;
835     ret[COL_UNKNOWN * 3 + 2] = 0.5F;
836
837     ret[COL_FULL * 3 + 0] = 0.0F;
838     ret[COL_FULL * 3 + 1] = 0.0F;
839     ret[COL_FULL * 3 + 2] = 0.0F;
840
841     ret[COL_EMPTY * 3 + 0] = 1.0F;
842     ret[COL_EMPTY * 3 + 1] = 1.0F;
843     ret[COL_EMPTY * 3 + 2] = 1.0F;
844
845     *ncolours = NCOLOURS;
846     return ret;
847 }
848
849 static game_drawstate *game_new_drawstate(game_state *state)
850 {
851     struct game_drawstate *ds = snew(struct game_drawstate);
852
853     ds->started = FALSE;
854     ds->w = state->w;
855     ds->h = state->h;
856     ds->visible = snewn(ds->w * ds->h, unsigned char);
857     memset(ds->visible, 255, ds->w * ds->h);
858
859     return ds;
860 }
861
862 static void game_free_drawstate(game_drawstate *ds)
863 {
864     sfree(ds->visible);
865     sfree(ds);
866 }
867
868 static void grid_square(frontend *fe, game_drawstate *ds,
869                         int y, int x, int state)
870 {
871     int xl, xr, yt, yb;
872
873     draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
874               TILE_SIZE, TILE_SIZE, COL_GRID);
875
876     xl = (x % 5 == 0 ? 1 : 0);
877     yt = (y % 5 == 0 ? 1 : 0);
878     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
879     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
880
881     draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
882               TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
883               (state == GRID_FULL ? COL_FULL :
884                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
885
886     draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
887                 TILE_SIZE, TILE_SIZE);
888 }
889
890 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
891                  game_state *state, int dir, game_ui *ui,
892                  float animtime, float flashtime)
893 {
894     int i, j;
895     int x1, x2, y1, y2;
896
897     if (!ds->started) {
898         /*
899          * The initial contents of the window are not guaranteed
900          * and can vary with front ends. To be on the safe side,
901          * all games should start by drawing a big background-
902          * colour rectangle covering the whole window.
903          */
904         draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
905
906         /*
907          * Draw the numbers.
908          */
909         for (i = 0; i < ds->w + ds->h; i++) {
910             int rowlen = state->rowlen[i];
911             int *rowdata = state->rowdata + state->rowsize * i;
912             int nfit;
913
914             /*
915              * Normally I space the numbers out by the same
916              * distance as the tile size. However, if there are
917              * more numbers than available spaces, I have to squash
918              * them up a bit.
919              */
920             nfit = max(rowlen, TLBORDER(ds->h))-1;
921             assert(nfit > 0);
922
923             for (j = 0; j < rowlen; j++) {
924                 int x, y;
925                 char str[80];
926
927                 if (i < ds->w) {
928                     x = TOCOORD(ds->w, i);
929                     y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
930                     y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
931                 } else {
932                     y = TOCOORD(ds->h, i - ds->w);
933                     x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
934                     x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
935                 }
936
937                 sprintf(str, "%d", rowdata[j]);
938                 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
939                           TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
940                           COL_FULL, str);   /* FIXME: COL_TEXT */
941             }
942         }
943
944         /*
945          * Draw the grid outline.
946          */
947         draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
948                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
949                   COL_GRID);
950
951         ds->started = TRUE;
952
953         draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
954     }
955
956     if (ui->dragging) {
957         x1 = min(ui->drag_start_x, ui->drag_end_x);
958         x2 = max(ui->drag_start_x, ui->drag_end_x);
959         y1 = min(ui->drag_start_y, ui->drag_end_y);
960         y2 = max(ui->drag_start_y, ui->drag_end_y);
961     } else {
962         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
963     }
964
965     /*
966      * Now draw any grid squares which have changed since last
967      * redraw.
968      */
969     for (i = 0; i < ds->h; i++) {
970         for (j = 0; j < ds->w; j++) {
971             int val;
972
973             /*
974              * Work out what state this square should be drawn in,
975              * taking any current drag operation into account.
976              */
977             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
978                 val = ui->state;
979             else
980                 val = state->grid[i * state->w + j];
981
982             /*
983              * Briefly invert everything twice during a completion
984              * flash.
985              */
986             if (flashtime > 0 &&
987                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
988                 val != GRID_UNKNOWN)
989                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
990
991             if (ds->visible[i * ds->w + j] != val) {
992                 grid_square(fe, ds, i, j, val);
993                 ds->visible[i * ds->w + j] = val;
994             }
995         }
996     }
997 }
998
999 static float game_anim_length(game_state *oldstate,
1000                               game_state *newstate, int dir)
1001 {
1002     return 0.0F;
1003 }
1004
1005 static float game_flash_length(game_state *oldstate,
1006                                game_state *newstate, int dir)
1007 {
1008     if (!oldstate->completed && newstate->completed)
1009         return FLASH_TIME;
1010     return 0.0F;
1011 }
1012
1013 static int game_wants_statusbar(void)
1014 {
1015     return FALSE;
1016 }
1017
1018 #ifdef COMBINED
1019 #define thegame pattern
1020 #endif
1021
1022 const struct game thegame = {
1023     "Pattern", "games.pattern",
1024     default_params,
1025     game_fetch_preset,
1026     decode_params,
1027     encode_params,
1028     free_params,
1029     dup_params,
1030     TRUE, game_configure, custom_params,
1031     validate_params,
1032     new_game_seed,
1033     validate_seed,
1034     new_game,
1035     dup_game,
1036     free_game,
1037     FALSE, game_text_format,
1038     new_ui,
1039     free_ui,
1040     make_move,
1041     game_size,
1042     game_colours,
1043     game_new_drawstate,
1044     game_free_drawstate,
1045     game_redraw,
1046     game_anim_length,
1047     game_flash_length,
1048     game_wants_statusbar,
1049 };
1050
1051 #ifdef STANDALONE_SOLVER
1052
1053 /*
1054  * gcc -DSTANDALONE_SOLVER -o patternsolver pattern.c malloc.c
1055  */
1056
1057 #include <stdarg.h>
1058
1059 void frontend_default_colour(frontend *fe, float *output) {}
1060 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1061                int align, int colour, char *text) {}
1062 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
1063 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
1064 void draw_polygon(frontend *fe, int *coords, int npoints,
1065                   int fill, int colour) {}
1066 void clip(frontend *fe, int x, int y, int w, int h) {}
1067 void unclip(frontend *fe) {}
1068 void start_draw(frontend *fe) {}
1069 void draw_update(frontend *fe, int x, int y, int w, int h) {}
1070 void end_draw(frontend *fe) {}
1071 unsigned long random_upto(random_state *state, unsigned long limit)
1072 { assert(!"Shouldn't get randomness"); return 0; }
1073
1074 void fatal(char *fmt, ...)
1075 {
1076     va_list ap;
1077
1078     fprintf(stderr, "fatal error: ");
1079
1080     va_start(ap, fmt);
1081     vfprintf(stderr, fmt, ap);
1082     va_end(ap);
1083
1084     fprintf(stderr, "\n");
1085     exit(1);
1086 }
1087
1088 int main(int argc, char **argv)
1089 {
1090     game_params *p;
1091     game_state *s;
1092     int recurse = TRUE;
1093     char *id = NULL, *seed, *err;
1094     int y, x;
1095     int grade = FALSE;
1096
1097     while (--argc > 0) {
1098         char *p = *++argv;
1099         if (*p == '-') {
1100             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
1101             return 1;
1102         } else {
1103             id = p;
1104         }
1105     }
1106
1107     if (!id) {
1108         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1109         return 1;
1110     }
1111
1112     seed = strchr(id, ':');
1113     if (!seed) {
1114         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1115         return 1;
1116     }
1117     *seed++ = '\0';
1118
1119     p = decode_params(id);
1120     err = validate_seed(p, seed);
1121     if (err) {
1122         fprintf(stderr, "%s: %s\n", argv[0], err);
1123         return 1;
1124     }
1125     s = new_game(p, seed);
1126
1127     {
1128         int w = p->w, h = p->h, i, j, done_any, max;
1129         unsigned char *matrix, *workspace;
1130         int *rowdata;
1131
1132         matrix = snewn(w*h, unsigned char);
1133         max = max(w, h);
1134         workspace = snewn(max*3, unsigned char);
1135         rowdata = snewn(max+1, int);
1136
1137         memset(matrix, 0, w*h);
1138
1139         do {
1140             done_any = 0;
1141             for (i=0; i<h; i++) {
1142                 memcpy(rowdata, s->rowdata + s->rowsize*(w+i),
1143                        max*sizeof(int));
1144                 rowdata[s->rowlen[w+i]] = 0;
1145                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1146                                    matrix+i*w, w, 1, rowdata);
1147             }
1148             for (i=0; i<w; i++) {
1149                 memcpy(rowdata, s->rowdata + s->rowsize*i, max*sizeof(int));
1150                 rowdata[s->rowlen[i]] = 0;
1151                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1152                                    matrix+i, h, w, rowdata);
1153             }
1154         } while (done_any);
1155
1156         for (i = 0; i < h; i++) {
1157             for (j = 0; j < w; j++) {
1158                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1159                          matrix[i*w+j] == BLOCK ? '#' :
1160                          matrix[i*w+j] == DOT ? '.' :
1161                          '!');
1162                 putchar(c);
1163             }
1164             printf("\n");
1165         }
1166     }
1167
1168     return 0;
1169 }
1170
1171 #endif