chiark / gitweb /
Add 'const' to the game_params arguments in validate_desc and
[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(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(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(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(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(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(game_state *state, unsigned char *grid, int w, int h,
472                         unsigned char *matrix, unsigned char *workspace,
473                         unsigned int *changed_h, unsigned int *changed_w,
474                         int *rowdata
475 #ifdef STANDALONE_SOLVER
476                         , int cluewid
477 #else
478                         , int dummy
479 #endif
480                         )
481 {
482     int i, j, ok, max;
483     int max_h, max_w;
484
485     assert((state!=NULL) ^ (grid!=NULL));
486
487     max = max(w, h);
488
489     memset(matrix, 0, w*h);
490
491     /* For each column, compute how many squares can be deduced
492      * from just the row-data.
493      * Later, changed_* will hold how many squares were changed
494      * in every row/column in the previous iteration
495      * Changed_* is used to choose the next rows / cols to re-examine
496      */
497     for (i=0; i<h; i++) {
498         int freespace;
499         if (state) {
500             memcpy(rowdata, state->rowdata + state->rowsize*(w+i), max*sizeof(int));
501             rowdata[state->rowlen[w+i]] = 0;
502         } else {
503             rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
504         }
505         for (j=0, freespace=w+1; rowdata[j]; j++) freespace -= rowdata[j] + 1;
506         for (j=0, changed_h[i]=0; rowdata[j]; j++)
507             if (rowdata[j] > freespace)
508                 changed_h[i] += rowdata[j] - freespace;
509     }
510     for (i=0,max_h=0; i<h; i++)
511         if (changed_h[i] > max_h)
512             max_h = changed_h[i];
513     for (i=0; i<w; i++) {
514         int freespace;
515         if (state) {
516             memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
517             rowdata[state->rowlen[i]] = 0;
518         } else {
519             rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
520         }
521         for (j=0, freespace=h+1; rowdata[j]; j++) freespace -= rowdata[j] + 1;
522         for (j=0, changed_w[i]=0; rowdata[j]; j++)
523             if (rowdata[j] > freespace)
524                 changed_w[i] += rowdata[j] - freespace;
525     }
526     for (i=0,max_w=0; i<w; i++)
527         if (changed_w[i] > max_w)
528             max_w = changed_w[i];
529
530     /* Solve the puzzle.
531      * Process rows/columns individually. Deductions involving more than one
532      * row and/or column at a time are not supported.
533      * Take care to only process rows/columns which have been changed since they
534      * were previously processed.
535      * Also, prioritize rows/columns which have had the most changes since their
536      * previous processing, as they promise the greatest benefit.
537      * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
538      */
539     do {
540         for (; max_h && max_h >= max_w; max_h--) {
541             for (i=0; i<h; i++) {
542                 if (changed_h[i] >= max_h) {
543                     if (state) {
544                         memcpy(rowdata, state->rowdata + state->rowsize*(w+i), max*sizeof(int));
545                         rowdata[state->rowlen[w+i]] = 0;
546                     } else {
547                         rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
548                     }
549                     do_row(workspace, workspace+max, workspace+2*max,
550                            workspace+3*max, workspace+4*max,
551                            workspace+5*max, workspace+6*max,
552                            matrix+i*w, w, 1, rowdata, changed_w
553 #ifdef STANDALONE_SOLVER
554                            , "row", i+1, cluewid
555 #endif
556                            );
557                     changed_h[i] = 0;
558                 }
559             }
560             for (i=0,max_w=0; i<w; i++)
561                 if (changed_w[i] > max_w)
562                     max_w = changed_w[i];
563         }
564         for (; max_w && max_w >= max_h; max_w--) {
565             for (i=0; i<w; i++) {
566                 if (changed_w[i] >= max_w) {
567                     if (state) {
568                         memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
569                         rowdata[state->rowlen[i]] = 0;
570                     } else {
571                         rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 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, h, w, rowdata, changed_h
577 #ifdef STANDALONE_SOLVER
578                            , "col", i+1, cluewid
579 #endif
580                            );
581                     changed_w[i] = 0;
582                 }
583             }
584             for (i=0,max_h=0; i<h; i++)
585                 if (changed_h[i] > max_h)
586                     max_h = changed_h[i];
587         }
588     } while (max_h>0 || max_w>0);
589
590     ok = TRUE;
591     for (i=0; i<h; i++) {
592         for (j=0; j<w; j++) {
593             if (matrix[i*w+j] == UNKNOWN)
594                 ok = FALSE;
595         }
596     }
597
598     return ok;
599 }
600
601 static unsigned char *generate_soluble(random_state *rs, int w, int h)
602 {
603     int i, j, ok, ntries, max;
604     unsigned char *grid, *matrix, *workspace;
605     unsigned int *changed_h, *changed_w;
606     int *rowdata;
607
608     max = max(w, h);
609
610     grid = snewn(w*h, unsigned char);
611     /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
612     matrix = snewn(w*h, unsigned char);
613     workspace = snewn(max*7, unsigned char);
614     changed_h = snewn(max+1, unsigned int);
615     changed_w = snewn(max+1, unsigned int);
616     rowdata = snewn(max+1, int);
617
618     ntries = 0;
619
620     do {
621         ntries++;
622
623         generate(rs, w, h, grid);
624
625         /*
626          * The game is a bit too easy if any row or column is
627          * completely black or completely white. An exception is
628          * made for rows/columns that are under 3 squares,
629          * otherwise nothing will ever be successfully generated.
630          */
631         ok = TRUE;
632         if (w > 2) {
633             for (i = 0; i < h; i++) {
634                 int colours = 0;
635                 for (j = 0; j < w; j++)
636                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
637                 if (colours != 3)
638                     ok = FALSE;
639             }
640         }
641         if (h > 2) {
642             for (j = 0; j < w; j++) {
643                 int colours = 0;
644                 for (i = 0; i < h; i++)
645                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
646                 if (colours != 3)
647                     ok = FALSE;
648             }
649         }
650         if (!ok)
651             continue;
652
653         ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
654                           changed_h, changed_w, rowdata, 0);
655     } while (!ok);
656
657     sfree(matrix);
658     sfree(workspace);
659     sfree(changed_h);
660     sfree(changed_w);
661     sfree(rowdata);
662     return grid;
663 }
664
665 static char *new_game_desc(const game_params *params, random_state *rs,
666                            char **aux, int interactive)
667 {
668     unsigned char *grid;
669     int i, j, max, rowlen, *rowdata;
670     char intbuf[80], *desc;
671     int desclen, descpos;
672
673     grid = generate_soluble(rs, params->w, params->h);
674     max = max(params->w, params->h);
675     rowdata = snewn(max, int);
676
677     /*
678      * Save the solved game in aux.
679      */
680     {
681         char *ai = snewn(params->w * params->h + 2, char);
682
683         /*
684          * String format is exactly the same as a solve move, so we
685          * can just dupstr this in solve_game().
686          */
687
688         ai[0] = 'S';
689
690         for (i = 0; i < params->w * params->h; i++)
691             ai[i+1] = grid[i] ? '1' : '0';
692
693         ai[params->w * params->h + 1] = '\0';
694
695         *aux = ai;
696     }
697
698     /*
699      * Seed is a slash-separated list of row contents; each row
700      * contents section is a dot-separated list of integers. Row
701      * contents are listed in the order (columns left to right,
702      * then rows top to bottom).
703      * 
704      * Simplest way to handle memory allocation is to make two
705      * passes, first computing the seed size and then writing it
706      * out.
707      */
708     desclen = 0;
709     for (i = 0; i < params->w + params->h; i++) {
710         if (i < params->w)
711             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
712         else
713             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
714                                      params->w, 1);
715         if (rowlen > 0) {
716             for (j = 0; j < rowlen; j++) {
717                 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
718             }
719         } else {
720             desclen++;
721         }
722     }
723     desc = snewn(desclen, char);
724     descpos = 0;
725     for (i = 0; i < params->w + params->h; i++) {
726         if (i < params->w)
727             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
728         else
729             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
730                                      params->w, 1);
731         if (rowlen > 0) {
732             for (j = 0; j < rowlen; j++) {
733                 int len = sprintf(desc+descpos, "%d", rowdata[j]);
734                 if (j+1 < rowlen)
735                     desc[descpos + len] = '.';
736                 else
737                     desc[descpos + len] = '/';
738                 descpos += len+1;
739             }
740         } else {
741             desc[descpos++] = '/';
742         }
743     }
744     assert(descpos == desclen);
745     assert(desc[desclen-1] == '/');
746     desc[desclen-1] = '\0';
747     sfree(rowdata);
748     sfree(grid);
749     return desc;
750 }
751
752 static char *validate_desc(const game_params *params, char *desc)
753 {
754     int i, n, rowspace;
755     char *p;
756
757     for (i = 0; i < params->w + params->h; i++) {
758         if (i < params->w)
759             rowspace = params->h + 1;
760         else
761             rowspace = params->w + 1;
762
763         if (*desc && isdigit((unsigned char)*desc)) {
764             do {
765                 p = desc;
766                 while (*desc && isdigit((unsigned char)*desc)) desc++;
767                 n = atoi(p);
768                 rowspace -= n+1;
769
770                 if (rowspace < 0) {
771                     if (i < params->w)
772                         return "at least one column contains more numbers than will fit";
773                     else
774                         return "at least one row contains more numbers than will fit";
775                 }
776             } while (*desc++ == '.');
777         } else {
778             desc++;                    /* expect a slash immediately */
779         }
780
781         if (desc[-1] == '/') {
782             if (i+1 == params->w + params->h)
783                 return "too many row/column specifications";
784         } else if (desc[-1] == '\0') {
785             if (i+1 < params->w + params->h)
786                 return "too few row/column specifications";
787         } else
788             return "unrecognised character in game specification";
789     }
790
791     return NULL;
792 }
793
794 static game_state *new_game(midend *me, game_params *params, char *desc)
795 {
796     int i;
797     char *p;
798     game_state *state = snew(game_state);
799
800     state->w = params->w;
801     state->h = params->h;
802
803     state->grid = snewn(state->w * state->h, unsigned char);
804     memset(state->grid, GRID_UNKNOWN, state->w * state->h);
805
806     state->rowsize = max(state->w, state->h);
807     state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
808     state->rowlen = snewn(state->w + state->h, int);
809
810     state->completed = state->cheated = FALSE;
811
812     for (i = 0; i < params->w + params->h; i++) {
813         state->rowlen[i] = 0;
814         if (*desc && isdigit((unsigned char)*desc)) {
815             do {
816                 p = desc;
817                 while (*desc && isdigit((unsigned char)*desc)) desc++;
818                 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
819                     atoi(p);
820             } while (*desc++ == '.');
821         } else {
822             desc++;                    /* expect a slash immediately */
823         }
824     }
825
826     return state;
827 }
828
829 static game_state *dup_game(game_state *state)
830 {
831     game_state *ret = snew(game_state);
832
833     ret->w = state->w;
834     ret->h = state->h;
835
836     ret->grid = snewn(ret->w * ret->h, unsigned char);
837     memcpy(ret->grid, state->grid, ret->w * ret->h);
838
839     ret->rowsize = state->rowsize;
840     ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
841     ret->rowlen = snewn(ret->w + ret->h, int);
842     memcpy(ret->rowdata, state->rowdata,
843            ret->rowsize * (ret->w + ret->h) * sizeof(int));
844     memcpy(ret->rowlen, state->rowlen,
845            (ret->w + ret->h) * sizeof(int));
846
847     ret->completed = state->completed;
848     ret->cheated = state->cheated;
849
850     return ret;
851 }
852
853 static void free_game(game_state *state)
854 {
855     sfree(state->rowdata);
856     sfree(state->rowlen);
857     sfree(state->grid);
858     sfree(state);
859 }
860
861 static char *solve_game(game_state *state, game_state *currstate,
862                         char *ai, char **error)
863 {
864     unsigned char *matrix;
865     int w = state->w, h = state->h;
866     int i;
867     char *ret;
868     int max, ok;
869     unsigned char *workspace;
870     unsigned int *changed_h, *changed_w;
871     int *rowdata;
872
873     /*
874      * If we already have the solved state in ai, copy it out.
875      */
876     if (ai)
877         return dupstr(ai);
878
879     max = max(w, h);
880     matrix = snewn(w*h, unsigned char);
881     workspace = snewn(max*7, unsigned char);
882     changed_h = snewn(max+1, unsigned int);
883     changed_w = snewn(max+1, unsigned int);
884     rowdata = snewn(max+1, int);
885
886     ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
887                       changed_h, changed_w, rowdata, 0);
888
889     sfree(workspace);
890     sfree(changed_h);
891     sfree(changed_w);
892     sfree(rowdata);
893
894     if (!ok) {
895         sfree(matrix);
896         *error = "Solving algorithm cannot complete this puzzle";
897         return NULL;
898     }
899
900     ret = snewn(w*h+2, char);
901     ret[0] = 'S';
902     for (i = 0; i < w*h; i++) {
903         assert(matrix[i] == BLOCK || matrix[i] == DOT);
904         ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
905     }
906     ret[w*h+1] = '\0';
907
908     sfree(matrix);
909
910     return ret;
911 }
912
913 static int game_can_format_as_text_now(game_params *params)
914 {
915     return TRUE;
916 }
917
918 static char *game_text_format(game_state *state)
919 {
920     return NULL;
921 }
922
923 struct game_ui {
924     int dragging;
925     int drag_start_x;
926     int drag_start_y;
927     int drag_end_x;
928     int drag_end_y;
929     int drag, release, state;
930     int cur_x, cur_y, cur_visible;
931 };
932
933 static game_ui *new_ui(game_state *state)
934 {
935     game_ui *ret;
936
937     ret = snew(game_ui);
938     ret->dragging = FALSE;
939     ret->cur_x = ret->cur_y = ret->cur_visible = 0;
940
941     return ret;
942 }
943
944 static void free_ui(game_ui *ui)
945 {
946     sfree(ui);
947 }
948
949 static char *encode_ui(game_ui *ui)
950 {
951     return NULL;
952 }
953
954 static void decode_ui(game_ui *ui, char *encoding)
955 {
956 }
957
958 static void game_changed_state(game_ui *ui, game_state *oldstate,
959                                game_state *newstate)
960 {
961 }
962
963 struct game_drawstate {
964     int started;
965     int w, h;
966     int tilesize;
967     unsigned char *visible, *numcolours;
968     int cur_x, cur_y;
969 };
970
971 static char *interpret_move(game_state *state, game_ui *ui, const game_drawstate *ds,
972                             int x, int y, int button)
973 {
974     button &= ~MOD_MASK;
975
976     x = FROMCOORD(state->w, x);
977     y = FROMCOORD(state->h, y);
978
979     if (x >= 0 && x < state->w && y >= 0 && y < state->h &&
980         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
981          button == MIDDLE_BUTTON)) {
982 #ifdef STYLUS_BASED
983         int currstate = state->grid[y * state->w + x];
984 #endif
985
986         ui->dragging = TRUE;
987
988         if (button == LEFT_BUTTON) {
989             ui->drag = LEFT_DRAG;
990             ui->release = LEFT_RELEASE;
991 #ifdef STYLUS_BASED
992             ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
993 #else
994             ui->state = GRID_FULL;
995 #endif
996         } else if (button == RIGHT_BUTTON) {
997             ui->drag = RIGHT_DRAG;
998             ui->release = RIGHT_RELEASE;
999 #ifdef STYLUS_BASED
1000             ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1001 #else
1002             ui->state = GRID_EMPTY;
1003 #endif
1004         } else /* if (button == MIDDLE_BUTTON) */ {
1005             ui->drag = MIDDLE_DRAG;
1006             ui->release = MIDDLE_RELEASE;
1007             ui->state = GRID_UNKNOWN;
1008         }
1009
1010         ui->drag_start_x = ui->drag_end_x = x;
1011         ui->drag_start_y = ui->drag_end_y = y;
1012         ui->cur_visible = 0;
1013
1014         return "";                     /* UI activity occurred */
1015     }
1016
1017     if (ui->dragging && button == ui->drag) {
1018         /*
1019          * There doesn't seem much point in allowing a rectangle
1020          * drag; people will generally only want to drag a single
1021          * horizontal or vertical line, so we make that easy by
1022          * snapping to it.
1023          * 
1024          * Exception: if we're _middle_-button dragging to tag
1025          * things as UNKNOWN, we may well want to trash an entire
1026          * area and start over!
1027          */
1028         if (ui->state != GRID_UNKNOWN) {
1029             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1030                 y = ui->drag_start_y;
1031             else
1032                 x = ui->drag_start_x;
1033         }
1034
1035         if (x < 0) x = 0;
1036         if (y < 0) y = 0;
1037         if (x >= state->w) x = state->w - 1;
1038         if (y >= state->h) y = state->h - 1;
1039
1040         ui->drag_end_x = x;
1041         ui->drag_end_y = y;
1042
1043         return "";                     /* UI activity occurred */
1044     }
1045
1046     if (ui->dragging && button == ui->release) {
1047         int x1, x2, y1, y2, xx, yy;
1048         int move_needed = FALSE;
1049
1050         x1 = min(ui->drag_start_x, ui->drag_end_x);
1051         x2 = max(ui->drag_start_x, ui->drag_end_x);
1052         y1 = min(ui->drag_start_y, ui->drag_end_y);
1053         y2 = max(ui->drag_start_y, ui->drag_end_y);
1054
1055         for (yy = y1; yy <= y2; yy++)
1056             for (xx = x1; xx <= x2; xx++)
1057                 if (state->grid[yy * state->w + xx] != ui->state)
1058                     move_needed = TRUE;
1059
1060         ui->dragging = FALSE;
1061
1062         if (move_needed) {
1063             char buf[80];
1064             sprintf(buf, "%c%d,%d,%d,%d",
1065                     (char)(ui->state == GRID_FULL ? 'F' :
1066                            ui->state == GRID_EMPTY ? 'E' : 'U'),
1067                     x1, y1, x2-x1+1, y2-y1+1);
1068             return dupstr(buf);
1069         } else
1070             return "";                 /* UI activity occurred */
1071     }
1072
1073     if (IS_CURSOR_MOVE(button)) {
1074         move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, 0);
1075         ui->cur_visible = 1;
1076         return "";
1077     }
1078     if (IS_CURSOR_SELECT(button)) {
1079         int currstate = state->grid[ui->cur_y * state->w + ui->cur_x];
1080         int newstate;
1081         char buf[80];
1082
1083         if (!ui->cur_visible) {
1084             ui->cur_visible = 1;
1085             return "";
1086         }
1087
1088         if (button == CURSOR_SELECT2)
1089             newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1090                 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1091         else
1092             newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1093                 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1094
1095         sprintf(buf, "%c%d,%d,%d,%d",
1096                 (char)(newstate == GRID_FULL ? 'F' :
1097                        newstate == GRID_EMPTY ? 'E' : 'U'),
1098                 ui->cur_x, ui->cur_y, 1, 1);
1099         return dupstr(buf);
1100     }
1101
1102     return NULL;
1103 }
1104
1105 static game_state *execute_move(game_state *from, char *move)
1106 {
1107     game_state *ret;
1108     int x1, x2, y1, y2, xx, yy;
1109     int val;
1110
1111     if (move[0] == 'S' && strlen(move) == from->w * from->h + 1) {
1112         int i;
1113
1114         ret = dup_game(from);
1115
1116         for (i = 0; i < ret->w * ret->h; i++)
1117             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1118
1119         ret->completed = ret->cheated = TRUE;
1120
1121         return ret;
1122     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1123         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1124         x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
1125         y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
1126
1127         x2 += x1;
1128         y2 += y1;
1129         val = (move[0] == 'F' ? GRID_FULL :
1130                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1131
1132         ret = dup_game(from);
1133         for (yy = y1; yy < y2; yy++)
1134             for (xx = x1; xx < x2; xx++)
1135                 ret->grid[yy * ret->w + xx] = val;
1136
1137         /*
1138          * An actual change, so check to see if we've completed the
1139          * game.
1140          */
1141         if (!ret->completed) {
1142             int *rowdata = snewn(ret->rowsize, int);
1143             int i, len;
1144
1145             ret->completed = TRUE;
1146
1147             for (i=0; i<ret->w; i++) {
1148                 len = compute_rowdata(rowdata,
1149                                       ret->grid+i, ret->h, ret->w);
1150                 if (len != ret->rowlen[i] ||
1151                     memcmp(ret->rowdata+i*ret->rowsize, rowdata,
1152                            len * sizeof(int))) {
1153                     ret->completed = FALSE;
1154                     break;
1155                 }
1156             }
1157             for (i=0; i<ret->h; i++) {
1158                 len = compute_rowdata(rowdata,
1159                                       ret->grid+i*ret->w, ret->w, 1);
1160                 if (len != ret->rowlen[i+ret->w] ||
1161                     memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
1162                            len * sizeof(int))) {
1163                     ret->completed = FALSE;
1164                     break;
1165                 }
1166             }
1167
1168             sfree(rowdata);
1169         }
1170
1171         return ret;
1172     } else
1173         return NULL;
1174 }
1175
1176 /* ----------------------------------------------------------------------
1177  * Error-checking during gameplay.
1178  */
1179
1180 /*
1181  * The difficulty in error-checking Pattern is to make the error check
1182  * _weak_ enough. The most obvious way would be to check each row and
1183  * column by calling (a modified form of) do_row() to recursively
1184  * analyse the row contents against the clue set and see if the
1185  * GRID_UNKNOWNs could be filled in in any way that would end up
1186  * correct. However, this turns out to be such a strong error check as
1187  * to constitute a spoiler in many situations: you make a typo while
1188  * trying to fill in one row, and not only does the row light up to
1189  * indicate an error, but several columns crossed by the move also
1190  * light up and draw your attention to deductions you hadn't even
1191  * noticed you could make.
1192  *
1193  * So instead I restrict error-checking to 'complete runs' within a
1194  * row, by which I mean contiguous sequences of GRID_FULL bounded at
1195  * both ends by either GRID_EMPTY or the ends of the row. We identify
1196  * all the complete runs in a row, and verify that _those_ are
1197  * consistent with the row's clue list. Sequences of complete runs
1198  * separated by solid GRID_EMPTY are required to match contiguous
1199  * sequences in the clue list, whereas if there's at least one
1200  * GRID_UNKNOWN between any two complete runs then those two need not
1201  * be contiguous in the clue list.
1202  *
1203  * To simplify the edge cases, I pretend that the clue list for the
1204  * row is extended with a 0 at each end, and I also pretend that the
1205  * grid data for the row is extended with a GRID_EMPTY and a
1206  * zero-length run at each end. This permits the contiguity checker to
1207  * handle the fiddly end effects (e.g. if the first contiguous
1208  * sequence of complete runs in the grid matches _something_ in the
1209  * clue list but not at the beginning, this is allowable iff there's a
1210  * GRID_UNKNOWN before the first one) with minimal faff, since the end
1211  * effects just drop out as special cases of the normal inter-run
1212  * handling (in this code the above case is not 'at the end of the
1213  * clue list' at all, but between the implicit initial zero run and
1214  * the first nonzero one).
1215  *
1216  * We must also be a little careful about how we search for a
1217  * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1218  * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1219  * for 1 in the clue list and find it at the very beginning. But now
1220  * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1221  * can't naively look at the next clue from the 1 we found, because
1222  * that'll be the second 1 and won't match. Instead, we must backtrack
1223  * by observing that the 2 we've just found must be contiguous with
1224  * the 1 we've already seen, so we search for the sequence (1 2) and
1225  * find it starting at the second 1. Now if we see a 3, we must
1226  * rethink again and search for (1 2 3).
1227  */
1228
1229 struct errcheck_state {
1230     /*
1231      * rowdata and rowlen point at the clue data for this row in the
1232      * game state.
1233      */
1234     int *rowdata;
1235     int rowlen;
1236     /*
1237      * rowpos indicates the lowest position where it would be valid to
1238      * see our next run length. It might be equal to rowlen,
1239      * indicating that the next run would have to be the terminating 0.
1240      */
1241     int rowpos;
1242     /*
1243      * ncontig indicates how many runs we've seen in a contiguous
1244      * block. This is taken into account when searching for the next
1245      * run we find, unless ncontig is zeroed out first by encountering
1246      * a GRID_UNKNOWN.
1247      */
1248     int ncontig;
1249 };
1250
1251 static int errcheck_found_run(struct errcheck_state *es, int r)
1252 {
1253 /* Macro to handle the pretence that rowdata has a 0 at each end */
1254 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1255
1256     /*
1257      * See if we can find this new run length at a position where it
1258      * also matches the last 'ncontig' runs we've seen.
1259      */
1260     int i, newpos;
1261     for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1262
1263         if (ROWDATA(newpos) != r)
1264             goto notfound;
1265
1266         for (i = 1; i <= es->ncontig; i++)
1267             if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1268                 goto notfound;
1269
1270         es->rowpos = newpos+1;
1271         es->ncontig++;
1272         return TRUE;
1273
1274       notfound:;
1275     }
1276
1277     return FALSE;
1278
1279 #undef ROWDATA
1280 }
1281
1282 static int check_errors(game_state *state, int i)
1283 {
1284     int start, step, end, j;
1285     int val, runlen;
1286     struct errcheck_state aes, *es = &aes;
1287
1288     es->rowlen = state->rowlen[i];
1289     es->rowdata = state->rowdata + state->rowsize * i;
1290     /* Pretend that we've already encountered the initial zero run */
1291     es->ncontig = 1;
1292     es->rowpos = 0;
1293
1294     if (i < state->w) {
1295         start = i;
1296         step = state->w;
1297         end = start + step * state->h;
1298     } else {
1299         start = (i - state->w) * state->w;
1300         step = 1;
1301         end = start + step * state->w;
1302     }
1303
1304     runlen = -1;
1305     for (j = start - step; j <= end; j += step) {
1306         if (j < start || j == end)
1307             val = GRID_EMPTY;
1308         else
1309             val = state->grid[j];
1310
1311         if (val == GRID_UNKNOWN) {
1312             runlen = -1;
1313             es->ncontig = 0;
1314         } else if (val == GRID_FULL) {
1315             if (runlen >= 0)
1316                 runlen++;
1317         } else if (val == GRID_EMPTY) {
1318             if (runlen > 0) {
1319                 if (!errcheck_found_run(es, runlen))
1320                     return TRUE;       /* error! */
1321             }
1322             runlen = 0;
1323         }
1324     }
1325
1326     /* Signal end-of-row by sending errcheck_found_run the terminating
1327      * zero run, which will be marked as contiguous with the previous
1328      * run if and only if there hasn't been a GRID_UNKNOWN before. */
1329     if (!errcheck_found_run(es, 0))
1330         return TRUE;                   /* error at the last minute! */
1331
1332     return FALSE;                      /* no error */
1333 }
1334
1335 /* ----------------------------------------------------------------------
1336  * Drawing routines.
1337  */
1338
1339 static void game_compute_size(game_params *params, int tilesize,
1340                               int *x, int *y)
1341 {
1342     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1343     struct { int tilesize; } ads, *ds = &ads;
1344     ads.tilesize = tilesize;
1345
1346     *x = SIZE(params->w);
1347     *y = SIZE(params->h);
1348 }
1349
1350 static void game_set_size(drawing *dr, game_drawstate *ds,
1351                           game_params *params, int tilesize)
1352 {
1353     ds->tilesize = tilesize;
1354 }
1355
1356 static float *game_colours(frontend *fe, int *ncolours)
1357 {
1358     float *ret = snewn(3 * NCOLOURS, float);
1359     int i;
1360
1361     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1362
1363     for (i = 0; i < 3; i++) {
1364         ret[COL_GRID    * 3 + i] = 0.3F;
1365         ret[COL_UNKNOWN * 3 + i] = 0.5F;
1366         ret[COL_TEXT    * 3 + i] = 0.0F;
1367         ret[COL_FULL    * 3 + i] = 0.0F;
1368         ret[COL_EMPTY   * 3 + i] = 1.0F;
1369     }
1370     ret[COL_CURSOR * 3 + 0] = 1.0F;
1371     ret[COL_CURSOR * 3 + 1] = 0.25F;
1372     ret[COL_CURSOR * 3 + 2] = 0.25F;
1373     ret[COL_ERROR * 3 + 0] = 1.0F;
1374     ret[COL_ERROR * 3 + 1] = 0.0F;
1375     ret[COL_ERROR * 3 + 2] = 0.0F;
1376
1377     *ncolours = NCOLOURS;
1378     return ret;
1379 }
1380
1381 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1382 {
1383     struct game_drawstate *ds = snew(struct game_drawstate);
1384
1385     ds->started = FALSE;
1386     ds->w = state->w;
1387     ds->h = state->h;
1388     ds->visible = snewn(ds->w * ds->h, unsigned char);
1389     ds->tilesize = 0;                  /* not decided yet */
1390     memset(ds->visible, 255, ds->w * ds->h);
1391     ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1392     memset(ds->numcolours, 255, ds->w + ds->h);
1393     ds->cur_x = ds->cur_y = 0;
1394
1395     return ds;
1396 }
1397
1398 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1399 {
1400     sfree(ds->visible);
1401     sfree(ds);
1402 }
1403
1404 static void grid_square(drawing *dr, game_drawstate *ds,
1405                         int y, int x, int state, int cur)
1406 {
1407     int xl, xr, yt, yb, dx, dy, dw, dh;
1408
1409     draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1410               TILE_SIZE, TILE_SIZE, COL_GRID);
1411
1412     xl = (x % 5 == 0 ? 1 : 0);
1413     yt = (y % 5 == 0 ? 1 : 0);
1414     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1415     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1416
1417     dx = TOCOORD(ds->w, x) + 1 + xl;
1418     dy = TOCOORD(ds->h, y) + 1 + yt;
1419     dw = TILE_SIZE - xl - xr - 1;
1420     dh = TILE_SIZE - yt - yb - 1;
1421
1422     draw_rect(dr, dx, dy, dw, dh,
1423               (state == GRID_FULL ? COL_FULL :
1424                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1425     if (cur) {
1426         draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1427         draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1428     }
1429
1430     draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1431                 TILE_SIZE, TILE_SIZE);
1432 }
1433
1434 /*
1435  * Draw the numbers for a single row or column.
1436  */
1437 static void draw_numbers(drawing *dr, game_drawstate *ds, game_state *state,
1438                          int i, int erase, int colour)
1439 {
1440     int rowlen = state->rowlen[i];
1441     int *rowdata = state->rowdata + state->rowsize * i;
1442     int nfit;
1443     int j;
1444
1445     if (erase) {
1446         if (i < state->w) {
1447             draw_rect(dr, TOCOORD(state->w, i), 0,
1448                       TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE,
1449                       COL_BACKGROUND);
1450         } else {
1451             draw_rect(dr, 0, TOCOORD(state->h, i - state->w),
1452                       BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE,
1453                       COL_BACKGROUND);
1454         }
1455     }
1456
1457     /*
1458      * Normally I space the numbers out by the same distance as the
1459      * tile size. However, if there are more numbers than available
1460      * spaces, I have to squash them up a bit.
1461      */
1462     if (i < state->w)
1463         nfit = TLBORDER(state->h);
1464     else
1465         nfit = TLBORDER(state->w);
1466     nfit = max(rowlen, nfit) - 1;
1467     assert(nfit > 0);
1468
1469     for (j = 0; j < rowlen; j++) {
1470         int x, y;
1471         char str[80];
1472
1473         if (i < state->w) {
1474             x = TOCOORD(state->w, i);
1475             y = BORDER + TILE_SIZE * (TLBORDER(state->h)-1);
1476             y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->h)-1) / nfit;
1477         } else {
1478             y = TOCOORD(state->h, i - state->w);
1479             x = BORDER + TILE_SIZE * (TLBORDER(state->w)-1);
1480             x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->w)-1) / nfit;
1481         }
1482
1483         sprintf(str, "%d", rowdata[j]);
1484         draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1485                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1486     }
1487
1488     if (i < state->w) {
1489         draw_update(dr, TOCOORD(state->w, i), 0,
1490                     TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE);
1491     } else {
1492         draw_update(dr, 0, TOCOORD(state->h, i - state->w),
1493                     BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE);
1494     }
1495 }
1496
1497 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1498                         game_state *state, int dir, game_ui *ui,
1499                         float animtime, float flashtime)
1500 {
1501     int i, j;
1502     int x1, x2, y1, y2;
1503     int cx, cy, cmoved;
1504
1505     if (!ds->started) {
1506         /*
1507          * The initial contents of the window are not guaranteed
1508          * and can vary with front ends. To be on the safe side,
1509          * all games should start by drawing a big background-
1510          * colour rectangle covering the whole window.
1511          */
1512         draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1513
1514         /*
1515          * Draw the grid outline.
1516          */
1517         draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1518                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1519                   COL_GRID);
1520
1521         ds->started = TRUE;
1522
1523         draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1524     }
1525
1526     if (ui->dragging) {
1527         x1 = min(ui->drag_start_x, ui->drag_end_x);
1528         x2 = max(ui->drag_start_x, ui->drag_end_x);
1529         y1 = min(ui->drag_start_y, ui->drag_end_y);
1530         y2 = max(ui->drag_start_y, ui->drag_end_y);
1531     } else {
1532         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1533     }
1534
1535     if (ui->cur_visible) {
1536         cx = ui->cur_x; cy = ui->cur_y;
1537     } else {
1538         cx = cy = -1;
1539     }
1540     cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1541
1542     /*
1543      * Now draw any grid squares which have changed since last
1544      * redraw.
1545      */
1546     for (i = 0; i < ds->h; i++) {
1547         for (j = 0; j < ds->w; j++) {
1548             int val, cc = 0;
1549
1550             /*
1551              * Work out what state this square should be drawn in,
1552              * taking any current drag operation into account.
1553              */
1554             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1555                 val = ui->state;
1556             else
1557                 val = state->grid[i * state->w + j];
1558
1559             if (cmoved) {
1560                 /* the cursor has moved; if we were the old or
1561                  * the new cursor position we need to redraw. */
1562                 if (j == cx && i == cy) cc = 1;
1563                 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1564             }
1565
1566             /*
1567              * Briefly invert everything twice during a completion
1568              * flash.
1569              */
1570             if (flashtime > 0 &&
1571                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1572                 val != GRID_UNKNOWN)
1573                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1574
1575             if (ds->visible[i * ds->w + j] != val || cc) {
1576                 grid_square(dr, ds, i, j, val,
1577                             (j == cx && i == cy));
1578                 ds->visible[i * ds->w + j] = val;
1579             }
1580         }
1581     }
1582     ds->cur_x = cx; ds->cur_y = cy;
1583
1584     /*
1585      * Redraw any numbers which have changed their colour due to error
1586      * indication.
1587      */
1588     for (i = 0; i < state->w + state->h; i++) {
1589         int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1590         if (ds->numcolours[i] != colour) {
1591             draw_numbers(dr, ds, state, i, TRUE, colour);
1592             ds->numcolours[i] = colour;
1593         }
1594     }
1595 }
1596
1597 static float game_anim_length(game_state *oldstate,
1598                               game_state *newstate, int dir, game_ui *ui)
1599 {
1600     return 0.0F;
1601 }
1602
1603 static float game_flash_length(game_state *oldstate,
1604                                game_state *newstate, int dir, game_ui *ui)
1605 {
1606     if (!oldstate->completed && newstate->completed &&
1607         !oldstate->cheated && !newstate->cheated)
1608         return FLASH_TIME;
1609     return 0.0F;
1610 }
1611
1612 static int game_status(game_state *state)
1613 {
1614     return state->completed ? +1 : 0;
1615 }
1616
1617 static int game_timing_state(game_state *state, game_ui *ui)
1618 {
1619     return TRUE;
1620 }
1621
1622 static void game_print_size(game_params *params, float *x, float *y)
1623 {
1624     int pw, ph;
1625
1626     /*
1627      * I'll use 5mm squares by default.
1628      */
1629     game_compute_size(params, 500, &pw, &ph);
1630     *x = pw / 100.0F;
1631     *y = ph / 100.0F;
1632 }
1633
1634 static void game_print(drawing *dr, game_state *state, int tilesize)
1635 {
1636     int w = state->w, h = state->h;
1637     int ink = print_mono_colour(dr, 0);
1638     int x, y, i;
1639
1640     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1641     game_drawstate ads, *ds = &ads;
1642     game_set_size(dr, ds, NULL, tilesize);
1643
1644     /*
1645      * Border.
1646      */
1647     print_line_width(dr, TILE_SIZE / 16);
1648     draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1649                       w*TILE_SIZE, h*TILE_SIZE, ink);
1650
1651     /*
1652      * Grid.
1653      */
1654     for (x = 1; x < w; x++) {
1655         print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1656         draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1657                   TOCOORD(w, x), TOCOORD(h, h), ink);
1658     }
1659     for (y = 1; y < h; y++) {
1660         print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1661         draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1662                   TOCOORD(w, w), TOCOORD(h, y), ink);
1663     }
1664
1665     /*
1666      * Clues.
1667      */
1668     for (i = 0; i < state->w + state->h; i++)
1669         draw_numbers(dr, ds, state, i, FALSE, ink);
1670
1671     /*
1672      * Solution.
1673      */
1674     print_line_width(dr, TILE_SIZE / 128);
1675     for (y = 0; y < h; y++)
1676         for (x = 0; x < w; x++) {
1677             if (state->grid[y*w+x] == GRID_FULL)
1678                 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1679                           TILE_SIZE, TILE_SIZE, ink);
1680             else if (state->grid[y*w+x] == GRID_EMPTY)
1681                 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1682                             TOCOORD(h, y) + TILE_SIZE/2,
1683                             TILE_SIZE/12, ink, ink);
1684         }
1685 }
1686
1687 #ifdef COMBINED
1688 #define thegame pattern
1689 #endif
1690
1691 const struct game thegame = {
1692     "Pattern", "games.pattern", "pattern",
1693     default_params,
1694     game_fetch_preset,
1695     decode_params,
1696     encode_params,
1697     free_params,
1698     dup_params,
1699     TRUE, game_configure, custom_params,
1700     validate_params,
1701     new_game_desc,
1702     validate_desc,
1703     new_game,
1704     dup_game,
1705     free_game,
1706     TRUE, solve_game,
1707     FALSE, game_can_format_as_text_now, game_text_format,
1708     new_ui,
1709     free_ui,
1710     encode_ui,
1711     decode_ui,
1712     game_changed_state,
1713     interpret_move,
1714     execute_move,
1715     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1716     game_colours,
1717     game_new_drawstate,
1718     game_free_drawstate,
1719     game_redraw,
1720     game_anim_length,
1721     game_flash_length,
1722     game_status,
1723     TRUE, FALSE, game_print_size, game_print,
1724     FALSE,                             /* wants_statusbar */
1725     FALSE, game_timing_state,
1726     REQUIRE_RBUTTON,                   /* flags */
1727 };
1728
1729 #ifdef STANDALONE_SOLVER
1730
1731 int main(int argc, char **argv)
1732 {
1733     game_params *p;
1734     game_state *s;
1735     char *id = NULL, *desc, *err;
1736
1737     while (--argc > 0) {
1738         char *p = *++argv;
1739         if (*p == '-') {
1740             if (!strcmp(p, "-v")) {
1741                 verbose = TRUE;
1742             } else {
1743                 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1744                 return 1;
1745             }
1746         } else {
1747             id = p;
1748         }
1749     }
1750
1751     if (!id) {
1752         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1753         return 1;
1754     }
1755
1756     desc = strchr(id, ':');
1757     if (!desc) {
1758         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1759         return 1;
1760     }
1761     *desc++ = '\0';
1762
1763     p = default_params();
1764     decode_params(p, id);
1765     err = validate_desc(p, desc);
1766     if (err) {
1767         fprintf(stderr, "%s: %s\n", argv[0], err);
1768         return 1;
1769     }
1770     s = new_game(NULL, p, desc);
1771
1772     {
1773         int w = p->w, h = p->h, i, j, max, cluewid = 0;
1774         unsigned char *matrix, *workspace;
1775         unsigned int *changed_h, *changed_w;
1776         int *rowdata;
1777
1778         matrix = snewn(w*h, unsigned char);
1779         max = max(w, h);
1780         workspace = snewn(max*7, unsigned char);
1781         changed_h = snewn(max+1, unsigned int);
1782         changed_w = snewn(max+1, unsigned int);
1783         rowdata = snewn(max+1, int);
1784
1785         if (verbose) {
1786             int thiswid;
1787             /*
1788              * Work out the maximum text width of the clue numbers
1789              * in a row or column, so we can print the solver's
1790              * working in a nicely lined up way.
1791              */
1792             for (i = 0; i < (w+h); i++) {
1793                 char buf[80];
1794                 for (thiswid = -1, j = 0; j < s->rowlen[i]; j++)
1795                     thiswid += sprintf(buf, " %d", s->rowdata[s->rowsize*i+j]);
1796                 if (cluewid < thiswid)
1797                     cluewid = thiswid;
1798             }
1799         }
1800
1801         solve_puzzle(s, NULL, w, h, matrix, workspace,
1802                      changed_h, changed_w, rowdata, cluewid);
1803
1804         for (i = 0; i < h; i++) {
1805             for (j = 0; j < w; j++) {
1806                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1807                          matrix[i*w+j] == BLOCK ? '#' :
1808                          matrix[i*w+j] == DOT ? '.' :
1809                          '!');
1810                 putchar(c);
1811             }
1812             printf("\n");
1813         }
1814     }
1815
1816     return 0;
1817 }
1818
1819 #endif
1820
1821 /* vim: set shiftwidth=4 tabstop=8: */