chiark / gitweb /
Giant const patch of doom: add a 'const' to every parameter in every
[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     return NULL;
923 }
924
925 struct game_ui {
926     int dragging;
927     int drag_start_x;
928     int drag_start_y;
929     int drag_end_x;
930     int drag_end_y;
931     int drag, release, state;
932     int cur_x, cur_y, cur_visible;
933 };
934
935 static game_ui *new_ui(const game_state *state)
936 {
937     game_ui *ret;
938
939     ret = snew(game_ui);
940     ret->dragging = FALSE;
941     ret->cur_x = ret->cur_y = ret->cur_visible = 0;
942
943     return ret;
944 }
945
946 static void free_ui(game_ui *ui)
947 {
948     sfree(ui);
949 }
950
951 static char *encode_ui(const game_ui *ui)
952 {
953     return NULL;
954 }
955
956 static void decode_ui(game_ui *ui, const char *encoding)
957 {
958 }
959
960 static void game_changed_state(game_ui *ui, const game_state *oldstate,
961                                const game_state *newstate)
962 {
963 }
964
965 struct game_drawstate {
966     int started;
967     int w, h;
968     int tilesize;
969     unsigned char *visible, *numcolours;
970     int cur_x, cur_y;
971 };
972
973 static char *interpret_move(const game_state *state, game_ui *ui,
974                             const game_drawstate *ds,
975                             int x, int y, int button)
976 {
977     button &= ~MOD_MASK;
978
979     x = FROMCOORD(state->w, x);
980     y = FROMCOORD(state->h, y);
981
982     if (x >= 0 && x < state->w && y >= 0 && y < state->h &&
983         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
984          button == MIDDLE_BUTTON)) {
985 #ifdef STYLUS_BASED
986         int currstate = state->grid[y * state->w + x];
987 #endif
988
989         ui->dragging = TRUE;
990
991         if (button == LEFT_BUTTON) {
992             ui->drag = LEFT_DRAG;
993             ui->release = LEFT_RELEASE;
994 #ifdef STYLUS_BASED
995             ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
996 #else
997             ui->state = GRID_FULL;
998 #endif
999         } else if (button == RIGHT_BUTTON) {
1000             ui->drag = RIGHT_DRAG;
1001             ui->release = RIGHT_RELEASE;
1002 #ifdef STYLUS_BASED
1003             ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1004 #else
1005             ui->state = GRID_EMPTY;
1006 #endif
1007         } else /* if (button == MIDDLE_BUTTON) */ {
1008             ui->drag = MIDDLE_DRAG;
1009             ui->release = MIDDLE_RELEASE;
1010             ui->state = GRID_UNKNOWN;
1011         }
1012
1013         ui->drag_start_x = ui->drag_end_x = x;
1014         ui->drag_start_y = ui->drag_end_y = y;
1015         ui->cur_visible = 0;
1016
1017         return "";                     /* UI activity occurred */
1018     }
1019
1020     if (ui->dragging && button == ui->drag) {
1021         /*
1022          * There doesn't seem much point in allowing a rectangle
1023          * drag; people will generally only want to drag a single
1024          * horizontal or vertical line, so we make that easy by
1025          * snapping to it.
1026          * 
1027          * Exception: if we're _middle_-button dragging to tag
1028          * things as UNKNOWN, we may well want to trash an entire
1029          * area and start over!
1030          */
1031         if (ui->state != GRID_UNKNOWN) {
1032             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1033                 y = ui->drag_start_y;
1034             else
1035                 x = ui->drag_start_x;
1036         }
1037
1038         if (x < 0) x = 0;
1039         if (y < 0) y = 0;
1040         if (x >= state->w) x = state->w - 1;
1041         if (y >= state->h) y = state->h - 1;
1042
1043         ui->drag_end_x = x;
1044         ui->drag_end_y = y;
1045
1046         return "";                     /* UI activity occurred */
1047     }
1048
1049     if (ui->dragging && button == ui->release) {
1050         int x1, x2, y1, y2, xx, yy;
1051         int move_needed = FALSE;
1052
1053         x1 = min(ui->drag_start_x, ui->drag_end_x);
1054         x2 = max(ui->drag_start_x, ui->drag_end_x);
1055         y1 = min(ui->drag_start_y, ui->drag_end_y);
1056         y2 = max(ui->drag_start_y, ui->drag_end_y);
1057
1058         for (yy = y1; yy <= y2; yy++)
1059             for (xx = x1; xx <= x2; xx++)
1060                 if (state->grid[yy * state->w + xx] != ui->state)
1061                     move_needed = TRUE;
1062
1063         ui->dragging = FALSE;
1064
1065         if (move_needed) {
1066             char buf[80];
1067             sprintf(buf, "%c%d,%d,%d,%d",
1068                     (char)(ui->state == GRID_FULL ? 'F' :
1069                            ui->state == GRID_EMPTY ? 'E' : 'U'),
1070                     x1, y1, x2-x1+1, y2-y1+1);
1071             return dupstr(buf);
1072         } else
1073             return "";                 /* UI activity occurred */
1074     }
1075
1076     if (IS_CURSOR_MOVE(button)) {
1077         move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, 0);
1078         ui->cur_visible = 1;
1079         return "";
1080     }
1081     if (IS_CURSOR_SELECT(button)) {
1082         int currstate = state->grid[ui->cur_y * state->w + ui->cur_x];
1083         int newstate;
1084         char buf[80];
1085
1086         if (!ui->cur_visible) {
1087             ui->cur_visible = 1;
1088             return "";
1089         }
1090
1091         if (button == CURSOR_SELECT2)
1092             newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1093                 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1094         else
1095             newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1096                 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1097
1098         sprintf(buf, "%c%d,%d,%d,%d",
1099                 (char)(newstate == GRID_FULL ? 'F' :
1100                        newstate == GRID_EMPTY ? 'E' : 'U'),
1101                 ui->cur_x, ui->cur_y, 1, 1);
1102         return dupstr(buf);
1103     }
1104
1105     return NULL;
1106 }
1107
1108 static game_state *execute_move(const game_state *from, const char *move)
1109 {
1110     game_state *ret;
1111     int x1, x2, y1, y2, xx, yy;
1112     int val;
1113
1114     if (move[0] == 'S' && strlen(move) == from->w * from->h + 1) {
1115         int i;
1116
1117         ret = dup_game(from);
1118
1119         for (i = 0; i < ret->w * ret->h; i++)
1120             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1121
1122         ret->completed = ret->cheated = TRUE;
1123
1124         return ret;
1125     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1126         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1127         x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
1128         y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
1129
1130         x2 += x1;
1131         y2 += y1;
1132         val = (move[0] == 'F' ? GRID_FULL :
1133                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1134
1135         ret = dup_game(from);
1136         for (yy = y1; yy < y2; yy++)
1137             for (xx = x1; xx < x2; xx++)
1138                 ret->grid[yy * ret->w + xx] = val;
1139
1140         /*
1141          * An actual change, so check to see if we've completed the
1142          * game.
1143          */
1144         if (!ret->completed) {
1145             int *rowdata = snewn(ret->rowsize, int);
1146             int i, len;
1147
1148             ret->completed = TRUE;
1149
1150             for (i=0; i<ret->w; i++) {
1151                 len = compute_rowdata(rowdata,
1152                                       ret->grid+i, ret->h, ret->w);
1153                 if (len != ret->rowlen[i] ||
1154                     memcmp(ret->rowdata+i*ret->rowsize, rowdata,
1155                            len * sizeof(int))) {
1156                     ret->completed = FALSE;
1157                     break;
1158                 }
1159             }
1160             for (i=0; i<ret->h; i++) {
1161                 len = compute_rowdata(rowdata,
1162                                       ret->grid+i*ret->w, ret->w, 1);
1163                 if (len != ret->rowlen[i+ret->w] ||
1164                     memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
1165                            len * sizeof(int))) {
1166                     ret->completed = FALSE;
1167                     break;
1168                 }
1169             }
1170
1171             sfree(rowdata);
1172         }
1173
1174         return ret;
1175     } else
1176         return NULL;
1177 }
1178
1179 /* ----------------------------------------------------------------------
1180  * Error-checking during gameplay.
1181  */
1182
1183 /*
1184  * The difficulty in error-checking Pattern is to make the error check
1185  * _weak_ enough. The most obvious way would be to check each row and
1186  * column by calling (a modified form of) do_row() to recursively
1187  * analyse the row contents against the clue set and see if the
1188  * GRID_UNKNOWNs could be filled in in any way that would end up
1189  * correct. However, this turns out to be such a strong error check as
1190  * to constitute a spoiler in many situations: you make a typo while
1191  * trying to fill in one row, and not only does the row light up to
1192  * indicate an error, but several columns crossed by the move also
1193  * light up and draw your attention to deductions you hadn't even
1194  * noticed you could make.
1195  *
1196  * So instead I restrict error-checking to 'complete runs' within a
1197  * row, by which I mean contiguous sequences of GRID_FULL bounded at
1198  * both ends by either GRID_EMPTY or the ends of the row. We identify
1199  * all the complete runs in a row, and verify that _those_ are
1200  * consistent with the row's clue list. Sequences of complete runs
1201  * separated by solid GRID_EMPTY are required to match contiguous
1202  * sequences in the clue list, whereas if there's at least one
1203  * GRID_UNKNOWN between any two complete runs then those two need not
1204  * be contiguous in the clue list.
1205  *
1206  * To simplify the edge cases, I pretend that the clue list for the
1207  * row is extended with a 0 at each end, and I also pretend that the
1208  * grid data for the row is extended with a GRID_EMPTY and a
1209  * zero-length run at each end. This permits the contiguity checker to
1210  * handle the fiddly end effects (e.g. if the first contiguous
1211  * sequence of complete runs in the grid matches _something_ in the
1212  * clue list but not at the beginning, this is allowable iff there's a
1213  * GRID_UNKNOWN before the first one) with minimal faff, since the end
1214  * effects just drop out as special cases of the normal inter-run
1215  * handling (in this code the above case is not 'at the end of the
1216  * clue list' at all, but between the implicit initial zero run and
1217  * the first nonzero one).
1218  *
1219  * We must also be a little careful about how we search for a
1220  * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1221  * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1222  * for 1 in the clue list and find it at the very beginning. But now
1223  * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1224  * can't naively look at the next clue from the 1 we found, because
1225  * that'll be the second 1 and won't match. Instead, we must backtrack
1226  * by observing that the 2 we've just found must be contiguous with
1227  * the 1 we've already seen, so we search for the sequence (1 2) and
1228  * find it starting at the second 1. Now if we see a 3, we must
1229  * rethink again and search for (1 2 3).
1230  */
1231
1232 struct errcheck_state {
1233     /*
1234      * rowdata and rowlen point at the clue data for this row in the
1235      * game state.
1236      */
1237     int *rowdata;
1238     int rowlen;
1239     /*
1240      * rowpos indicates the lowest position where it would be valid to
1241      * see our next run length. It might be equal to rowlen,
1242      * indicating that the next run would have to be the terminating 0.
1243      */
1244     int rowpos;
1245     /*
1246      * ncontig indicates how many runs we've seen in a contiguous
1247      * block. This is taken into account when searching for the next
1248      * run we find, unless ncontig is zeroed out first by encountering
1249      * a GRID_UNKNOWN.
1250      */
1251     int ncontig;
1252 };
1253
1254 static int errcheck_found_run(struct errcheck_state *es, int r)
1255 {
1256 /* Macro to handle the pretence that rowdata has a 0 at each end */
1257 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1258
1259     /*
1260      * See if we can find this new run length at a position where it
1261      * also matches the last 'ncontig' runs we've seen.
1262      */
1263     int i, newpos;
1264     for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1265
1266         if (ROWDATA(newpos) != r)
1267             goto notfound;
1268
1269         for (i = 1; i <= es->ncontig; i++)
1270             if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1271                 goto notfound;
1272
1273         es->rowpos = newpos+1;
1274         es->ncontig++;
1275         return TRUE;
1276
1277       notfound:;
1278     }
1279
1280     return FALSE;
1281
1282 #undef ROWDATA
1283 }
1284
1285 static int check_errors(const game_state *state, int i)
1286 {
1287     int start, step, end, j;
1288     int val, runlen;
1289     struct errcheck_state aes, *es = &aes;
1290
1291     es->rowlen = state->rowlen[i];
1292     es->rowdata = state->rowdata + state->rowsize * i;
1293     /* Pretend that we've already encountered the initial zero run */
1294     es->ncontig = 1;
1295     es->rowpos = 0;
1296
1297     if (i < state->w) {
1298         start = i;
1299         step = state->w;
1300         end = start + step * state->h;
1301     } else {
1302         start = (i - state->w) * state->w;
1303         step = 1;
1304         end = start + step * state->w;
1305     }
1306
1307     runlen = -1;
1308     for (j = start - step; j <= end; j += step) {
1309         if (j < start || j == end)
1310             val = GRID_EMPTY;
1311         else
1312             val = state->grid[j];
1313
1314         if (val == GRID_UNKNOWN) {
1315             runlen = -1;
1316             es->ncontig = 0;
1317         } else if (val == GRID_FULL) {
1318             if (runlen >= 0)
1319                 runlen++;
1320         } else if (val == GRID_EMPTY) {
1321             if (runlen > 0) {
1322                 if (!errcheck_found_run(es, runlen))
1323                     return TRUE;       /* error! */
1324             }
1325             runlen = 0;
1326         }
1327     }
1328
1329     /* Signal end-of-row by sending errcheck_found_run the terminating
1330      * zero run, which will be marked as contiguous with the previous
1331      * run if and only if there hasn't been a GRID_UNKNOWN before. */
1332     if (!errcheck_found_run(es, 0))
1333         return TRUE;                   /* error at the last minute! */
1334
1335     return FALSE;                      /* no error */
1336 }
1337
1338 /* ----------------------------------------------------------------------
1339  * Drawing routines.
1340  */
1341
1342 static void game_compute_size(const game_params *params, int tilesize,
1343                               int *x, int *y)
1344 {
1345     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1346     struct { int tilesize; } ads, *ds = &ads;
1347     ads.tilesize = tilesize;
1348
1349     *x = SIZE(params->w);
1350     *y = SIZE(params->h);
1351 }
1352
1353 static void game_set_size(drawing *dr, game_drawstate *ds,
1354                           const game_params *params, int tilesize)
1355 {
1356     ds->tilesize = tilesize;
1357 }
1358
1359 static float *game_colours(frontend *fe, int *ncolours)
1360 {
1361     float *ret = snewn(3 * NCOLOURS, float);
1362     int i;
1363
1364     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1365
1366     for (i = 0; i < 3; i++) {
1367         ret[COL_GRID    * 3 + i] = 0.3F;
1368         ret[COL_UNKNOWN * 3 + i] = 0.5F;
1369         ret[COL_TEXT    * 3 + i] = 0.0F;
1370         ret[COL_FULL    * 3 + i] = 0.0F;
1371         ret[COL_EMPTY   * 3 + i] = 1.0F;
1372     }
1373     ret[COL_CURSOR * 3 + 0] = 1.0F;
1374     ret[COL_CURSOR * 3 + 1] = 0.25F;
1375     ret[COL_CURSOR * 3 + 2] = 0.25F;
1376     ret[COL_ERROR * 3 + 0] = 1.0F;
1377     ret[COL_ERROR * 3 + 1] = 0.0F;
1378     ret[COL_ERROR * 3 + 2] = 0.0F;
1379
1380     *ncolours = NCOLOURS;
1381     return ret;
1382 }
1383
1384 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1385 {
1386     struct game_drawstate *ds = snew(struct game_drawstate);
1387
1388     ds->started = FALSE;
1389     ds->w = state->w;
1390     ds->h = state->h;
1391     ds->visible = snewn(ds->w * ds->h, unsigned char);
1392     ds->tilesize = 0;                  /* not decided yet */
1393     memset(ds->visible, 255, ds->w * ds->h);
1394     ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1395     memset(ds->numcolours, 255, ds->w + ds->h);
1396     ds->cur_x = ds->cur_y = 0;
1397
1398     return ds;
1399 }
1400
1401 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1402 {
1403     sfree(ds->visible);
1404     sfree(ds);
1405 }
1406
1407 static void grid_square(drawing *dr, game_drawstate *ds,
1408                         int y, int x, int state, int cur)
1409 {
1410     int xl, xr, yt, yb, dx, dy, dw, dh;
1411
1412     draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1413               TILE_SIZE, TILE_SIZE, COL_GRID);
1414
1415     xl = (x % 5 == 0 ? 1 : 0);
1416     yt = (y % 5 == 0 ? 1 : 0);
1417     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1418     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1419
1420     dx = TOCOORD(ds->w, x) + 1 + xl;
1421     dy = TOCOORD(ds->h, y) + 1 + yt;
1422     dw = TILE_SIZE - xl - xr - 1;
1423     dh = TILE_SIZE - yt - yb - 1;
1424
1425     draw_rect(dr, dx, dy, dw, dh,
1426               (state == GRID_FULL ? COL_FULL :
1427                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1428     if (cur) {
1429         draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1430         draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1431     }
1432
1433     draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1434                 TILE_SIZE, TILE_SIZE);
1435 }
1436
1437 /*
1438  * Draw the numbers for a single row or column.
1439  */
1440 static void draw_numbers(drawing *dr, game_drawstate *ds,
1441                          const game_state *state, int i, int erase, int colour)
1442 {
1443     int rowlen = state->rowlen[i];
1444     int *rowdata = state->rowdata + state->rowsize * i;
1445     int nfit;
1446     int j;
1447
1448     if (erase) {
1449         if (i < state->w) {
1450             draw_rect(dr, TOCOORD(state->w, i), 0,
1451                       TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE,
1452                       COL_BACKGROUND);
1453         } else {
1454             draw_rect(dr, 0, TOCOORD(state->h, i - state->w),
1455                       BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE,
1456                       COL_BACKGROUND);
1457         }
1458     }
1459
1460     /*
1461      * Normally I space the numbers out by the same distance as the
1462      * tile size. However, if there are more numbers than available
1463      * spaces, I have to squash them up a bit.
1464      */
1465     if (i < state->w)
1466         nfit = TLBORDER(state->h);
1467     else
1468         nfit = TLBORDER(state->w);
1469     nfit = max(rowlen, nfit) - 1;
1470     assert(nfit > 0);
1471
1472     for (j = 0; j < rowlen; j++) {
1473         int x, y;
1474         char str[80];
1475
1476         if (i < state->w) {
1477             x = TOCOORD(state->w, i);
1478             y = BORDER + TILE_SIZE * (TLBORDER(state->h)-1);
1479             y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->h)-1) / nfit;
1480         } else {
1481             y = TOCOORD(state->h, i - state->w);
1482             x = BORDER + TILE_SIZE * (TLBORDER(state->w)-1);
1483             x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->w)-1) / nfit;
1484         }
1485
1486         sprintf(str, "%d", rowdata[j]);
1487         draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1488                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1489     }
1490
1491     if (i < state->w) {
1492         draw_update(dr, TOCOORD(state->w, i), 0,
1493                     TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE);
1494     } else {
1495         draw_update(dr, 0, TOCOORD(state->h, i - state->w),
1496                     BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE);
1497     }
1498 }
1499
1500 static void game_redraw(drawing *dr, game_drawstate *ds,
1501                         const game_state *oldstate, const game_state *state,
1502                         int dir, const game_ui *ui,
1503                         float animtime, float flashtime)
1504 {
1505     int i, j;
1506     int x1, x2, y1, y2;
1507     int cx, cy, cmoved;
1508
1509     if (!ds->started) {
1510         /*
1511          * The initial contents of the window are not guaranteed
1512          * and can vary with front ends. To be on the safe side,
1513          * all games should start by drawing a big background-
1514          * colour rectangle covering the whole window.
1515          */
1516         draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1517
1518         /*
1519          * Draw the grid outline.
1520          */
1521         draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1522                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1523                   COL_GRID);
1524
1525         ds->started = TRUE;
1526
1527         draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1528     }
1529
1530     if (ui->dragging) {
1531         x1 = min(ui->drag_start_x, ui->drag_end_x);
1532         x2 = max(ui->drag_start_x, ui->drag_end_x);
1533         y1 = min(ui->drag_start_y, ui->drag_end_y);
1534         y2 = max(ui->drag_start_y, ui->drag_end_y);
1535     } else {
1536         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1537     }
1538
1539     if (ui->cur_visible) {
1540         cx = ui->cur_x; cy = ui->cur_y;
1541     } else {
1542         cx = cy = -1;
1543     }
1544     cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1545
1546     /*
1547      * Now draw any grid squares which have changed since last
1548      * redraw.
1549      */
1550     for (i = 0; i < ds->h; i++) {
1551         for (j = 0; j < ds->w; j++) {
1552             int val, cc = 0;
1553
1554             /*
1555              * Work out what state this square should be drawn in,
1556              * taking any current drag operation into account.
1557              */
1558             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1559                 val = ui->state;
1560             else
1561                 val = state->grid[i * state->w + j];
1562
1563             if (cmoved) {
1564                 /* the cursor has moved; if we were the old or
1565                  * the new cursor position we need to redraw. */
1566                 if (j == cx && i == cy) cc = 1;
1567                 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1568             }
1569
1570             /*
1571              * Briefly invert everything twice during a completion
1572              * flash.
1573              */
1574             if (flashtime > 0 &&
1575                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1576                 val != GRID_UNKNOWN)
1577                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1578
1579             if (ds->visible[i * ds->w + j] != val || cc) {
1580                 grid_square(dr, ds, i, j, val,
1581                             (j == cx && i == cy));
1582                 ds->visible[i * ds->w + j] = val;
1583             }
1584         }
1585     }
1586     ds->cur_x = cx; ds->cur_y = cy;
1587
1588     /*
1589      * Redraw any numbers which have changed their colour due to error
1590      * indication.
1591      */
1592     for (i = 0; i < state->w + state->h; i++) {
1593         int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1594         if (ds->numcolours[i] != colour) {
1595             draw_numbers(dr, ds, state, i, TRUE, colour);
1596             ds->numcolours[i] = colour;
1597         }
1598     }
1599 }
1600
1601 static float game_anim_length(const game_state *oldstate,
1602                               const game_state *newstate, int dir, game_ui *ui)
1603 {
1604     return 0.0F;
1605 }
1606
1607 static float game_flash_length(const game_state *oldstate,
1608                                const game_state *newstate, int dir, game_ui *ui)
1609 {
1610     if (!oldstate->completed && newstate->completed &&
1611         !oldstate->cheated && !newstate->cheated)
1612         return FLASH_TIME;
1613     return 0.0F;
1614 }
1615
1616 static int game_status(const game_state *state)
1617 {
1618     return state->completed ? +1 : 0;
1619 }
1620
1621 static int game_timing_state(const game_state *state, game_ui *ui)
1622 {
1623     return TRUE;
1624 }
1625
1626 static void game_print_size(const game_params *params, float *x, float *y)
1627 {
1628     int pw, ph;
1629
1630     /*
1631      * I'll use 5mm squares by default.
1632      */
1633     game_compute_size(params, 500, &pw, &ph);
1634     *x = pw / 100.0F;
1635     *y = ph / 100.0F;
1636 }
1637
1638 static void game_print(drawing *dr, const game_state *state, int tilesize)
1639 {
1640     int w = state->w, h = state->h;
1641     int ink = print_mono_colour(dr, 0);
1642     int x, y, i;
1643
1644     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1645     game_drawstate ads, *ds = &ads;
1646     game_set_size(dr, ds, NULL, tilesize);
1647
1648     /*
1649      * Border.
1650      */
1651     print_line_width(dr, TILE_SIZE / 16);
1652     draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1653                       w*TILE_SIZE, h*TILE_SIZE, ink);
1654
1655     /*
1656      * Grid.
1657      */
1658     for (x = 1; x < w; x++) {
1659         print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1660         draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1661                   TOCOORD(w, x), TOCOORD(h, h), ink);
1662     }
1663     for (y = 1; y < h; y++) {
1664         print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1665         draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1666                   TOCOORD(w, w), TOCOORD(h, y), ink);
1667     }
1668
1669     /*
1670      * Clues.
1671      */
1672     for (i = 0; i < state->w + state->h; i++)
1673         draw_numbers(dr, ds, state, i, FALSE, ink);
1674
1675     /*
1676      * Solution.
1677      */
1678     print_line_width(dr, TILE_SIZE / 128);
1679     for (y = 0; y < h; y++)
1680         for (x = 0; x < w; x++) {
1681             if (state->grid[y*w+x] == GRID_FULL)
1682                 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1683                           TILE_SIZE, TILE_SIZE, ink);
1684             else if (state->grid[y*w+x] == GRID_EMPTY)
1685                 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1686                             TOCOORD(h, y) + TILE_SIZE/2,
1687                             TILE_SIZE/12, ink, ink);
1688         }
1689 }
1690
1691 #ifdef COMBINED
1692 #define thegame pattern
1693 #endif
1694
1695 const struct game thegame = {
1696     "Pattern", "games.pattern", "pattern",
1697     default_params,
1698     game_fetch_preset,
1699     decode_params,
1700     encode_params,
1701     free_params,
1702     dup_params,
1703     TRUE, game_configure, custom_params,
1704     validate_params,
1705     new_game_desc,
1706     validate_desc,
1707     new_game,
1708     dup_game,
1709     free_game,
1710     TRUE, solve_game,
1711     FALSE, game_can_format_as_text_now, game_text_format,
1712     new_ui,
1713     free_ui,
1714     encode_ui,
1715     decode_ui,
1716     game_changed_state,
1717     interpret_move,
1718     execute_move,
1719     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1720     game_colours,
1721     game_new_drawstate,
1722     game_free_drawstate,
1723     game_redraw,
1724     game_anim_length,
1725     game_flash_length,
1726     game_status,
1727     TRUE, FALSE, game_print_size, game_print,
1728     FALSE,                             /* wants_statusbar */
1729     FALSE, game_timing_state,
1730     REQUIRE_RBUTTON,                   /* flags */
1731 };
1732
1733 #ifdef STANDALONE_SOLVER
1734
1735 int main(int argc, char **argv)
1736 {
1737     game_params *p;
1738     game_state *s;
1739     char *id = NULL, *desc, *err;
1740
1741     while (--argc > 0) {
1742         char *p = *++argv;
1743         if (*p == '-') {
1744             if (!strcmp(p, "-v")) {
1745                 verbose = TRUE;
1746             } else {
1747                 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1748                 return 1;
1749             }
1750         } else {
1751             id = p;
1752         }
1753     }
1754
1755     if (!id) {
1756         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1757         return 1;
1758     }
1759
1760     desc = strchr(id, ':');
1761     if (!desc) {
1762         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1763         return 1;
1764     }
1765     *desc++ = '\0';
1766
1767     p = default_params();
1768     decode_params(p, id);
1769     err = validate_desc(p, desc);
1770     if (err) {
1771         fprintf(stderr, "%s: %s\n", argv[0], err);
1772         return 1;
1773     }
1774     s = new_game(NULL, p, desc);
1775
1776     {
1777         int w = p->w, h = p->h, i, j, max, cluewid = 0;
1778         unsigned char *matrix, *workspace;
1779         unsigned int *changed_h, *changed_w;
1780         int *rowdata;
1781
1782         matrix = snewn(w*h, unsigned char);
1783         max = max(w, h);
1784         workspace = snewn(max*7, unsigned char);
1785         changed_h = snewn(max+1, unsigned int);
1786         changed_w = snewn(max+1, unsigned int);
1787         rowdata = snewn(max+1, int);
1788
1789         if (verbose) {
1790             int thiswid;
1791             /*
1792              * Work out the maximum text width of the clue numbers
1793              * in a row or column, so we can print the solver's
1794              * working in a nicely lined up way.
1795              */
1796             for (i = 0; i < (w+h); i++) {
1797                 char buf[80];
1798                 for (thiswid = -1, j = 0; j < s->rowlen[i]; j++)
1799                     thiswid += sprintf(buf, " %d", s->rowdata[s->rowsize*i+j]);
1800                 if (cluewid < thiswid)
1801                     cluewid = thiswid;
1802             }
1803         }
1804
1805         solve_puzzle(s, NULL, w, h, matrix, workspace,
1806                      changed_h, changed_w, rowdata, cluewid);
1807
1808         for (i = 0; i < h; i++) {
1809             for (j = 0; j < w; j++) {
1810                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1811                          matrix[i*w+j] == BLOCK ? '#' :
1812                          matrix[i*w+j] == DOT ? '.' :
1813                          '!');
1814                 putchar(c);
1815             }
1816             printf("\n");
1817         }
1818     }
1819
1820     return 0;
1821 }
1822
1823 #endif
1824
1825 /* vim: set shiftwidth=4 tabstop=8: */