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