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