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