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