chiark / gitweb /
Forbid undo of new-game if it would change the params.
[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 enum {
15     COL_BACKGROUND,
16     COL_EMPTY,
17     COL_FULL,
18     COL_TEXT,
19     COL_UNKNOWN,
20     COL_GRID,
21     COL_CURSOR,
22     COL_ERROR,
23     NCOLOURS
24 };
25
26 #define PREFERRED_TILE_SIZE 24
27 #define TILE_SIZE (ds->tilesize)
28 #define BORDER (3 * TILE_SIZE / 4)
29 #define TLBORDER(d) ( (d) / 5 + 2 )
30 #define GUTTER (TILE_SIZE / 2)
31
32 #define FROMCOORD(d, x) \
33         ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
34
35 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
36 #define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
37
38 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
39
40 struct game_params {
41     int w, h;
42 };
43
44 #define GRID_UNKNOWN 2
45 #define GRID_FULL 1
46 #define GRID_EMPTY 0
47
48 typedef struct game_state_common {
49     /* Parts of the game state that don't change during play. */
50     int w, h;
51     int rowsize;
52     int *rowdata, *rowlen;
53     unsigned char *immutable;
54     int refcount;
55 } game_state_common;
56
57 struct game_state {
58     game_state_common *common;
59     unsigned char *grid;
60     int completed, cheated;
61 };
62
63 #define FLASH_TIME 0.13F
64
65 static game_params *default_params(void)
66 {
67     game_params *ret = snew(game_params);
68
69     ret->w = ret->h = 15;
70
71     return ret;
72 }
73
74 static const struct game_params pattern_presets[] = {
75     {10, 10},
76     {15, 15},
77     {20, 20},
78 #ifndef SLOW_SYSTEM
79     {25, 25},
80     {30, 30},
81 #endif
82 };
83
84 static int game_fetch_preset(int i, char **name, game_params **params)
85 {
86     game_params *ret;
87     char str[80];
88
89     if (i < 0 || i >= lenof(pattern_presets))
90         return FALSE;
91
92     ret = snew(game_params);
93     *ret = pattern_presets[i];
94
95     sprintf(str, "%dx%d", ret->w, ret->h);
96
97     *name = dupstr(str);
98     *params = ret;
99     return TRUE;
100 }
101
102 static void free_params(game_params *params)
103 {
104     sfree(params);
105 }
106
107 static game_params *dup_params(const game_params *params)
108 {
109     game_params *ret = snew(game_params);
110     *ret = *params;                    /* structure copy */
111     return ret;
112 }
113
114 static void decode_params(game_params *ret, char const *string)
115 {
116     char const *p = string;
117
118     ret->w = atoi(p);
119     while (*p && isdigit((unsigned char)*p)) p++;
120     if (*p == 'x') {
121         p++;
122         ret->h = atoi(p);
123         while (*p && isdigit((unsigned char)*p)) p++;
124     } else {
125         ret->h = ret->w;
126     }
127 }
128
129 static char *encode_params(const game_params *params, int full)
130 {
131     char ret[400];
132     int len;
133
134     len = sprintf(ret, "%dx%d", params->w, params->h);
135     assert(len < lenof(ret));
136     ret[len] = '\0';
137
138     return dupstr(ret);
139 }
140
141 static config_item *game_configure(const game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(3, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].sval = dupstr(buf);
152     ret[0].ival = 0;
153
154     ret[1].name = "Height";
155     ret[1].type = C_STRING;
156     sprintf(buf, "%d", params->h);
157     ret[1].sval = dupstr(buf);
158     ret[1].ival = 0;
159
160     ret[2].name = NULL;
161     ret[2].type = C_END;
162     ret[2].sval = NULL;
163     ret[2].ival = 0;
164
165     return ret;
166 }
167
168 static game_params *custom_params(const config_item *cfg)
169 {
170     game_params *ret = snew(game_params);
171
172     ret->w = atoi(cfg[0].sval);
173     ret->h = atoi(cfg[1].sval);
174
175     return ret;
176 }
177
178 static char *validate_params(const game_params *params, int full)
179 {
180     if (params->w <= 0 || params->h <= 0)
181         return "Width and height must both 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 #ifndef STANDALONE_PICTURE_GENERATOR
230 static int float_compare(const void *av, const void *bv)
231 {
232     const float *a = (const float *)av;
233     const float *b = (const float *)bv;
234     if (*a < *b)
235         return -1;
236     else if (*a > *b)
237         return +1;
238     else
239         return 0;
240 }
241
242 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
243 {
244     float *fgrid;
245     float *fgrid2;
246     int step, i, j;
247     float threshold;
248
249     fgrid = snewn(w*h, float);
250
251     for (i = 0; i < h; i++) {
252         for (j = 0; j < w; j++) {
253             fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
254         }
255     }
256
257     /*
258      * The above gives a completely random splattering of black and
259      * white cells. We want to gently bias this in favour of _some_
260      * reasonably thick areas of white and black, while retaining
261      * some randomness and fine detail.
262      * 
263      * So we evolve the starting grid using a cellular automaton.
264      * Currently, I'm doing something very simple indeed, which is
265      * to set each square to the average of the surrounding nine
266      * cells (or the average of fewer, if we're on a corner).
267      */
268     for (step = 0; step < 1; step++) {
269         fgrid2 = snewn(w*h, float);
270
271         for (i = 0; i < h; i++) {
272             for (j = 0; j < w; j++) {
273                 float sx, xbar;
274                 int n, p, q;
275
276                 /*
277                  * Compute the average of the surrounding cells.
278                  */
279                 n = 0;
280                 sx = 0.F;
281                 for (p = -1; p <= +1; p++) {
282                     for (q = -1; q <= +1; q++) {
283                         if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
284                             continue;
285                         /*
286                          * An additional special case not mentioned
287                          * above: if a grid dimension is 2xn then
288                          * we do not average across that dimension
289                          * at all. Otherwise a 2x2 grid would
290                          * contain four identical squares.
291                          */
292                         if ((h==2 && p!=0) || (w==2 && q!=0))
293                             continue;
294                         n++;
295                         sx += fgrid[(i+p)*w+(j+q)];
296                     }
297                 }
298                 xbar = sx / n;
299
300                 fgrid2[i*w+j] = xbar;
301             }
302         }
303
304         sfree(fgrid);
305         fgrid = fgrid2;
306     }
307
308     fgrid2 = snewn(w*h, float);
309     memcpy(fgrid2, fgrid, w*h*sizeof(float));
310     qsort(fgrid2, w*h, sizeof(float), float_compare);
311     /* Choose a threshold that makes half the pixels black. In case of
312      * an odd number of pixels, select randomly between just under and
313      * just over half. */
314     {
315         int index = w * h / 2;
316         if (w & h & 1)
317             index += random_upto(rs, 2);
318         if (index < w*h)
319             threshold = fgrid2[index];
320         else
321             threshold = fgrid2[w*h-1] + 1;
322     }
323     sfree(fgrid2);
324
325     for (i = 0; i < h; i++) {
326         for (j = 0; j < w; j++) {
327             retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
328                               GRID_EMPTY);
329         }
330     }
331
332     sfree(fgrid);
333 }
334 #endif
335
336 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
337 {
338     int i, n;
339
340     n = 0;
341
342     for (i = 0; i < len; i++) {
343         if (start[i*step] == GRID_FULL) {
344             int runlen = 1;
345             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
346                 runlen++;
347             ret[n++] = runlen;
348             i += runlen;
349         }
350
351         if (i < len && start[i*step] == GRID_UNKNOWN)
352             return -1;
353     }
354
355     return n;
356 }
357
358 #define UNKNOWN 0
359 #define BLOCK 1
360 #define DOT 2
361 #define STILL_UNKNOWN 3
362
363 #ifdef STANDALONE_SOLVER
364 int verbose = FALSE;
365 #endif
366
367 static int do_recurse(unsigned char *known, unsigned char *deduced,
368                        unsigned char *row,
369                        unsigned char *minpos_done, unsigned char *maxpos_done,
370                        unsigned char *minpos_ok, unsigned char *maxpos_ok,
371                        int *data, int len,
372                        int freespace, int ndone, int lowest)
373 {
374     int i, j, k;
375
376
377     /* This algorithm basically tries all possible ways the given rows of
378      * black blocks can be laid out in the row/column being examined.
379      * Special care is taken to avoid checking the tail of a row/column
380      * if the same conditions have already been checked during this recursion
381      * The algorithm also takes care to cut its losses as soon as an
382      * invalid (partial) solution is detected.
383      */
384     if (data[ndone]) {
385         if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
386             if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
387                 for (i=0; i<lowest; i++)
388                     deduced[i] |= row[i];
389             }
390             return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
391         } else {
392             if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
393             if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
394         }
395         for (i=0; i<=freespace; i++) {
396             j = lowest;
397             for (k=0; k<i; k++) {
398                 if (known[j] == BLOCK) goto next_iter;
399                 row[j++] = DOT;
400             }
401             for (k=0; k<data[ndone]; k++) {
402                 if (known[j] == DOT) goto next_iter;
403                 row[j++] = BLOCK;
404             }
405             if (j < len) {
406                 if (known[j] == BLOCK) goto next_iter;
407                 row[j++] = DOT;
408             }
409             if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
410                            minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
411                 if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
412                 if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
413                 if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
414             }
415             next_iter:
416             j++;
417         }
418         return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
419     } else {
420         for (i=lowest; i<len; i++) {
421             if (known[i] == BLOCK) return FALSE;
422             row[i] = DOT;
423             }
424         for (i=0; i<len; i++)
425             deduced[i] |= row[i];
426         return TRUE;
427     }
428 }
429
430
431 static int do_row(unsigned char *known, unsigned char *deduced,
432                   unsigned char *row,
433                   unsigned char *minpos_done, unsigned char *maxpos_done,
434                   unsigned char *minpos_ok, unsigned char *maxpos_ok,
435                   unsigned char *start, int len, int step, int *data,
436                   unsigned int *changed
437 #ifdef STANDALONE_SOLVER
438                   , const char *rowcol, int index, int cluewid
439 #endif
440                   )
441 {
442     int rowlen, i, freespace, done_any;
443
444     freespace = len+1;
445     for (rowlen = 0; data[rowlen]; rowlen++) {
446         minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
447         maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
448         freespace -= data[rowlen]+1;
449     }
450
451     for (i = 0; i < len; i++) {
452         known[i] = start[i*step];
453         deduced[i] = 0;
454     }
455     for (i = len - 1; i >= 0 && known[i] == DOT; i--)
456         freespace--;
457
458     if (rowlen == 0) {
459         memset(deduced, DOT, len);
460     } else if (rowlen == 1 && data[0] == len) {
461         memset(deduced, BLOCK, len);
462     } else {
463         do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok,
464                    maxpos_ok, data, len, freespace, 0, 0);
465     }
466
467     done_any = FALSE;
468     for (i=0; i<len; i++)
469         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
470             start[i*step] = deduced[i];
471             if (changed) changed[i]++;
472             done_any = TRUE;
473         }
474 #ifdef STANDALONE_SOLVER
475     if (verbose && done_any) {
476         char buf[80];
477         int thiscluewid;
478         printf("%s %2d: [", rowcol, index);
479         for (thiscluewid = -1, i = 0; data[i]; i++)
480             thiscluewid += sprintf(buf, " %d", data[i]);
481         printf("%*s", cluewid - thiscluewid, "");
482         for (i = 0; data[i]; i++)
483             printf(" %d", data[i]);
484         printf(" ] ");
485         for (i = 0; i < len; i++)
486             putchar(known[i] == BLOCK ? '#' :
487                     known[i] == DOT ? '.' : '?');
488         printf(" -> ");
489         for (i = 0; i < len; i++)
490             putchar(start[i*step] == BLOCK ? '#' :
491                     start[i*step] == DOT ? '.' : '?');
492         putchar('\n');
493     }
494 #endif
495     return done_any;
496 }
497
498 static int solve_puzzle(const game_state *state, unsigned char *grid,
499                         int w, int h,
500                         unsigned char *matrix, unsigned char *workspace,
501                         unsigned int *changed_h, unsigned int *changed_w,
502                         int *rowdata
503 #ifdef STANDALONE_SOLVER
504                         , int cluewid
505 #else
506                         , int dummy
507 #endif
508                         )
509 {
510     int i, j, ok, max;
511     int max_h, max_w;
512
513     assert((state!=NULL && state->common->rowdata!=NULL) ^ (grid!=NULL));
514
515     max = max(w, h);
516
517     memset(matrix, 0, w*h);
518     if (state) {
519         for (i=0; i<w*h; i++) {
520             if (state->common->immutable[i])
521                 matrix[i] = state->grid[i];
522         }
523     }
524
525     /* For each column, compute how many squares can be deduced
526      * from just the row-data and initial clues.
527      * Later, changed_* will hold how many squares were changed
528      * in every row/column in the previous iteration
529      * Changed_* is used to choose the next rows / cols to re-examine
530      */
531     for (i=0; i<h; i++) {
532         int freespace, rowlen;
533         if (state && state->common->rowdata) {
534             memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
535             rowlen = state->common->rowlen[w+i];
536         } else {
537             rowlen = compute_rowdata(rowdata, grid+i*w, w, 1);
538         }
539         rowdata[rowlen] = 0;
540         if (rowlen == 0) {
541             changed_h[i] = w;
542         } else {
543             for (j=0, freespace=w+1; rowdata[j]; j++)
544                 freespace -= rowdata[j] + 1;
545             for (j=0, changed_h[i]=0; rowdata[j]; j++)
546                 if (rowdata[j] > freespace)
547                     changed_h[i] += rowdata[j] - freespace;
548         }
549         for (j = 0; j < w; j++)
550             if (matrix[i*w+j])
551                 changed_h[i]++;
552     }
553     for (i=0,max_h=0; i<h; i++)
554         if (changed_h[i] > max_h)
555             max_h = changed_h[i];
556     for (i=0; i<w; i++) {
557         int freespace, rowlen;
558         if (state && state->common->rowdata) {
559             memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
560             rowlen = state->common->rowlen[i];
561         } else {
562             rowlen = compute_rowdata(rowdata, grid+i, h, w);
563         }
564         rowdata[rowlen] = 0;
565         if (rowlen == 0) {
566             changed_w[i] = h;
567         } else {
568             for (j=0, freespace=h+1; rowdata[j]; j++)
569                 freespace -= rowdata[j] + 1;
570             for (j=0, changed_w[i]=0; rowdata[j]; j++)
571                 if (rowdata[j] > freespace)
572                     changed_w[i] += rowdata[j] - freespace;
573         }
574         for (j = 0; j < h; j++)
575             if (matrix[j*w+i])
576                 changed_w[i]++;
577     }
578     for (i=0,max_w=0; i<w; i++)
579         if (changed_w[i] > max_w)
580             max_w = changed_w[i];
581
582     /* Solve the puzzle.
583      * Process rows/columns individually. Deductions involving more than one
584      * row and/or column at a time are not supported.
585      * Take care to only process rows/columns which have been changed since they
586      * were previously processed.
587      * Also, prioritize rows/columns which have had the most changes since their
588      * previous processing, as they promise the greatest benefit.
589      * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
590      */
591     do {
592         for (; max_h && max_h >= max_w; max_h--) {
593             for (i=0; i<h; i++) {
594                 if (changed_h[i] >= max_h) {
595                     if (state && state->common->rowdata) {
596                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
597                         rowdata[state->common->rowlen[w+i]] = 0;
598                     } else {
599                         rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
600                     }
601                     do_row(workspace, workspace+max, workspace+2*max,
602                            workspace+3*max, workspace+4*max,
603                            workspace+5*max, workspace+6*max,
604                            matrix+i*w, w, 1, rowdata, changed_w
605 #ifdef STANDALONE_SOLVER
606                            , "row", i+1, cluewid
607 #endif
608                            );
609                     changed_h[i] = 0;
610                 }
611             }
612             for (i=0,max_w=0; i<w; i++)
613                 if (changed_w[i] > max_w)
614                     max_w = changed_w[i];
615         }
616         for (; max_w && max_w >= max_h; max_w--) {
617             for (i=0; i<w; i++) {
618                 if (changed_w[i] >= max_w) {
619                     if (state && state->common->rowdata) {
620                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
621                         rowdata[state->common->rowlen[i]] = 0;
622                     } else {
623                         rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
624                     }
625                     do_row(workspace, workspace+max, workspace+2*max,
626                            workspace+3*max, workspace+4*max,
627                            workspace+5*max, workspace+6*max,
628                            matrix+i, h, w, rowdata, changed_h
629 #ifdef STANDALONE_SOLVER
630                            , "col", i+1, cluewid
631 #endif
632                            );
633                     changed_w[i] = 0;
634                 }
635             }
636             for (i=0,max_h=0; i<h; i++)
637                 if (changed_h[i] > max_h)
638                     max_h = changed_h[i];
639         }
640     } while (max_h>0 || max_w>0);
641
642     ok = TRUE;
643     for (i=0; i<h; i++) {
644         for (j=0; j<w; j++) {
645             if (matrix[i*w+j] == UNKNOWN)
646                 ok = FALSE;
647         }
648     }
649
650     return ok;
651 }
652
653 #ifndef STANDALONE_PICTURE_GENERATOR
654 static unsigned char *generate_soluble(random_state *rs, int w, int h)
655 {
656     int i, j, ok, ntries, max;
657     unsigned char *grid, *matrix, *workspace;
658     unsigned int *changed_h, *changed_w;
659     int *rowdata;
660
661     max = max(w, h);
662
663     grid = snewn(w*h, unsigned char);
664     /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
665     matrix = snewn(w*h, unsigned char);
666     workspace = snewn(max*7, unsigned char);
667     changed_h = snewn(max+1, unsigned int);
668     changed_w = snewn(max+1, unsigned int);
669     rowdata = snewn(max+1, int);
670
671     ntries = 0;
672
673     do {
674         ntries++;
675
676         generate(rs, w, h, grid);
677
678         /*
679          * The game is a bit too easy if any row or column is
680          * completely black or completely white. An exception is
681          * made for rows/columns that are under 3 squares,
682          * otherwise nothing will ever be successfully generated.
683          */
684         ok = TRUE;
685         if (w > 2) {
686             for (i = 0; i < h; i++) {
687                 int colours = 0;
688                 for (j = 0; j < w; j++)
689                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
690                 if (colours != 3)
691                     ok = FALSE;
692             }
693         }
694         if (h > 2) {
695             for (j = 0; j < w; j++) {
696                 int colours = 0;
697                 for (i = 0; i < h; i++)
698                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
699                 if (colours != 3)
700                     ok = FALSE;
701             }
702         }
703         if (!ok)
704             continue;
705
706         ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
707                           changed_h, changed_w, rowdata, 0);
708     } while (!ok);
709
710     sfree(matrix);
711     sfree(workspace);
712     sfree(changed_h);
713     sfree(changed_w);
714     sfree(rowdata);
715     return grid;
716 }
717 #endif
718
719 #ifdef STANDALONE_PICTURE_GENERATOR
720 unsigned char *picture;
721 #endif
722
723 static char *new_game_desc(const game_params *params, random_state *rs,
724                            char **aux, int interactive)
725 {
726     unsigned char *grid;
727     int i, j, max, rowlen, *rowdata;
728     char intbuf[80], *desc;
729     int desclen, descpos;
730 #ifdef STANDALONE_PICTURE_GENERATOR
731     game_state *state;
732     int *index;
733 #endif
734
735     max = max(params->w, params->h);
736
737 #ifdef STANDALONE_PICTURE_GENERATOR
738     /*
739      * Fixed input picture.
740      */
741     grid = snewn(params->w * params->h, unsigned char);
742     memcpy(grid, picture, params->w * params->h);
743
744     /*
745      * Now winnow the immutable square set as far as possible.
746      */
747     state = snew(game_state);
748     state->grid = grid;
749     state->common = snew(game_state_common);
750     state->common->rowdata = NULL;
751     state->common->immutable = snewn(params->w * params->h, unsigned char);
752     memset(state->common->immutable, 1, params->w * params->h);
753
754     index = snewn(params->w * params->h, int);
755     for (i = 0; i < params->w * params->h; i++)
756         index[i] = i;
757     shuffle(index, params->w * params->h, sizeof(*index), rs);
758
759     {
760         unsigned char *matrix = snewn(params->w*params->h, unsigned char);
761         unsigned char *workspace = snewn(max*7, unsigned char);
762         unsigned int *changed_h = snewn(max+1, unsigned int);
763         unsigned int *changed_w = snewn(max+1, unsigned int);
764         int *rowdata = snewn(max+1, int);
765         for (i = 0; i < params->w * params->h; i++) {
766             state->common->immutable[index[i]] = 0;
767             if (!solve_puzzle(state, grid, params->w, params->h,
768                               matrix, workspace, changed_h, changed_w,
769                               rowdata, 0))
770                 state->common->immutable[index[i]] = 1;
771         }
772         sfree(workspace);
773         sfree(changed_h);
774         sfree(changed_w);
775         sfree(rowdata);
776         sfree(matrix);
777     }
778 #else
779     grid = generate_soluble(rs, params->w, params->h);
780 #endif
781     rowdata = snewn(max, int);
782
783     /*
784      * Save the solved game in aux.
785      */
786     if (aux) {
787         char *ai = snewn(params->w * params->h + 2, char);
788
789         /*
790          * String format is exactly the same as a solve move, so we
791          * can just dupstr this in solve_game().
792          */
793
794         ai[0] = 'S';
795
796         for (i = 0; i < params->w * params->h; i++)
797             ai[i+1] = grid[i] ? '1' : '0';
798
799         ai[params->w * params->h + 1] = '\0';
800
801         *aux = ai;
802     }
803
804     /*
805      * Seed is a slash-separated list of row contents; each row
806      * contents section is a dot-separated list of integers. Row
807      * contents are listed in the order (columns left to right,
808      * then rows top to bottom).
809      * 
810      * Simplest way to handle memory allocation is to make two
811      * passes, first computing the seed size and then writing it
812      * out.
813      */
814     desclen = 0;
815     for (i = 0; i < params->w + params->h; i++) {
816         if (i < params->w)
817             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
818         else
819             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
820                                      params->w, 1);
821         if (rowlen > 0) {
822             for (j = 0; j < rowlen; j++) {
823                 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
824             }
825         } else {
826             desclen++;
827         }
828     }
829     desc = snewn(desclen, char);
830     descpos = 0;
831     for (i = 0; i < params->w + params->h; i++) {
832         if (i < params->w)
833             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
834         else
835             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
836                                      params->w, 1);
837         if (rowlen > 0) {
838             for (j = 0; j < rowlen; j++) {
839                 int len = sprintf(desc+descpos, "%d", rowdata[j]);
840                 if (j+1 < rowlen)
841                     desc[descpos + len] = '.';
842                 else
843                     desc[descpos + len] = '/';
844                 descpos += len+1;
845             }
846         } else {
847             desc[descpos++] = '/';
848         }
849     }
850     assert(descpos == desclen);
851     assert(desc[desclen-1] == '/');
852     desc[desclen-1] = '\0';
853 #ifdef STANDALONE_PICTURE_GENERATOR
854     for (i = 0; i < params->w * params->h; i++)
855         if (state->common->immutable[i])
856             break;
857     if (i < params->w * params->h) {
858         /*
859          * At least one immutable square, so we need a suffix.
860          */
861         int run;
862
863         desc = sresize(desc, desclen + params->w * params->h + 3, char);
864         desc[descpos-1] = ',';
865
866         run = 0;
867         for (i = 0; i < params->w * params->h; i++) {
868             if (!state->common->immutable[i]) {
869                 run++;
870                 if (run == 25) {
871                     desc[descpos++] = 'z';
872                     run = 0;
873                 }
874             } else {
875                 desc[descpos++] = run + (grid[i] == GRID_FULL ? 'A' : 'a');
876                 run = 0;
877             }
878         }
879         if (run > 0)
880             desc[descpos++] = run + 'a';
881         desc[descpos] = '\0';
882     }
883     sfree(state->common->immutable);
884     sfree(state->common);
885     sfree(state);
886 #endif
887     sfree(rowdata);
888     sfree(grid);
889     return desc;
890 }
891
892 static char *validate_desc(const game_params *params, const char *desc)
893 {
894     int i, n, rowspace;
895     const char *p;
896
897     for (i = 0; i < params->w + params->h; i++) {
898         if (i < params->w)
899             rowspace = params->h + 1;
900         else
901             rowspace = params->w + 1;
902
903         if (*desc && isdigit((unsigned char)*desc)) {
904             do {
905                 p = desc;
906                 while (*desc && isdigit((unsigned char)*desc)) desc++;
907                 n = atoi(p);
908                 rowspace -= n+1;
909
910                 if (rowspace < 0) {
911                     if (i < params->w)
912                         return "at least one column contains more numbers than will fit";
913                     else
914                         return "at least one row contains more numbers than will fit";
915                 }
916             } while (*desc++ == '.');
917         } else {
918             desc++;                    /* expect a slash immediately */
919         }
920
921         if (desc[-1] == '/') {
922             if (i+1 == params->w + params->h)
923                 return "too many row/column specifications";
924         } else if (desc[-1] == '\0' || desc[-1] == ',') {
925             if (i+1 < params->w + params->h)
926                 return "too few row/column specifications";
927         } else
928             return "unrecognised character in game specification";
929     }
930
931     if (desc[-1] == ',') {
932         /*
933          * Optional extra piece of game description which fills in
934          * some grid squares as extra clues.
935          */
936         i = 0;
937         while (i < params->w * params->h) {
938             int c = (unsigned char)*desc++;
939             if ((c >= 'a' && c <= 'z') ||
940                 (c >= 'A' && c <= 'Z')) {
941                 int len = tolower(c) - 'a';
942                 i += len;
943                 if (len < 25 && i < params->w*params->h)
944                     i++;
945                 if (i > params->w * params->h) {
946                     return "too much data in clue-squares section";
947                 }
948             } else if (!c) {
949                 return "too little data in clue-squares section";
950             } else {
951                 return "unrecognised character in clue-squares section";
952             }
953         }
954         if (*desc) {
955             return "too much data in clue-squares section";
956         }
957     }
958
959     return NULL;
960 }
961
962 static game_state *new_game(midend *me, const game_params *params,
963                             const char *desc)
964 {
965     int i;
966     const char *p;
967     game_state *state = snew(game_state);
968
969     state->common = snew(game_state_common);
970     state->common->refcount = 1;
971
972     state->common->w = params->w;
973     state->common->h = params->h;
974
975     state->grid = snewn(state->common->w * state->common->h, unsigned char);
976     memset(state->grid, GRID_UNKNOWN, state->common->w * state->common->h);
977
978     state->common->immutable = snewn(state->common->w * state->common->h,
979                                      unsigned char);
980     memset(state->common->immutable, 0, state->common->w * state->common->h);
981
982     state->common->rowsize = max(state->common->w, state->common->h);
983     state->common->rowdata = snewn(state->common->rowsize * (state->common->w + state->common->h), int);
984     state->common->rowlen = snewn(state->common->w + state->common->h, int);
985
986     state->completed = state->cheated = FALSE;
987
988     for (i = 0; i < params->w + params->h; i++) {
989         state->common->rowlen[i] = 0;
990         if (*desc && isdigit((unsigned char)*desc)) {
991             do {
992                 p = desc;
993                 while (*desc && isdigit((unsigned char)*desc)) desc++;
994                 state->common->rowdata[state->common->rowsize * i + state->common->rowlen[i]++] =
995                     atoi(p);
996             } while (*desc++ == '.');
997         } else {
998             desc++;                    /* expect a slash immediately */
999         }
1000     }
1001
1002     if (desc[-1] == ',') {
1003         /*
1004          * Optional extra piece of game description which fills in
1005          * some grid squares as extra clues.
1006          */
1007         i = 0;
1008         while (i < params->w * params->h) {
1009             int c = (unsigned char)*desc++;
1010             int full = isupper(c), len = tolower(c) - 'a';
1011             i += len;
1012             if (len < 25 && i < params->w*params->h) {
1013                 state->grid[i] = full ? GRID_FULL : GRID_EMPTY;
1014                 state->common->immutable[i] = TRUE;
1015                 i++;
1016             }
1017         }
1018     }
1019
1020     return state;
1021 }
1022
1023 static game_state *dup_game(const game_state *state)
1024 {
1025     game_state *ret = snew(game_state);
1026
1027     ret->common = state->common;
1028     ret->common->refcount++;
1029
1030     ret->grid = snewn(ret->common->w * ret->common->h, unsigned char);
1031     memcpy(ret->grid, state->grid, ret->common->w * ret->common->h);
1032
1033     ret->completed = state->completed;
1034     ret->cheated = state->cheated;
1035
1036     return ret;
1037 }
1038
1039 static void free_game(game_state *state)
1040 {
1041     if (--state->common->refcount == 0) {
1042         sfree(state->common->rowdata);
1043         sfree(state->common->rowlen);
1044         sfree(state->common->immutable);
1045         sfree(state->common);
1046     }
1047     sfree(state->grid);
1048     sfree(state);
1049 }
1050
1051 static char *solve_game(const game_state *state, const game_state *currstate,
1052                         const char *ai, char **error)
1053 {
1054     unsigned char *matrix;
1055     int w = state->common->w, h = state->common->h;
1056     int i;
1057     char *ret;
1058     int max, ok;
1059     unsigned char *workspace;
1060     unsigned int *changed_h, *changed_w;
1061     int *rowdata;
1062
1063     /*
1064      * If we already have the solved state in ai, copy it out.
1065      */
1066     if (ai)
1067         return dupstr(ai);
1068
1069     max = max(w, h);
1070     matrix = snewn(w*h, unsigned char);
1071     workspace = snewn(max*7, unsigned char);
1072     changed_h = snewn(max+1, unsigned int);
1073     changed_w = snewn(max+1, unsigned int);
1074     rowdata = snewn(max+1, int);
1075
1076     ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
1077                       changed_h, changed_w, rowdata, 0);
1078
1079     sfree(workspace);
1080     sfree(changed_h);
1081     sfree(changed_w);
1082     sfree(rowdata);
1083
1084     if (!ok) {
1085         sfree(matrix);
1086         *error = "Solving algorithm cannot complete this puzzle";
1087         return NULL;
1088     }
1089
1090     ret = snewn(w*h+2, char);
1091     ret[0] = 'S';
1092     for (i = 0; i < w*h; i++) {
1093         assert(matrix[i] == BLOCK || matrix[i] == DOT);
1094         ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
1095     }
1096     ret[w*h+1] = '\0';
1097
1098     sfree(matrix);
1099
1100     return ret;
1101 }
1102
1103 static int game_can_format_as_text_now(const game_params *params)
1104 {
1105     return TRUE;
1106 }
1107
1108 static char *game_text_format(const game_state *state)
1109 {
1110     int w = state->common->w, h = state->common->h, i, j;
1111     int left_gap = 0, top_gap = 0, ch = 2, cw = 1, limit = 1;
1112
1113     int len, topleft, lw, lh, gw, gh; /* {line,grid}_{width,height} */
1114     char *board, *buf;
1115
1116     for (i = 0; i < w; ++i) {
1117         top_gap = max(top_gap, state->common->rowlen[i]);
1118         for (j = 0; j < state->common->rowlen[i]; ++j)
1119             while (state->common->rowdata[i*state->common->rowsize + j] >= limit) {
1120                 ++cw;
1121                 limit *= 10;
1122             }
1123     }
1124     for (i = 0; i < h; ++i) {
1125         int rowlen = 0, predecessors = FALSE;
1126         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1127             int copy = state->common->rowdata[(i+w)*state->common->rowsize + j];
1128             rowlen += predecessors;
1129             predecessors = TRUE;
1130             do ++rowlen; while (copy /= 10);
1131         }
1132         left_gap = max(left_gap, rowlen);
1133     }
1134
1135     cw = max(cw, 3);
1136
1137     gw = w*cw + 2;
1138     gh = h*ch + 1;
1139     lw = gw + left_gap;
1140     lh = gh + top_gap;
1141     len = lw * lh;
1142     topleft = lw * top_gap + left_gap;
1143
1144     board = snewn(len + 1, char);
1145     sprintf(board, "%*s\n", len - 2, "");
1146
1147     for (i = 0; i < lh; ++i) {
1148         board[lw - 1 + i*lw] = '\n';
1149         if (i < top_gap) continue;
1150         board[lw - 2 + i*lw] = ((i - top_gap) % ch ? '|' : '+');
1151     }
1152
1153     for (i = 0; i < w; ++i) {
1154         for (j = 0; j < state->common->rowlen[i]; ++j) {
1155             int cell = topleft + i*cw + 1 + lw*(j - state->common->rowlen[i]);
1156             int nch = sprintf(board + cell, "%*d", cw - 1,
1157                               state->common->rowdata[i*state->common->rowsize + j]);
1158             board[cell + nch] = ' '; /* de-NUL-ify */
1159         }
1160     }
1161
1162     buf = snewn(left_gap, char);
1163     for (i = 0; i < h; ++i) {
1164         char *p = buf, *start = board + top_gap*lw + left_gap + (i*ch+1)*lw;
1165         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1166             if (p > buf) *p++ = ' ';
1167             p += sprintf(p, "%d", state->common->rowdata[(i+w)*state->common->rowsize + j]);
1168         }
1169         memcpy(start - (p - buf), buf, p - buf);
1170     }
1171
1172     for (i = 0; i < w; ++i) {
1173         for (j = 0; j < h; ++j) {
1174             int cell = topleft + i*cw + j*ch*lw;
1175             int center = cell + cw/2 + (ch/2)*lw;
1176             int dx, dy;
1177             board[cell] = 0 ? center : '+';
1178             for (dx = 1; dx < cw; ++dx) board[cell + dx] = '-';
1179             for (dy = 1; dy < ch; ++dy) board[cell + dy*lw] = '|';
1180             if (state->grid[i*w+j] == GRID_UNKNOWN) continue;
1181             for (dx = 1; dx < cw; ++dx)
1182                 for (dy = 1; dy < ch; ++dy)
1183                     board[cell + dx + dy*lw] =
1184                         state->grid[i*w+j] == GRID_FULL ? '#' : '.';
1185         }
1186     }
1187
1188     memcpy(board + topleft + h*ch*lw, board + topleft, gw - 1);
1189
1190     sfree(buf);
1191
1192     return board;
1193 }
1194
1195 struct game_ui {
1196     int dragging;
1197     int drag_start_x;
1198     int drag_start_y;
1199     int drag_end_x;
1200     int drag_end_y;
1201     int drag, release, state;
1202     int cur_x, cur_y, cur_visible;
1203 };
1204
1205 static game_ui *new_ui(const game_state *state)
1206 {
1207     game_ui *ret;
1208
1209     ret = snew(game_ui);
1210     ret->dragging = FALSE;
1211     ret->cur_x = ret->cur_y = ret->cur_visible = 0;
1212
1213     return ret;
1214 }
1215
1216 static void free_ui(game_ui *ui)
1217 {
1218     sfree(ui);
1219 }
1220
1221 static char *encode_ui(const game_ui *ui)
1222 {
1223     return NULL;
1224 }
1225
1226 static void decode_ui(game_ui *ui, const char *encoding)
1227 {
1228 }
1229
1230 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1231                                const game_state *newstate)
1232 {
1233 }
1234
1235 struct game_drawstate {
1236     int started;
1237     int w, h;
1238     int tilesize;
1239     unsigned char *visible, *numcolours;
1240     int cur_x, cur_y;
1241 };
1242
1243 static char *interpret_move(const game_state *state, game_ui *ui,
1244                             const game_drawstate *ds,
1245                             int x, int y, int button)
1246 {
1247     int control = button & MOD_CTRL, shift = button & MOD_SHFT;
1248     button &= ~MOD_MASK;
1249
1250     x = FROMCOORD(state->common->w, x);
1251     y = FROMCOORD(state->common->h, y);
1252
1253     if (x >= 0 && x < state->common->w && y >= 0 && y < state->common->h &&
1254         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
1255          button == MIDDLE_BUTTON)) {
1256 #ifdef STYLUS_BASED
1257         int currstate = state->grid[y * state->common->w + x];
1258 #endif
1259
1260         ui->dragging = TRUE;
1261
1262         if (button == LEFT_BUTTON) {
1263             ui->drag = LEFT_DRAG;
1264             ui->release = LEFT_RELEASE;
1265 #ifdef STYLUS_BASED
1266             ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
1267 #else
1268             ui->state = GRID_FULL;
1269 #endif
1270         } else if (button == RIGHT_BUTTON) {
1271             ui->drag = RIGHT_DRAG;
1272             ui->release = RIGHT_RELEASE;
1273 #ifdef STYLUS_BASED
1274             ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1275 #else
1276             ui->state = GRID_EMPTY;
1277 #endif
1278         } else /* if (button == MIDDLE_BUTTON) */ {
1279             ui->drag = MIDDLE_DRAG;
1280             ui->release = MIDDLE_RELEASE;
1281             ui->state = GRID_UNKNOWN;
1282         }
1283
1284         ui->drag_start_x = ui->drag_end_x = x;
1285         ui->drag_start_y = ui->drag_end_y = y;
1286         ui->cur_visible = 0;
1287
1288         return "";                     /* UI activity occurred */
1289     }
1290
1291     if (ui->dragging && button == ui->drag) {
1292         /*
1293          * There doesn't seem much point in allowing a rectangle
1294          * drag; people will generally only want to drag a single
1295          * horizontal or vertical line, so we make that easy by
1296          * snapping to it.
1297          * 
1298          * Exception: if we're _middle_-button dragging to tag
1299          * things as UNKNOWN, we may well want to trash an entire
1300          * area and start over!
1301          */
1302         if (ui->state != GRID_UNKNOWN) {
1303             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1304                 y = ui->drag_start_y;
1305             else
1306                 x = ui->drag_start_x;
1307         }
1308
1309         if (x < 0) x = 0;
1310         if (y < 0) y = 0;
1311         if (x >= state->common->w) x = state->common->w - 1;
1312         if (y >= state->common->h) y = state->common->h - 1;
1313
1314         ui->drag_end_x = x;
1315         ui->drag_end_y = y;
1316
1317         return "";                     /* UI activity occurred */
1318     }
1319
1320     if (ui->dragging && button == ui->release) {
1321         int x1, x2, y1, y2, xx, yy;
1322         int move_needed = FALSE;
1323
1324         x1 = min(ui->drag_start_x, ui->drag_end_x);
1325         x2 = max(ui->drag_start_x, ui->drag_end_x);
1326         y1 = min(ui->drag_start_y, ui->drag_end_y);
1327         y2 = max(ui->drag_start_y, ui->drag_end_y);
1328
1329         for (yy = y1; yy <= y2; yy++)
1330             for (xx = x1; xx <= x2; xx++)
1331                 if (!state->common->immutable[yy * state->common->w + xx] &&
1332                     state->grid[yy * state->common->w + xx] != ui->state)
1333                     move_needed = TRUE;
1334
1335         ui->dragging = FALSE;
1336
1337         if (move_needed) {
1338             char buf[80];
1339             sprintf(buf, "%c%d,%d,%d,%d",
1340                     (char)(ui->state == GRID_FULL ? 'F' :
1341                            ui->state == GRID_EMPTY ? 'E' : 'U'),
1342                     x1, y1, x2-x1+1, y2-y1+1);
1343             return dupstr(buf);
1344         } else
1345             return "";                 /* UI activity occurred */
1346     }
1347
1348     if (IS_CURSOR_MOVE(button)) {
1349         int x = ui->cur_x, y = ui->cur_y, newstate;
1350         char buf[80];
1351         move_cursor(button, &ui->cur_x, &ui->cur_y, state->common->w, state->common->h, 0);
1352         ui->cur_visible = 1;
1353         if (!control && !shift) return "";
1354
1355         newstate = control ? shift ? GRID_UNKNOWN : GRID_FULL : GRID_EMPTY;
1356         if (state->grid[y * state->common->w + x] == newstate &&
1357             state->grid[ui->cur_y * state->common->w + ui->cur_x] == newstate)
1358             return "";
1359
1360         sprintf(buf, "%c%d,%d,%d,%d", control ? shift ? 'U' : 'F' : 'E',
1361                 min(x, ui->cur_x), min(y, ui->cur_y),
1362                 abs(x - ui->cur_x) + 1, abs(y - ui->cur_y) + 1);
1363         return dupstr(buf);
1364     }
1365
1366     if (IS_CURSOR_SELECT(button)) {
1367         int currstate = state->grid[ui->cur_y * state->common->w + ui->cur_x];
1368         int newstate;
1369         char buf[80];
1370
1371         if (!ui->cur_visible) {
1372             ui->cur_visible = 1;
1373             return "";
1374         }
1375
1376         if (button == CURSOR_SELECT2)
1377             newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1378                 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1379         else
1380             newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1381                 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1382
1383         sprintf(buf, "%c%d,%d,%d,%d",
1384                 (char)(newstate == GRID_FULL ? 'F' :
1385                        newstate == GRID_EMPTY ? 'E' : 'U'),
1386                 ui->cur_x, ui->cur_y, 1, 1);
1387         return dupstr(buf);
1388     }
1389
1390     return NULL;
1391 }
1392
1393 static game_state *execute_move(const game_state *from, const char *move)
1394 {
1395     game_state *ret;
1396     int x1, x2, y1, y2, xx, yy;
1397     int val;
1398
1399     if (move[0] == 'S' &&
1400         strlen(move) == from->common->w * from->common->h + 1) {
1401         int i;
1402
1403         ret = dup_game(from);
1404
1405         for (i = 0; i < ret->common->w * ret->common->h; i++)
1406             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1407
1408         ret->completed = ret->cheated = TRUE;
1409
1410         return ret;
1411     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1412         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1413         x1 >= 0 && x2 >= 0 && x1+x2 <= from->common->w &&
1414         y1 >= 0 && y2 >= 0 && y1+y2 <= from->common->h) {
1415
1416         x2 += x1;
1417         y2 += y1;
1418         val = (move[0] == 'F' ? GRID_FULL :
1419                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1420
1421         ret = dup_game(from);
1422         for (yy = y1; yy < y2; yy++)
1423             for (xx = x1; xx < x2; xx++)
1424                 if (!ret->common->immutable[yy * ret->common->w + xx])
1425                     ret->grid[yy * ret->common->w + xx] = val;
1426
1427         /*
1428          * An actual change, so check to see if we've completed the
1429          * game.
1430          */
1431         if (!ret->completed) {
1432             int *rowdata = snewn(ret->common->rowsize, int);
1433             int i, len;
1434
1435             ret->completed = TRUE;
1436
1437             for (i=0; i<ret->common->w; i++) {
1438                 len = compute_rowdata(rowdata, ret->grid+i,
1439                                       ret->common->h, ret->common->w);
1440                 if (len != ret->common->rowlen[i] ||
1441                     memcmp(ret->common->rowdata+i*ret->common->rowsize,
1442                            rowdata, len * sizeof(int))) {
1443                     ret->completed = FALSE;
1444                     break;
1445                 }
1446             }
1447             for (i=0; i<ret->common->h; i++) {
1448                 len = compute_rowdata(rowdata, ret->grid+i*ret->common->w,
1449                                       ret->common->w, 1);
1450                 if (len != ret->common->rowlen[i+ret->common->w] ||
1451                     memcmp(ret->common->rowdata +
1452                            (i+ret->common->w)*ret->common->rowsize,
1453                            rowdata, len * sizeof(int))) {
1454                     ret->completed = FALSE;
1455                     break;
1456                 }
1457             }
1458
1459             sfree(rowdata);
1460         }
1461
1462         return ret;
1463     } else
1464         return NULL;
1465 }
1466
1467 /* ----------------------------------------------------------------------
1468  * Error-checking during gameplay.
1469  */
1470
1471 /*
1472  * The difficulty in error-checking Pattern is to make the error check
1473  * _weak_ enough. The most obvious way would be to check each row and
1474  * column by calling (a modified form of) do_row() to recursively
1475  * analyse the row contents against the clue set and see if the
1476  * GRID_UNKNOWNs could be filled in in any way that would end up
1477  * correct. However, this turns out to be such a strong error check as
1478  * to constitute a spoiler in many situations: you make a typo while
1479  * trying to fill in one row, and not only does the row light up to
1480  * indicate an error, but several columns crossed by the move also
1481  * light up and draw your attention to deductions you hadn't even
1482  * noticed you could make.
1483  *
1484  * So instead I restrict error-checking to 'complete runs' within a
1485  * row, by which I mean contiguous sequences of GRID_FULL bounded at
1486  * both ends by either GRID_EMPTY or the ends of the row. We identify
1487  * all the complete runs in a row, and verify that _those_ are
1488  * consistent with the row's clue list. Sequences of complete runs
1489  * separated by solid GRID_EMPTY are required to match contiguous
1490  * sequences in the clue list, whereas if there's at least one
1491  * GRID_UNKNOWN between any two complete runs then those two need not
1492  * be contiguous in the clue list.
1493  *
1494  * To simplify the edge cases, I pretend that the clue list for the
1495  * row is extended with a 0 at each end, and I also pretend that the
1496  * grid data for the row is extended with a GRID_EMPTY and a
1497  * zero-length run at each end. This permits the contiguity checker to
1498  * handle the fiddly end effects (e.g. if the first contiguous
1499  * sequence of complete runs in the grid matches _something_ in the
1500  * clue list but not at the beginning, this is allowable iff there's a
1501  * GRID_UNKNOWN before the first one) with minimal faff, since the end
1502  * effects just drop out as special cases of the normal inter-run
1503  * handling (in this code the above case is not 'at the end of the
1504  * clue list' at all, but between the implicit initial zero run and
1505  * the first nonzero one).
1506  *
1507  * We must also be a little careful about how we search for a
1508  * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1509  * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1510  * for 1 in the clue list and find it at the very beginning. But now
1511  * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1512  * can't naively look at the next clue from the 1 we found, because
1513  * that'll be the second 1 and won't match. Instead, we must backtrack
1514  * by observing that the 2 we've just found must be contiguous with
1515  * the 1 we've already seen, so we search for the sequence (1 2) and
1516  * find it starting at the second 1. Now if we see a 3, we must
1517  * rethink again and search for (1 2 3).
1518  */
1519
1520 struct errcheck_state {
1521     /*
1522      * rowdata and rowlen point at the clue data for this row in the
1523      * game state.
1524      */
1525     int *rowdata;
1526     int rowlen;
1527     /*
1528      * rowpos indicates the lowest position where it would be valid to
1529      * see our next run length. It might be equal to rowlen,
1530      * indicating that the next run would have to be the terminating 0.
1531      */
1532     int rowpos;
1533     /*
1534      * ncontig indicates how many runs we've seen in a contiguous
1535      * block. This is taken into account when searching for the next
1536      * run we find, unless ncontig is zeroed out first by encountering
1537      * a GRID_UNKNOWN.
1538      */
1539     int ncontig;
1540 };
1541
1542 static int errcheck_found_run(struct errcheck_state *es, int r)
1543 {
1544 /* Macro to handle the pretence that rowdata has a 0 at each end */
1545 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1546
1547     /*
1548      * See if we can find this new run length at a position where it
1549      * also matches the last 'ncontig' runs we've seen.
1550      */
1551     int i, newpos;
1552     for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1553
1554         if (ROWDATA(newpos) != r)
1555             goto notfound;
1556
1557         for (i = 1; i <= es->ncontig; i++)
1558             if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1559                 goto notfound;
1560
1561         es->rowpos = newpos+1;
1562         es->ncontig++;
1563         return TRUE;
1564
1565       notfound:;
1566     }
1567
1568     return FALSE;
1569
1570 #undef ROWDATA
1571 }
1572
1573 static int check_errors(const game_state *state, int i)
1574 {
1575     int start, step, end, j;
1576     int val, runlen;
1577     struct errcheck_state aes, *es = &aes;
1578
1579     es->rowlen = state->common->rowlen[i];
1580     es->rowdata = state->common->rowdata + state->common->rowsize * i;
1581     /* Pretend that we've already encountered the initial zero run */
1582     es->ncontig = 1;
1583     es->rowpos = 0;
1584
1585     if (i < state->common->w) {
1586         start = i;
1587         step = state->common->w;
1588         end = start + step * state->common->h;
1589     } else {
1590         start = (i - state->common->w) * state->common->w;
1591         step = 1;
1592         end = start + step * state->common->w;
1593     }
1594
1595     runlen = -1;
1596     for (j = start - step; j <= end; j += step) {
1597         if (j < start || j == end)
1598             val = GRID_EMPTY;
1599         else
1600             val = state->grid[j];
1601
1602         if (val == GRID_UNKNOWN) {
1603             runlen = -1;
1604             es->ncontig = 0;
1605         } else if (val == GRID_FULL) {
1606             if (runlen >= 0)
1607                 runlen++;
1608         } else if (val == GRID_EMPTY) {
1609             if (runlen > 0) {
1610                 if (!errcheck_found_run(es, runlen))
1611                     return TRUE;       /* error! */
1612             }
1613             runlen = 0;
1614         }
1615     }
1616
1617     /* Signal end-of-row by sending errcheck_found_run the terminating
1618      * zero run, which will be marked as contiguous with the previous
1619      * run if and only if there hasn't been a GRID_UNKNOWN before. */
1620     if (!errcheck_found_run(es, 0))
1621         return TRUE;                   /* error at the last minute! */
1622
1623     return FALSE;                      /* no error */
1624 }
1625
1626 /* ----------------------------------------------------------------------
1627  * Drawing routines.
1628  */
1629
1630 static void game_compute_size(const game_params *params, int tilesize,
1631                               int *x, int *y)
1632 {
1633     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1634     struct { int tilesize; } ads, *ds = &ads;
1635     ads.tilesize = tilesize;
1636
1637     *x = SIZE(params->w);
1638     *y = SIZE(params->h);
1639 }
1640
1641 static void game_set_size(drawing *dr, game_drawstate *ds,
1642                           const game_params *params, int tilesize)
1643 {
1644     ds->tilesize = tilesize;
1645 }
1646
1647 static float *game_colours(frontend *fe, int *ncolours)
1648 {
1649     float *ret = snewn(3 * NCOLOURS, float);
1650     int i;
1651
1652     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1653
1654     for (i = 0; i < 3; i++) {
1655         ret[COL_GRID    * 3 + i] = 0.3F;
1656         ret[COL_UNKNOWN * 3 + i] = 0.5F;
1657         ret[COL_TEXT    * 3 + i] = 0.0F;
1658         ret[COL_FULL    * 3 + i] = 0.0F;
1659         ret[COL_EMPTY   * 3 + i] = 1.0F;
1660     }
1661     ret[COL_CURSOR * 3 + 0] = 1.0F;
1662     ret[COL_CURSOR * 3 + 1] = 0.25F;
1663     ret[COL_CURSOR * 3 + 2] = 0.25F;
1664     ret[COL_ERROR * 3 + 0] = 1.0F;
1665     ret[COL_ERROR * 3 + 1] = 0.0F;
1666     ret[COL_ERROR * 3 + 2] = 0.0F;
1667
1668     *ncolours = NCOLOURS;
1669     return ret;
1670 }
1671
1672 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1673 {
1674     struct game_drawstate *ds = snew(struct game_drawstate);
1675
1676     ds->started = FALSE;
1677     ds->w = state->common->w;
1678     ds->h = state->common->h;
1679     ds->visible = snewn(ds->w * ds->h, unsigned char);
1680     ds->tilesize = 0;                  /* not decided yet */
1681     memset(ds->visible, 255, ds->w * ds->h);
1682     ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1683     memset(ds->numcolours, 255, ds->w + ds->h);
1684     ds->cur_x = ds->cur_y = 0;
1685
1686     return ds;
1687 }
1688
1689 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1690 {
1691     sfree(ds->visible);
1692     sfree(ds);
1693 }
1694
1695 static void grid_square(drawing *dr, game_drawstate *ds,
1696                         int y, int x, int state, int cur)
1697 {
1698     int xl, xr, yt, yb, dx, dy, dw, dh;
1699
1700     draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1701               TILE_SIZE, TILE_SIZE, COL_GRID);
1702
1703     xl = (x % 5 == 0 ? 1 : 0);
1704     yt = (y % 5 == 0 ? 1 : 0);
1705     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1706     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1707
1708     dx = TOCOORD(ds->w, x) + 1 + xl;
1709     dy = TOCOORD(ds->h, y) + 1 + yt;
1710     dw = TILE_SIZE - xl - xr - 1;
1711     dh = TILE_SIZE - yt - yb - 1;
1712
1713     draw_rect(dr, dx, dy, dw, dh,
1714               (state == GRID_FULL ? COL_FULL :
1715                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1716     if (cur) {
1717         draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1718         draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1719     }
1720
1721     draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1722                 TILE_SIZE, TILE_SIZE);
1723 }
1724
1725 /*
1726  * Draw the numbers for a single row or column.
1727  */
1728 static void draw_numbers(drawing *dr, game_drawstate *ds,
1729                          const game_state *state, int i, int erase, int colour)
1730 {
1731     int rowlen = state->common->rowlen[i];
1732     int *rowdata = state->common->rowdata + state->common->rowsize * i;
1733     int nfit;
1734     int j;
1735
1736     if (erase) {
1737         if (i < state->common->w) {
1738             draw_rect(dr, TOCOORD(state->common->w, i), 0,
1739                       TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE,
1740                       COL_BACKGROUND);
1741         } else {
1742             draw_rect(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1743                       BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE,
1744                       COL_BACKGROUND);
1745         }
1746     }
1747
1748     /*
1749      * Normally I space the numbers out by the same distance as the
1750      * tile size. However, if there are more numbers than available
1751      * spaces, I have to squash them up a bit.
1752      */
1753     if (i < state->common->w)
1754         nfit = TLBORDER(state->common->h);
1755     else
1756         nfit = TLBORDER(state->common->w);
1757     nfit = max(rowlen, nfit) - 1;
1758     assert(nfit > 0);
1759
1760     for (j = 0; j < rowlen; j++) {
1761         int x, y;
1762         char str[80];
1763
1764         if (i < state->common->w) {
1765             x = TOCOORD(state->common->w, i);
1766             y = BORDER + TILE_SIZE * (TLBORDER(state->common->h)-1);
1767             y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->h)-1) / nfit;
1768         } else {
1769             y = TOCOORD(state->common->h, i - state->common->w);
1770             x = BORDER + TILE_SIZE * (TLBORDER(state->common->w)-1);
1771             x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->w)-1) / nfit;
1772         }
1773
1774         sprintf(str, "%d", rowdata[j]);
1775         draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1776                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1777     }
1778
1779     if (i < state->common->w) {
1780         draw_update(dr, TOCOORD(state->common->w, i), 0,
1781                     TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE);
1782     } else {
1783         draw_update(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1784                     BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE);
1785     }
1786 }
1787
1788 static void game_redraw(drawing *dr, game_drawstate *ds,
1789                         const game_state *oldstate, const game_state *state,
1790                         int dir, const game_ui *ui,
1791                         float animtime, float flashtime)
1792 {
1793     int i, j;
1794     int x1, x2, y1, y2;
1795     int cx, cy, cmoved;
1796
1797     if (!ds->started) {
1798         /*
1799          * The initial contents of the window are not guaranteed
1800          * and can vary with front ends. To be on the safe side,
1801          * all games should start by drawing a big background-
1802          * colour rectangle covering the whole window.
1803          */
1804         draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1805
1806         /*
1807          * Draw the grid outline.
1808          */
1809         draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1810                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1811                   COL_GRID);
1812
1813         ds->started = TRUE;
1814
1815         draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1816     }
1817
1818     if (ui->dragging) {
1819         x1 = min(ui->drag_start_x, ui->drag_end_x);
1820         x2 = max(ui->drag_start_x, ui->drag_end_x);
1821         y1 = min(ui->drag_start_y, ui->drag_end_y);
1822         y2 = max(ui->drag_start_y, ui->drag_end_y);
1823     } else {
1824         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1825     }
1826
1827     if (ui->cur_visible) {
1828         cx = ui->cur_x; cy = ui->cur_y;
1829     } else {
1830         cx = cy = -1;
1831     }
1832     cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1833
1834     /*
1835      * Now draw any grid squares which have changed since last
1836      * redraw.
1837      */
1838     for (i = 0; i < ds->h; i++) {
1839         for (j = 0; j < ds->w; j++) {
1840             int val, cc = 0;
1841
1842             /*
1843              * Work out what state this square should be drawn in,
1844              * taking any current drag operation into account.
1845              */
1846             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2 &&
1847                 !state->common->immutable[i * state->common->w + j])
1848                 val = ui->state;
1849             else
1850                 val = state->grid[i * state->common->w + j];
1851
1852             if (cmoved) {
1853                 /* the cursor has moved; if we were the old or
1854                  * the new cursor position we need to redraw. */
1855                 if (j == cx && i == cy) cc = 1;
1856                 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1857             }
1858
1859             /*
1860              * Briefly invert everything twice during a completion
1861              * flash.
1862              */
1863             if (flashtime > 0 &&
1864                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1865                 val != GRID_UNKNOWN)
1866                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1867
1868             if (ds->visible[i * ds->w + j] != val || cc) {
1869                 grid_square(dr, ds, i, j, val,
1870                             (j == cx && i == cy));
1871                 ds->visible[i * ds->w + j] = val;
1872             }
1873         }
1874     }
1875     ds->cur_x = cx; ds->cur_y = cy;
1876
1877     /*
1878      * Redraw any numbers which have changed their colour due to error
1879      * indication.
1880      */
1881     for (i = 0; i < state->common->w + state->common->h; i++) {
1882         int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1883         if (ds->numcolours[i] != colour) {
1884             draw_numbers(dr, ds, state, i, TRUE, colour);
1885             ds->numcolours[i] = colour;
1886         }
1887     }
1888 }
1889
1890 static float game_anim_length(const game_state *oldstate,
1891                               const game_state *newstate, int dir, game_ui *ui)
1892 {
1893     return 0.0F;
1894 }
1895
1896 static float game_flash_length(const game_state *oldstate,
1897                                const game_state *newstate, int dir, game_ui *ui)
1898 {
1899     if (!oldstate->completed && newstate->completed &&
1900         !oldstate->cheated && !newstate->cheated)
1901         return FLASH_TIME;
1902     return 0.0F;
1903 }
1904
1905 static int game_status(const game_state *state)
1906 {
1907     return state->completed ? +1 : 0;
1908 }
1909
1910 static int game_timing_state(const game_state *state, game_ui *ui)
1911 {
1912     return TRUE;
1913 }
1914
1915 static void game_print_size(const game_params *params, float *x, float *y)
1916 {
1917     int pw, ph;
1918
1919     /*
1920      * I'll use 5mm squares by default.
1921      */
1922     game_compute_size(params, 500, &pw, &ph);
1923     *x = pw / 100.0F;
1924     *y = ph / 100.0F;
1925 }
1926
1927 static void game_print(drawing *dr, const game_state *state, int tilesize)
1928 {
1929     int w = state->common->w, h = state->common->h;
1930     int ink = print_mono_colour(dr, 0);
1931     int x, y, i;
1932
1933     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1934     game_drawstate ads, *ds = &ads;
1935     game_set_size(dr, ds, NULL, tilesize);
1936
1937     /*
1938      * Border.
1939      */
1940     print_line_width(dr, TILE_SIZE / 16);
1941     draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1942                       w*TILE_SIZE, h*TILE_SIZE, ink);
1943
1944     /*
1945      * Grid.
1946      */
1947     for (x = 1; x < w; x++) {
1948         print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1949         draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1950                   TOCOORD(w, x), TOCOORD(h, h), ink);
1951     }
1952     for (y = 1; y < h; y++) {
1953         print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1954         draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1955                   TOCOORD(w, w), TOCOORD(h, y), ink);
1956     }
1957
1958     /*
1959      * Clues.
1960      */
1961     for (i = 0; i < state->common->w + state->common->h; i++)
1962         draw_numbers(dr, ds, state, i, FALSE, ink);
1963
1964     /*
1965      * Solution.
1966      */
1967     print_line_width(dr, TILE_SIZE / 128);
1968     for (y = 0; y < h; y++)
1969         for (x = 0; x < w; x++) {
1970             if (state->grid[y*w+x] == GRID_FULL)
1971                 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1972                           TILE_SIZE, TILE_SIZE, ink);
1973             else if (state->grid[y*w+x] == GRID_EMPTY)
1974                 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1975                             TOCOORD(h, y) + TILE_SIZE/2,
1976                             TILE_SIZE/12, ink, ink);
1977         }
1978 }
1979
1980 #ifdef COMBINED
1981 #define thegame pattern
1982 #endif
1983
1984 const struct game thegame = {
1985     "Pattern", "games.pattern", "pattern",
1986     default_params,
1987     game_fetch_preset, NULL,
1988     decode_params,
1989     encode_params,
1990     free_params,
1991     dup_params,
1992     TRUE, game_configure, custom_params,
1993     validate_params,
1994     new_game_desc,
1995     validate_desc,
1996     new_game,
1997     dup_game,
1998     free_game,
1999     TRUE, solve_game,
2000     TRUE, game_can_format_as_text_now, game_text_format,
2001     new_ui,
2002     free_ui,
2003     encode_ui,
2004     decode_ui,
2005     game_changed_state,
2006     interpret_move,
2007     execute_move,
2008     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2009     game_colours,
2010     game_new_drawstate,
2011     game_free_drawstate,
2012     game_redraw,
2013     game_anim_length,
2014     game_flash_length,
2015     game_status,
2016     TRUE, FALSE, game_print_size, game_print,
2017     FALSE,                             /* wants_statusbar */
2018     FALSE, game_timing_state,
2019     REQUIRE_RBUTTON,                   /* flags */
2020 };
2021
2022 #ifdef STANDALONE_SOLVER
2023
2024 int main(int argc, char **argv)
2025 {
2026     game_params *p;
2027     game_state *s;
2028     char *id = NULL, *desc, *err;
2029
2030     while (--argc > 0) {
2031         char *p = *++argv;
2032         if (*p == '-') {
2033             if (!strcmp(p, "-v")) {
2034                 verbose = TRUE;
2035             } else {
2036                 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2037                 return 1;
2038             }
2039         } else {
2040             id = p;
2041         }
2042     }
2043
2044     if (!id) {
2045         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
2046         return 1;
2047     }
2048
2049     desc = strchr(id, ':');
2050     if (!desc) {
2051         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2052         return 1;
2053     }
2054     *desc++ = '\0';
2055
2056     p = default_params();
2057     decode_params(p, id);
2058     err = validate_desc(p, desc);
2059     if (err) {
2060         fprintf(stderr, "%s: %s\n", argv[0], err);
2061         return 1;
2062     }
2063     s = new_game(NULL, p, desc);
2064
2065     {
2066         int w = p->w, h = p->h, i, j, max, cluewid = 0;
2067         unsigned char *matrix, *workspace;
2068         unsigned int *changed_h, *changed_w;
2069         int *rowdata;
2070
2071         matrix = snewn(w*h, unsigned char);
2072         max = max(w, h);
2073         workspace = snewn(max*7, unsigned char);
2074         changed_h = snewn(max+1, unsigned int);
2075         changed_w = snewn(max+1, unsigned int);
2076         rowdata = snewn(max+1, int);
2077
2078         if (verbose) {
2079             int thiswid;
2080             /*
2081              * Work out the maximum text width of the clue numbers
2082              * in a row or column, so we can print the solver's
2083              * working in a nicely lined up way.
2084              */
2085             for (i = 0; i < (w+h); i++) {
2086                 char buf[80];
2087                 for (thiswid = -1, j = 0; j < s->common->rowlen[i]; j++)
2088                     thiswid += sprintf
2089                         (buf, " %d",
2090                          s->common->rowdata[s->common->rowsize*i+j]);
2091                 if (cluewid < thiswid)
2092                     cluewid = thiswid;
2093             }
2094         }
2095
2096         solve_puzzle(s, NULL, w, h, matrix, workspace,
2097                      changed_h, changed_w, rowdata, cluewid);
2098
2099         for (i = 0; i < h; i++) {
2100             for (j = 0; j < w; j++) {
2101                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
2102                          matrix[i*w+j] == BLOCK ? '#' :
2103                          matrix[i*w+j] == DOT ? '.' :
2104                          '!');
2105                 putchar(c);
2106             }
2107             printf("\n");
2108         }
2109     }
2110
2111     return 0;
2112 }
2113
2114 #endif
2115
2116 #ifdef STANDALONE_PICTURE_GENERATOR
2117
2118 /*
2119  * Main program for the standalone picture generator. To use it,
2120  * simply provide it with an XBM-format bitmap file (note XBM, not
2121  * XPM) on standard input, and it will output a game ID in return.
2122  * For example:
2123  *
2124  *   $ ./patternpicture < calligraphic-A.xbm
2125  *   15x15:2/4/2/2/2/3/3/3.1/3.1/3.1/11/14/12/6/1/2/2/3/4/5/1.3/2.3/1.3/2.3/1.4/9/1.1.3/2.2.3/5.4/3.2
2126  *
2127  * That looks easy, of course - all the program has done is to count
2128  * up the clue numbers! But in fact, it's done more than that: it's
2129  * also checked that the result is uniquely soluble from just the
2130  * numbers. If it hadn't been, then it would have also left some
2131  * filled squares in the playing area as extra clues.
2132  *
2133  *   $ ./patternpicture < cube.xbm
2134  *   15x15:10/2.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.10/1.1.1/1.1.1/1.1.1/2.1/10/10/1.2/1.1.1/1.1.1/1.1.1/10.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.2/10,TNINzzzzGNzw
2135  *
2136  * This enables a reasonably convenient design workflow for coming up
2137  * with pictorial Pattern puzzles which _are_ uniquely soluble without
2138  * those inelegant pre-filled squares. Fire up a bitmap editor (X11
2139  * bitmap(1) is good enough), save a trial .xbm, and then test it by
2140  * running a command along the lines of
2141  *
2142  *   $ ./pattern $(./patternpicture < test.xbm)
2143  *
2144  * If the resulting window pops up with some pre-filled squares, then
2145  * that tells you which parts of the image are giving rise to
2146  * ambiguities, so try making tweaks in those areas, try the test
2147  * command again, and see if it helps. Once you have a design for
2148  * which the Pattern starting grid comes out empty, there's your game
2149  * ID.
2150  */
2151
2152 #include <time.h>
2153
2154 int main(int argc, char **argv)
2155 {
2156     game_params *par;
2157     char *params, *desc;
2158     random_state *rs;
2159     time_t seed = time(NULL);
2160     char buf[4096];
2161     int i;
2162     int x, y;
2163
2164     par = default_params();
2165     if (argc > 1)
2166         decode_params(par, argv[1]);   /* get difficulty */
2167     par->w = par->h = -1;
2168
2169     /*
2170      * Now read an XBM file from standard input. This is simple and
2171      * hacky and will do very little error detection, so don't feed
2172      * it bogus data.
2173      */
2174     picture = NULL;
2175     x = y = 0;
2176     while (fgets(buf, sizeof(buf), stdin)) {
2177         buf[strcspn(buf, "\r\n")] = '\0';
2178         if (!strncmp(buf, "#define", 7)) {
2179             /*
2180              * Lines starting `#define' give the width and height.
2181              */
2182             char *num = buf + strlen(buf);
2183             char *symend;
2184
2185             while (num > buf && isdigit((unsigned char)num[-1]))
2186                 num--;
2187             symend = num;
2188             while (symend > buf && isspace((unsigned char)symend[-1]))
2189                 symend--;
2190
2191             if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
2192                 par->w = atoi(num);
2193             else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
2194                 par->h = atoi(num);
2195         } else {
2196             /*
2197              * Otherwise, break the string up into words and take
2198              * any word of the form `0x' plus hex digits to be a
2199              * byte.
2200              */
2201             char *p, *wordstart;
2202
2203             if (!picture) {
2204                 if (par->w < 0 || par->h < 0) {
2205                     printf("failed to read width and height\n");
2206                     return 1;
2207                 }
2208                 picture = snewn(par->w * par->h, unsigned char);
2209                 for (i = 0; i < par->w * par->h; i++)
2210                     picture[i] = GRID_UNKNOWN;
2211             }
2212
2213             p = buf;
2214             while (*p) {
2215                 while (*p && (*p == ',' || isspace((unsigned char)*p)))
2216                     p++;
2217                 wordstart = p;
2218                 while (*p && !(*p == ',' || *p == '}' ||
2219                                isspace((unsigned char)*p)))
2220                     p++;
2221                 if (*p)
2222                     *p++ = '\0';
2223
2224                 if (wordstart[0] == '0' &&
2225                     (wordstart[1] == 'x' || wordstart[1] == 'X') &&
2226                     !wordstart[2 + strspn(wordstart+2,
2227                                           "0123456789abcdefABCDEF")]) {
2228                     unsigned long byte = strtoul(wordstart+2, NULL, 16);
2229                     for (i = 0; i < 8; i++) {
2230                         int bit = (byte >> i) & 1;
2231                         if (y < par->h && x < par->w)
2232                             picture[y * par->w + x] =
2233                                 bit ? GRID_FULL : GRID_EMPTY;
2234                         x++;
2235                     }
2236
2237                     if (x >= par->w) {
2238                         x = 0;
2239                         y++;
2240                     }
2241                 }
2242             }
2243         }
2244     }
2245
2246     for (i = 0; i < par->w * par->h; i++)
2247         if (picture[i] == GRID_UNKNOWN) {
2248             fprintf(stderr, "failed to read enough bitmap data\n");
2249             return 1;
2250         }
2251
2252     rs = random_new((void*)&seed, sizeof(time_t));
2253
2254     desc = new_game_desc(par, rs, NULL, FALSE);
2255     params = encode_params(par, FALSE);
2256     printf("%s:%s\n", params, desc);
2257
2258     sfree(desc);
2259     sfree(params);
2260     free_params(par);
2261     random_free(rs);
2262
2263     return 0;
2264 }
2265
2266 #endif
2267
2268 /* vim: set shiftwidth=4 tabstop=8: */