chiark / gitweb /
New {en,de}code_ui functions should be static. Oops.
[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_UNKNOWN,
19     COL_GRID,
20     NCOLOURS
21 };
22
23 #define PREFERRED_TILE_SIZE 24
24 #define TILE_SIZE (ds->tilesize)
25 #define BORDER (3 * TILE_SIZE / 4)
26 #define TLBORDER(d) ( (d) / 5 + 2 )
27 #define GUTTER (TILE_SIZE / 2)
28
29 #define FROMCOORD(d, x) \
30         ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
31
32 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
33 #define GETTILESIZE(d, w) (w / (2 + TLBORDER(d) + (d)))
34
35 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
36
37 struct game_params {
38     int w, h;
39 };
40
41 #define GRID_UNKNOWN 2
42 #define GRID_FULL 1
43 #define GRID_EMPTY 0
44
45 struct game_state {
46     int w, h;
47     unsigned char *grid;
48     int rowsize;
49     int *rowdata, *rowlen;
50     int completed, cheated;
51 };
52
53 #define FLASH_TIME 0.13F
54
55 static game_params *default_params(void)
56 {
57     game_params *ret = snew(game_params);
58
59     ret->w = ret->h = 15;
60
61     return ret;
62 }
63
64 static const struct game_params pattern_presets[] = {
65     {10, 10},
66     {15, 15},
67     {20, 20},
68 #ifndef SLOW_SYSTEM
69     {25, 25},
70     {30, 30},
71 #endif
72 };
73
74 static int game_fetch_preset(int i, char **name, game_params **params)
75 {
76     game_params *ret;
77     char str[80];
78
79     if (i < 0 || i >= lenof(pattern_presets))
80         return FALSE;
81
82     ret = snew(game_params);
83     *ret = pattern_presets[i];
84
85     sprintf(str, "%dx%d", ret->w, ret->h);
86
87     *name = dupstr(str);
88     *params = ret;
89     return TRUE;
90 }
91
92 static void free_params(game_params *params)
93 {
94     sfree(params);
95 }
96
97 static game_params *dup_params(game_params *params)
98 {
99     game_params *ret = snew(game_params);
100     *ret = *params;                    /* structure copy */
101     return ret;
102 }
103
104 static void decode_params(game_params *ret, char const *string)
105 {
106     char const *p = string;
107
108     ret->w = atoi(p);
109     while (*p && isdigit(*p)) p++;
110     if (*p == 'x') {
111         p++;
112         ret->h = atoi(p);
113         while (*p && isdigit(*p)) p++;
114     } else {
115         ret->h = ret->w;
116     }
117 }
118
119 static char *encode_params(game_params *params, int full)
120 {
121     char ret[400];
122     int len;
123
124     len = sprintf(ret, "%dx%d", params->w, params->h);
125     assert(len < lenof(ret));
126     ret[len] = '\0';
127
128     return dupstr(ret);
129 }
130
131 static config_item *game_configure(game_params *params)
132 {
133     config_item *ret;
134     char buf[80];
135
136     ret = snewn(3, config_item);
137
138     ret[0].name = "Width";
139     ret[0].type = C_STRING;
140     sprintf(buf, "%d", params->w);
141     ret[0].sval = dupstr(buf);
142     ret[0].ival = 0;
143
144     ret[1].name = "Height";
145     ret[1].type = C_STRING;
146     sprintf(buf, "%d", params->h);
147     ret[1].sval = dupstr(buf);
148     ret[1].ival = 0;
149
150     ret[2].name = NULL;
151     ret[2].type = C_END;
152     ret[2].sval = NULL;
153     ret[2].ival = 0;
154
155     return ret;
156 }
157
158 static game_params *custom_params(config_item *cfg)
159 {
160     game_params *ret = snew(game_params);
161
162     ret->w = atoi(cfg[0].sval);
163     ret->h = atoi(cfg[1].sval);
164
165     return ret;
166 }
167
168 static char *validate_params(game_params *params)
169 {
170     if (params->w <= 0 || params->h <= 0)
171         return "Width and height must both be greater than zero";
172     return NULL;
173 }
174
175 /* ----------------------------------------------------------------------
176  * Puzzle generation code.
177  * 
178  * For this particular puzzle, it seemed important to me to ensure
179  * a unique solution. I do this the brute-force way, by having a
180  * solver algorithm alongside the generator, and repeatedly
181  * generating a random grid until I find one whose solution is
182  * unique. It turns out that this isn't too onerous on a modern PC
183  * provided you keep grid size below around 30. Any offers of
184  * better algorithms, however, will be very gratefully received.
185  * 
186  * Another annoyance of this approach is that it limits the
187  * available puzzles to those solvable by the algorithm I've used.
188  * My algorithm only ever considers a single row or column at any
189  * one time, which means it's incapable of solving the following
190  * difficult example (found by Bella Image around 1995/6, when she
191  * and I were both doing maths degrees):
192  * 
193  *        2  1  2  1 
194  *
195  *      +--+--+--+--+
196  * 1 1  |  |  |  |  |
197  *      +--+--+--+--+
198  *   2  |  |  |  |  |
199  *      +--+--+--+--+
200  *   1  |  |  |  |  |
201  *      +--+--+--+--+
202  *   1  |  |  |  |  |
203  *      +--+--+--+--+
204  * 
205  * Obviously this cannot be solved by a one-row-or-column-at-a-time
206  * algorithm (it would require at least one row or column reading
207  * `2 1', `1 2', `3' or `4' to get started). However, it can be
208  * proved to have a unique solution: if the top left square were
209  * empty, then the only option for the top row would be to fill the
210  * two squares in the 1 columns, which would imply the squares
211  * below those were empty, leaving no place for the 2 in the second
212  * row. Contradiction. Hence the top left square is full, and the
213  * unique solution follows easily from that starting point.
214  * 
215  * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
216  * it's useful to anyone.)
217  */
218
219 static int float_compare(const void *av, const void *bv)
220 {
221     const float *a = (const float *)av;
222     const float *b = (const float *)bv;
223     if (*a < *b)
224         return -1;
225     else if (*a > *b)
226         return +1;
227     else
228         return 0;
229 }
230
231 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
232 {
233     float *fgrid;
234     float *fgrid2;
235     int step, i, j;
236     float threshold;
237
238     fgrid = snewn(w*h, float);
239
240     for (i = 0; i < h; i++) {
241         for (j = 0; j < w; j++) {
242             fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
243         }
244     }
245
246     /*
247      * The above gives a completely random splattering of black and
248      * white cells. We want to gently bias this in favour of _some_
249      * reasonably thick areas of white and black, while retaining
250      * some randomness and fine detail.
251      * 
252      * So we evolve the starting grid using a cellular automaton.
253      * Currently, I'm doing something very simple indeed, which is
254      * to set each square to the average of the surrounding nine
255      * cells (or the average of fewer, if we're on a corner).
256      */
257     for (step = 0; step < 1; step++) {
258         fgrid2 = snewn(w*h, float);
259
260         for (i = 0; i < h; i++) {
261             for (j = 0; j < w; j++) {
262                 float sx, xbar;
263                 int n, p, q;
264
265                 /*
266                  * Compute the average of the surrounding cells.
267                  */
268                 n = 0;
269                 sx = 0.F;
270                 for (p = -1; p <= +1; p++) {
271                     for (q = -1; q <= +1; q++) {
272                         if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
273                             continue;
274                         /*
275                          * An additional special case not mentioned
276                          * above: if a grid dimension is 2xn then
277                          * we do not average across that dimension
278                          * at all. Otherwise a 2x2 grid would
279                          * contain four identical squares.
280                          */
281                         if ((h==2 && p!=0) || (w==2 && q!=0))
282                             continue;
283                         n++;
284                         sx += fgrid[(i+p)*w+(j+q)];
285                     }
286                 }
287                 xbar = sx / n;
288
289                 fgrid2[i*w+j] = xbar;
290             }
291         }
292
293         sfree(fgrid);
294         fgrid = fgrid2;
295     }
296
297     fgrid2 = snewn(w*h, float);
298     memcpy(fgrid2, fgrid, w*h*sizeof(float));
299     qsort(fgrid2, w*h, sizeof(float), float_compare);
300     threshold = fgrid2[w*h/2];
301     sfree(fgrid2);
302
303     for (i = 0; i < h; i++) {
304         for (j = 0; j < w; j++) {
305             retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
306                               GRID_EMPTY);
307         }
308     }
309
310     sfree(fgrid);
311 }
312
313 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
314 {
315     int i, n;
316
317     n = 0;
318
319     for (i = 0; i < len; i++) {
320         if (start[i*step] == GRID_FULL) {
321             int runlen = 1;
322             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
323                 runlen++;
324             ret[n++] = runlen;
325             i += runlen;
326         }
327
328         if (i < len && start[i*step] == GRID_UNKNOWN)
329             return -1;
330     }
331
332     return n;
333 }
334
335 #define UNKNOWN 0
336 #define BLOCK 1
337 #define DOT 2
338 #define STILL_UNKNOWN 3
339
340 static void do_recurse(unsigned char *known, unsigned char *deduced,
341                        unsigned char *row, int *data, int len,
342                        int freespace, int ndone, int lowest)
343 {
344     int i, j, k;
345
346     if (data[ndone]) {
347         for (i=0; i<=freespace; i++) {
348             j = lowest;
349             for (k=0; k<i; k++) row[j++] = DOT;
350             for (k=0; k<data[ndone]; k++) row[j++] = BLOCK;
351             if (j < len) row[j++] = DOT;
352             do_recurse(known, deduced, row, data, len,
353                        freespace-i, ndone+1, j);
354         }
355     } else {
356         for (i=lowest; i<len; i++)
357             row[i] = DOT;
358         for (i=0; i<len; i++)
359             if (known[i] && known[i] != row[i])
360                 return;
361         for (i=0; i<len; i++)
362             deduced[i] |= row[i];
363     }
364 }
365
366 static int do_row(unsigned char *known, unsigned char *deduced,
367                   unsigned char *row,
368                   unsigned char *start, int len, int step, int *data)
369 {
370     int rowlen, i, freespace, done_any;
371
372     freespace = len+1;
373     for (rowlen = 0; data[rowlen]; rowlen++)
374         freespace -= data[rowlen]+1;
375
376     for (i = 0; i < len; i++) {
377         known[i] = start[i*step];
378         deduced[i] = 0;
379     }
380
381     do_recurse(known, deduced, row, data, len, freespace, 0, 0);
382     done_any = FALSE;
383     for (i=0; i<len; i++)
384         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
385             start[i*step] = deduced[i];
386             done_any = TRUE;
387         }
388     return done_any;
389 }
390
391 static unsigned char *generate_soluble(random_state *rs, int w, int h)
392 {
393     int i, j, done_any, ok, ntries, max;
394     unsigned char *grid, *matrix, *workspace;
395     int *rowdata;
396
397     grid = snewn(w*h, unsigned char);
398     matrix = snewn(w*h, unsigned char);
399     max = max(w, h);
400     workspace = snewn(max*3, unsigned char);
401     rowdata = snewn(max+1, int);
402
403     ntries = 0;
404
405     do {
406         ntries++;
407
408         generate(rs, w, h, grid);
409
410         /*
411          * The game is a bit too easy if any row or column is
412          * completely black or completely white. An exception is
413          * made for rows/columns that are under 3 squares,
414          * otherwise nothing will ever be successfully generated.
415          */
416         ok = TRUE;
417         if (w > 2) {
418             for (i = 0; i < h; i++) {
419                 int colours = 0;
420                 for (j = 0; j < w; j++)
421                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
422                 if (colours != 3)
423                     ok = FALSE;
424             }
425         }
426         if (h > 2) {
427             for (j = 0; j < w; j++) {
428                 int colours = 0;
429                 for (i = 0; i < h; i++)
430                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
431                 if (colours != 3)
432                     ok = FALSE;
433             }
434         }
435         if (!ok)
436             continue;
437
438         memset(matrix, 0, w*h);
439
440         do {
441             done_any = 0;
442             for (i=0; i<h; i++) {
443                 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
444                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
445                                    matrix+i*w, w, 1, rowdata);
446             }
447             for (i=0; i<w; i++) {
448                 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
449                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
450                                    matrix+i, h, w, rowdata);
451             }
452         } while (done_any);
453
454         ok = TRUE;
455         for (i=0; i<h; i++) {
456             for (j=0; j<w; j++) {
457                 if (matrix[i*w+j] == UNKNOWN)
458                     ok = FALSE;
459             }
460         }
461     } while (!ok);
462
463     sfree(matrix);
464     sfree(workspace);
465     sfree(rowdata);
466     return grid;
467 }
468
469 static char *new_game_desc(game_params *params, random_state *rs,
470                            char **aux, int interactive)
471 {
472     unsigned char *grid;
473     int i, j, max, rowlen, *rowdata;
474     char intbuf[80], *desc;
475     int desclen, descpos;
476
477     grid = generate_soluble(rs, params->w, params->h);
478     max = max(params->w, params->h);
479     rowdata = snewn(max, int);
480
481     /*
482      * Save the solved game in aux.
483      */
484     {
485         char *ai = snewn(params->w * params->h + 2, char);
486
487         /*
488          * String format is exactly the same as a solve move, so we
489          * can just dupstr this in solve_game().
490          */
491
492         ai[0] = 'S';
493
494         for (i = 0; i < params->w * params->h; i++)
495             ai[i+1] = grid[i] ? '1' : '0';
496
497         ai[params->w * params->h + 1] = '\0';
498
499         *aux = ai;
500     }
501
502     /*
503      * Seed is a slash-separated list of row contents; each row
504      * contents section is a dot-separated list of integers. Row
505      * contents are listed in the order (columns left to right,
506      * then rows top to bottom).
507      * 
508      * Simplest way to handle memory allocation is to make two
509      * passes, first computing the seed size and then writing it
510      * out.
511      */
512     desclen = 0;
513     for (i = 0; i < params->w + params->h; i++) {
514         if (i < params->w)
515             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
516         else
517             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
518                                      params->w, 1);
519         if (rowlen > 0) {
520             for (j = 0; j < rowlen; j++) {
521                 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
522             }
523         } else {
524             desclen++;
525         }
526     }
527     desc = snewn(desclen, char);
528     descpos = 0;
529     for (i = 0; i < params->w + params->h; i++) {
530         if (i < params->w)
531             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
532         else
533             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
534                                      params->w, 1);
535         if (rowlen > 0) {
536             for (j = 0; j < rowlen; j++) {
537                 int len = sprintf(desc+descpos, "%d", rowdata[j]);
538                 if (j+1 < rowlen)
539                     desc[descpos + len] = '.';
540                 else
541                     desc[descpos + len] = '/';
542                 descpos += len+1;
543             }
544         } else {
545             desc[descpos++] = '/';
546         }
547     }
548     assert(descpos == desclen);
549     assert(desc[desclen-1] == '/');
550     desc[desclen-1] = '\0';
551     sfree(rowdata);
552     return desc;
553 }
554
555 static char *validate_desc(game_params *params, char *desc)
556 {
557     int i, n, rowspace;
558     char *p;
559
560     for (i = 0; i < params->w + params->h; i++) {
561         if (i < params->w)
562             rowspace = params->h + 1;
563         else
564             rowspace = params->w + 1;
565
566         if (*desc && isdigit((unsigned char)*desc)) {
567             do {
568                 p = desc;
569                 while (desc && isdigit((unsigned char)*desc)) desc++;
570                 n = atoi(p);
571                 rowspace -= n+1;
572
573                 if (rowspace < 0) {
574                     if (i < params->w)
575                         return "at least one column contains more numbers than will fit";
576                     else
577                         return "at least one row contains more numbers than will fit";
578                 }
579             } while (*desc++ == '.');
580         } else {
581             desc++;                    /* expect a slash immediately */
582         }
583
584         if (desc[-1] == '/') {
585             if (i+1 == params->w + params->h)
586                 return "too many row/column specifications";
587         } else if (desc[-1] == '\0') {
588             if (i+1 < params->w + params->h)
589                 return "too few row/column specifications";
590         } else
591             return "unrecognised character in game specification";
592     }
593
594     return NULL;
595 }
596
597 static game_state *new_game(midend_data *me, game_params *params, char *desc)
598 {
599     int i;
600     char *p;
601     game_state *state = snew(game_state);
602
603     state->w = params->w;
604     state->h = params->h;
605
606     state->grid = snewn(state->w * state->h, unsigned char);
607     memset(state->grid, GRID_UNKNOWN, state->w * state->h);
608
609     state->rowsize = max(state->w, state->h);
610     state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
611     state->rowlen = snewn(state->w + state->h, int);
612
613     state->completed = state->cheated = FALSE;
614
615     for (i = 0; i < params->w + params->h; i++) {
616         state->rowlen[i] = 0;
617         if (*desc && isdigit((unsigned char)*desc)) {
618             do {
619                 p = desc;
620                 while (desc && isdigit((unsigned char)*desc)) desc++;
621                 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
622                     atoi(p);
623             } while (*desc++ == '.');
624         } else {
625             desc++;                    /* expect a slash immediately */
626         }
627     }
628
629     return state;
630 }
631
632 static game_state *dup_game(game_state *state)
633 {
634     game_state *ret = snew(game_state);
635
636     ret->w = state->w;
637     ret->h = state->h;
638
639     ret->grid = snewn(ret->w * ret->h, unsigned char);
640     memcpy(ret->grid, state->grid, ret->w * ret->h);
641
642     ret->rowsize = state->rowsize;
643     ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
644     ret->rowlen = snewn(ret->w + ret->h, int);
645     memcpy(ret->rowdata, state->rowdata,
646            ret->rowsize * (ret->w + ret->h) * sizeof(int));
647     memcpy(ret->rowlen, state->rowlen,
648            (ret->w + ret->h) * sizeof(int));
649
650     ret->completed = state->completed;
651     ret->cheated = state->cheated;
652
653     return ret;
654 }
655
656 static void free_game(game_state *state)
657 {
658     sfree(state->rowdata);
659     sfree(state->rowlen);
660     sfree(state->grid);
661     sfree(state);
662 }
663
664 static char *solve_game(game_state *state, game_state *currstate,
665                         char *ai, char **error)
666 {
667     unsigned char *matrix;
668     int w = state->w, h = state->h;
669     int i;
670     char *ret;
671     int done_any, max;
672     unsigned char *workspace;
673     int *rowdata;
674
675     /*
676      * If we already have the solved state in ai, copy it out.
677      */
678     if (ai)
679         return dupstr(ai);
680
681     matrix = snewn(w*h, unsigned char);
682     max = max(w, h);
683     workspace = snewn(max*3, unsigned char);
684     rowdata = snewn(max+1, int);
685
686     memset(matrix, 0, w*h);
687
688     do {
689         done_any = 0;
690         for (i=0; i<h; i++) {
691             memcpy(rowdata, state->rowdata + state->rowsize*(w+i),
692                    max*sizeof(int));
693             rowdata[state->rowlen[w+i]] = 0;
694             done_any |= do_row(workspace, workspace+max, workspace+2*max,
695                                matrix+i*w, w, 1, rowdata);
696         }
697         for (i=0; i<w; i++) {
698             memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
699             rowdata[state->rowlen[i]] = 0;
700             done_any |= do_row(workspace, workspace+max, workspace+2*max,
701                                matrix+i, h, w, rowdata);
702         }
703     } while (done_any);
704
705     sfree(workspace);
706     sfree(rowdata);
707
708     for (i = 0; i < w*h; i++) {
709         if (matrix[i] != BLOCK && matrix[i] != DOT) {
710             sfree(matrix);
711             *error = "Solving algorithm cannot complete this puzzle";
712             return NULL;
713         }
714     }
715
716     ret = snewn(w*h+2, char);
717     ret[0] = 'S';
718     for (i = 0; i < w*h; i++) {
719         assert(matrix[i] == BLOCK || matrix[i] == DOT);
720         ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
721     }
722     ret[w*h+1] = '\0';
723
724     sfree(matrix);
725
726     return ret;
727 }
728
729 static char *game_text_format(game_state *state)
730 {
731     return NULL;
732 }
733
734 struct game_ui {
735     int dragging;
736     int drag_start_x;
737     int drag_start_y;
738     int drag_end_x;
739     int drag_end_y;
740     int drag, release, state;
741 };
742
743 static game_ui *new_ui(game_state *state)
744 {
745     game_ui *ret;
746
747     ret = snew(game_ui);
748     ret->dragging = FALSE;
749
750     return ret;
751 }
752
753 static void free_ui(game_ui *ui)
754 {
755     sfree(ui);
756 }
757
758 static char *encode_ui(game_ui *ui)
759 {
760     return NULL;
761 }
762
763 static void decode_ui(game_ui *ui, char *encoding)
764 {
765 }
766
767 static void game_changed_state(game_ui *ui, game_state *oldstate,
768                                game_state *newstate)
769 {
770 }
771
772 struct game_drawstate {
773     int started;
774     int w, h;
775     int tilesize;
776     unsigned char *visible;
777 };
778
779 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
780                             int x, int y, int button)
781 {
782     button &= ~MOD_MASK;
783
784     x = FROMCOORD(state->w, x);
785     y = FROMCOORD(state->h, y);
786
787     if (x >= 0 && x < state->w && y >= 0 && y < state->h &&
788         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
789          button == MIDDLE_BUTTON)) {
790
791         ui->dragging = TRUE;
792
793         if (button == LEFT_BUTTON) {
794             ui->drag = LEFT_DRAG;
795             ui->release = LEFT_RELEASE;
796             ui->state = GRID_FULL;
797         } else if (button == RIGHT_BUTTON) {
798             ui->drag = RIGHT_DRAG;
799             ui->release = RIGHT_RELEASE;
800             ui->state = GRID_EMPTY;
801         } else /* if (button == MIDDLE_BUTTON) */ {
802             ui->drag = MIDDLE_DRAG;
803             ui->release = MIDDLE_RELEASE;
804             ui->state = GRID_UNKNOWN;
805         }
806
807         ui->drag_start_x = ui->drag_end_x = x;
808         ui->drag_start_y = ui->drag_end_y = y;
809
810         return "";                     /* UI activity occurred */
811     }
812
813     if (ui->dragging && button == ui->drag) {
814         /*
815          * There doesn't seem much point in allowing a rectangle
816          * drag; people will generally only want to drag a single
817          * horizontal or vertical line, so we make that easy by
818          * snapping to it.
819          * 
820          * Exception: if we're _middle_-button dragging to tag
821          * things as UNKNOWN, we may well want to trash an entire
822          * area and start over!
823          */
824         if (ui->state != GRID_UNKNOWN) {
825             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
826                 y = ui->drag_start_y;
827             else
828                 x = ui->drag_start_x;
829         }
830
831         if (x < 0) x = 0;
832         if (y < 0) y = 0;
833         if (x >= state->w) x = state->w - 1;
834         if (y >= state->h) y = state->h - 1;
835
836         ui->drag_end_x = x;
837         ui->drag_end_y = y;
838
839         return "";                     /* UI activity occurred */
840     }
841
842     if (ui->dragging && button == ui->release) {
843         int x1, x2, y1, y2, xx, yy;
844         int move_needed = FALSE;
845
846         x1 = min(ui->drag_start_x, ui->drag_end_x);
847         x2 = max(ui->drag_start_x, ui->drag_end_x);
848         y1 = min(ui->drag_start_y, ui->drag_end_y);
849         y2 = max(ui->drag_start_y, ui->drag_end_y);
850
851         for (yy = y1; yy <= y2; yy++)
852             for (xx = x1; xx <= x2; xx++)
853                 if (state->grid[yy * state->w + xx] != ui->state)
854                     move_needed = TRUE;
855
856         ui->dragging = FALSE;
857
858         if (move_needed) {
859             char buf[80];
860             sprintf(buf, "%c%d,%d,%d,%d",
861                     (ui->state == GRID_FULL ? 'F' :
862                      ui->state == GRID_EMPTY ? 'E' : 'U'),
863                     x1, y1, x2-x1+1, y2-y1+1);
864             return dupstr(buf);
865         } else
866             return "";                 /* UI activity occurred */
867     }
868
869     return NULL;
870 }
871
872 static game_state *execute_move(game_state *from, char *move)
873 {
874     game_state *ret;
875     int x1, x2, y1, y2, xx, yy;
876     int val;
877
878     if (move[0] == 'S' && strlen(move) == from->w * from->h + 1) {
879         int i;
880
881         ret = dup_game(from);
882
883         for (i = 0; i < ret->w * ret->h; i++)
884             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
885
886         ret->completed = ret->cheated = TRUE;
887
888         return ret;
889     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
890         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
891         x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
892         y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
893
894         x2 += x1;
895         y2 += y1;
896         val = (move[0] == 'F' ? GRID_FULL :
897                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
898
899         ret = dup_game(from);
900         for (yy = y1; yy < y2; yy++)
901             for (xx = x1; xx < x2; xx++)
902                 ret->grid[yy * ret->w + xx] = val;
903
904         /*
905          * An actual change, so check to see if we've completed the
906          * game.
907          */
908         if (!ret->completed) {
909             int *rowdata = snewn(ret->rowsize, int);
910             int i, len;
911
912             ret->completed = TRUE;
913
914             for (i=0; i<ret->w; i++) {
915                 len = compute_rowdata(rowdata,
916                                       ret->grid+i, ret->h, ret->w);
917                 if (len != ret->rowlen[i] ||
918                     memcmp(ret->rowdata+i*ret->rowsize, rowdata,
919                            len * sizeof(int))) {
920                     ret->completed = FALSE;
921                     break;
922                 }
923             }
924             for (i=0; i<ret->h; i++) {
925                 len = compute_rowdata(rowdata,
926                                       ret->grid+i*ret->w, ret->w, 1);
927                 if (len != ret->rowlen[i+ret->w] ||
928                     memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
929                            len * sizeof(int))) {
930                     ret->completed = FALSE;
931                     break;
932                 }
933             }
934
935             sfree(rowdata);
936         }
937
938         return ret;
939     } else
940         return NULL;
941 }
942
943 /* ----------------------------------------------------------------------
944  * Drawing routines.
945  */
946
947 static void game_size(game_params *params, game_drawstate *ds,
948                       int *x, int *y, int expand)
949 {
950     int ts;
951
952     ts = min(GETTILESIZE(params->w, *x), GETTILESIZE(params->h, *y));
953     if (expand)
954         ds->tilesize = ts;
955     else
956         ds->tilesize = min(ts, PREFERRED_TILE_SIZE);
957
958     *x = SIZE(params->w);
959     *y = SIZE(params->h);
960 }
961
962 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
963 {
964     float *ret = snewn(3 * NCOLOURS, float);
965
966     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
967
968     ret[COL_GRID * 3 + 0] = 0.3F;
969     ret[COL_GRID * 3 + 1] = 0.3F;
970     ret[COL_GRID * 3 + 2] = 0.3F;
971
972     ret[COL_UNKNOWN * 3 + 0] = 0.5F;
973     ret[COL_UNKNOWN * 3 + 1] = 0.5F;
974     ret[COL_UNKNOWN * 3 + 2] = 0.5F;
975
976     ret[COL_FULL * 3 + 0] = 0.0F;
977     ret[COL_FULL * 3 + 1] = 0.0F;
978     ret[COL_FULL * 3 + 2] = 0.0F;
979
980     ret[COL_EMPTY * 3 + 0] = 1.0F;
981     ret[COL_EMPTY * 3 + 1] = 1.0F;
982     ret[COL_EMPTY * 3 + 2] = 1.0F;
983
984     *ncolours = NCOLOURS;
985     return ret;
986 }
987
988 static game_drawstate *game_new_drawstate(game_state *state)
989 {
990     struct game_drawstate *ds = snew(struct game_drawstate);
991
992     ds->started = FALSE;
993     ds->w = state->w;
994     ds->h = state->h;
995     ds->visible = snewn(ds->w * ds->h, unsigned char);
996     ds->tilesize = 0;                  /* not decided yet */
997     memset(ds->visible, 255, ds->w * ds->h);
998
999     return ds;
1000 }
1001
1002 static void game_free_drawstate(game_drawstate *ds)
1003 {
1004     sfree(ds->visible);
1005     sfree(ds);
1006 }
1007
1008 static void grid_square(frontend *fe, game_drawstate *ds,
1009                         int y, int x, int state)
1010 {
1011     int xl, xr, yt, yb;
1012
1013     draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1014               TILE_SIZE, TILE_SIZE, COL_GRID);
1015
1016     xl = (x % 5 == 0 ? 1 : 0);
1017     yt = (y % 5 == 0 ? 1 : 0);
1018     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1019     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1020
1021     draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
1022               TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
1023               (state == GRID_FULL ? COL_FULL :
1024                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1025
1026     draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1027                 TILE_SIZE, TILE_SIZE);
1028 }
1029
1030 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1031                         game_state *state, int dir, game_ui *ui,
1032                         float animtime, float flashtime)
1033 {
1034     int i, j;
1035     int x1, x2, y1, y2;
1036
1037     if (!ds->started) {
1038         /*
1039          * The initial contents of the window are not guaranteed
1040          * and can vary with front ends. To be on the safe side,
1041          * all games should start by drawing a big background-
1042          * colour rectangle covering the whole window.
1043          */
1044         draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1045
1046         /*
1047          * Draw the numbers.
1048          */
1049         for (i = 0; i < ds->w + ds->h; i++) {
1050             int rowlen = state->rowlen[i];
1051             int *rowdata = state->rowdata + state->rowsize * i;
1052             int nfit;
1053
1054             /*
1055              * Normally I space the numbers out by the same
1056              * distance as the tile size. However, if there are
1057              * more numbers than available spaces, I have to squash
1058              * them up a bit.
1059              */
1060             nfit = max(rowlen, TLBORDER(ds->h))-1;
1061             assert(nfit > 0);
1062
1063             for (j = 0; j < rowlen; j++) {
1064                 int x, y;
1065                 char str[80];
1066
1067                 if (i < ds->w) {
1068                     x = TOCOORD(ds->w, i);
1069                     y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
1070                     y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1071                 } else {
1072                     y = TOCOORD(ds->h, i - ds->w);
1073                     x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
1074                     x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1075                 }
1076
1077                 sprintf(str, "%d", rowdata[j]);
1078                 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1079                           TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
1080                           COL_FULL, str);   /* FIXME: COL_TEXT */
1081             }
1082         }
1083
1084         /*
1085          * Draw the grid outline.
1086          */
1087         draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1088                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1089                   COL_GRID);
1090
1091         ds->started = TRUE;
1092
1093         draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
1094     }
1095
1096     if (ui->dragging) {
1097         x1 = min(ui->drag_start_x, ui->drag_end_x);
1098         x2 = max(ui->drag_start_x, ui->drag_end_x);
1099         y1 = min(ui->drag_start_y, ui->drag_end_y);
1100         y2 = max(ui->drag_start_y, ui->drag_end_y);
1101     } else {
1102         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1103     }
1104
1105     /*
1106      * Now draw any grid squares which have changed since last
1107      * redraw.
1108      */
1109     for (i = 0; i < ds->h; i++) {
1110         for (j = 0; j < ds->w; j++) {
1111             int val;
1112
1113             /*
1114              * Work out what state this square should be drawn in,
1115              * taking any current drag operation into account.
1116              */
1117             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1118                 val = ui->state;
1119             else
1120                 val = state->grid[i * state->w + j];
1121
1122             /*
1123              * Briefly invert everything twice during a completion
1124              * flash.
1125              */
1126             if (flashtime > 0 &&
1127                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1128                 val != GRID_UNKNOWN)
1129                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1130
1131             if (ds->visible[i * ds->w + j] != val) {
1132                 grid_square(fe, ds, i, j, val);
1133                 ds->visible[i * ds->w + j] = val;
1134             }
1135         }
1136     }
1137 }
1138
1139 static float game_anim_length(game_state *oldstate,
1140                               game_state *newstate, int dir, game_ui *ui)
1141 {
1142     return 0.0F;
1143 }
1144
1145 static float game_flash_length(game_state *oldstate,
1146                                game_state *newstate, int dir, game_ui *ui)
1147 {
1148     if (!oldstate->completed && newstate->completed &&
1149         !oldstate->cheated && !newstate->cheated)
1150         return FLASH_TIME;
1151     return 0.0F;
1152 }
1153
1154 static int game_wants_statusbar(void)
1155 {
1156     return FALSE;
1157 }
1158
1159 static int game_timing_state(game_state *state)
1160 {
1161     return TRUE;
1162 }
1163
1164 #ifdef COMBINED
1165 #define thegame pattern
1166 #endif
1167
1168 const struct game thegame = {
1169     "Pattern", "games.pattern",
1170     default_params,
1171     game_fetch_preset,
1172     decode_params,
1173     encode_params,
1174     free_params,
1175     dup_params,
1176     TRUE, game_configure, custom_params,
1177     validate_params,
1178     new_game_desc,
1179     validate_desc,
1180     new_game,
1181     dup_game,
1182     free_game,
1183     TRUE, solve_game,
1184     FALSE, game_text_format,
1185     new_ui,
1186     free_ui,
1187     encode_ui,
1188     decode_ui,
1189     game_changed_state,
1190     interpret_move,
1191     execute_move,
1192     game_size,
1193     game_colours,
1194     game_new_drawstate,
1195     game_free_drawstate,
1196     game_redraw,
1197     game_anim_length,
1198     game_flash_length,
1199     game_wants_statusbar,
1200     FALSE, game_timing_state,
1201     0,                                 /* mouse_priorities */
1202 };
1203
1204 #ifdef STANDALONE_SOLVER
1205
1206 /*
1207  * gcc -DSTANDALONE_SOLVER -o patternsolver pattern.c malloc.c
1208  */
1209
1210 #include <stdarg.h>
1211
1212 void frontend_default_colour(frontend *fe, float *output) {}
1213 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1214                int align, int colour, char *text) {}
1215 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
1216 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
1217 void draw_polygon(frontend *fe, int *coords, int npoints,
1218                   int fill, int colour) {}
1219 void clip(frontend *fe, int x, int y, int w, int h) {}
1220 void unclip(frontend *fe) {}
1221 void start_draw(frontend *fe) {}
1222 void draw_update(frontend *fe, int x, int y, int w, int h) {}
1223 void end_draw(frontend *fe) {}
1224 unsigned long random_upto(random_state *state, unsigned long limit)
1225 { assert(!"Shouldn't get randomness"); return 0; }
1226
1227 void fatal(char *fmt, ...)
1228 {
1229     va_list ap;
1230
1231     fprintf(stderr, "fatal error: ");
1232
1233     va_start(ap, fmt);
1234     vfprintf(stderr, fmt, ap);
1235     va_end(ap);
1236
1237     fprintf(stderr, "\n");
1238     exit(1);
1239 }
1240
1241 int main(int argc, char **argv)
1242 {
1243     game_params *p;
1244     game_state *s;
1245     int recurse = TRUE;
1246     char *id = NULL, *desc, *err;
1247     int y, x;
1248     int grade = FALSE;
1249
1250     while (--argc > 0) {
1251         char *p = *++argv;
1252         if (*p == '-') {
1253             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
1254             return 1;
1255         } else {
1256             id = p;
1257         }
1258     }
1259
1260     if (!id) {
1261         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1262         return 1;
1263     }
1264
1265     desc = strchr(id, ':');
1266     if (!desc) {
1267         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1268         return 1;
1269     }
1270     *desc++ = '\0';
1271
1272     p = default_params();
1273     decode_params(p, id);
1274     err = validate_desc(p, desc);
1275     if (err) {
1276         fprintf(stderr, "%s: %s\n", argv[0], err);
1277         return 1;
1278     }
1279     s = new_game(NULL, p, desc);
1280
1281     {
1282         int w = p->w, h = p->h, i, j, done_any, max;
1283         unsigned char *matrix, *workspace;
1284         int *rowdata;
1285
1286         matrix = snewn(w*h, unsigned char);
1287         max = max(w, h);
1288         workspace = snewn(max*3, unsigned char);
1289         rowdata = snewn(max+1, int);
1290
1291         memset(matrix, 0, w*h);
1292
1293         do {
1294             done_any = 0;
1295             for (i=0; i<h; i++) {
1296                 memcpy(rowdata, s->rowdata + s->rowsize*(w+i),
1297                        max*sizeof(int));
1298                 rowdata[s->rowlen[w+i]] = 0;
1299                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1300                                    matrix+i*w, w, 1, rowdata);
1301             }
1302             for (i=0; i<w; i++) {
1303                 memcpy(rowdata, s->rowdata + s->rowsize*i, max*sizeof(int));
1304                 rowdata[s->rowlen[i]] = 0;
1305                 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1306                                    matrix+i, h, w, rowdata);
1307             }
1308         } while (done_any);
1309
1310         for (i = 0; i < h; i++) {
1311             for (j = 0; j < w; j++) {
1312                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1313                          matrix[i*w+j] == BLOCK ? '#' :
1314                          matrix[i*w+j] == DOT ? '.' :
1315                          '!');
1316                 putchar(c);
1317             }
1318             printf("\n");
1319         }
1320     }
1321
1322     return 0;
1323 }
1324
1325 #endif