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