Re-architecting of the game backend interface. make_move() has been
[sgt/puzzles] / 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 struct game_aux_info {
470 int w, h;
471 unsigned char *grid;
472 };
473
474 static char *new_game_desc(game_params *params, random_state *rs,
475 game_aux_info **aux, int interactive)
476 {
477 unsigned char *grid;
478 int i, j, max, rowlen, *rowdata;
479 char intbuf[80], *desc;
480 int desclen, descpos;
481
482 grid = generate_soluble(rs, params->w, params->h);
483 max = max(params->w, params->h);
484 rowdata = snewn(max, int);
485
486 /*
487 * Save the solved game in an aux_info.
488 */
489 {
490 game_aux_info *ai = snew(game_aux_info);
491
492 ai->w = params->w;
493 ai->h = params->h;
494 ai->grid = grid;
495
496 *aux = ai;
497 }
498
499 /*
500 * Seed is a slash-separated list of row contents; each row
501 * contents section is a dot-separated list of integers. Row
502 * contents are listed in the order (columns left to right,
503 * then rows top to bottom).
504 *
505 * Simplest way to handle memory allocation is to make two
506 * passes, first computing the seed size and then writing it
507 * out.
508 */
509 desclen = 0;
510 for (i = 0; i < params->w + params->h; i++) {
511 if (i < params->w)
512 rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
513 else
514 rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
515 params->w, 1);
516 if (rowlen > 0) {
517 for (j = 0; j < rowlen; j++) {
518 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
519 }
520 } else {
521 desclen++;
522 }
523 }
524 desc = snewn(desclen, char);
525 descpos = 0;
526 for (i = 0; i < params->w + params->h; i++) {
527 if (i < params->w)
528 rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
529 else
530 rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
531 params->w, 1);
532 if (rowlen > 0) {
533 for (j = 0; j < rowlen; j++) {
534 int len = sprintf(desc+descpos, "%d", rowdata[j]);
535 if (j+1 < rowlen)
536 desc[descpos + len] = '.';
537 else
538 desc[descpos + len] = '/';
539 descpos += len+1;
540 }
541 } else {
542 desc[descpos++] = '/';
543 }
544 }
545 assert(descpos == desclen);
546 assert(desc[desclen-1] == '/');
547 desc[desclen-1] = '\0';
548 sfree(rowdata);
549 return desc;
550 }
551
552 static void game_free_aux_info(game_aux_info *aux)
553 {
554 sfree(aux->grid);
555 sfree(aux);
556 }
557
558 static char *validate_desc(game_params *params, char *desc)
559 {
560 int i, n, rowspace;
561 char *p;
562
563 for (i = 0; i < params->w + params->h; i++) {
564 if (i < params->w)
565 rowspace = params->h + 1;
566 else
567 rowspace = params->w + 1;
568
569 if (*desc && isdigit((unsigned char)*desc)) {
570 do {
571 p = desc;
572 while (desc && isdigit((unsigned char)*desc)) desc++;
573 n = atoi(p);
574 rowspace -= n+1;
575
576 if (rowspace < 0) {
577 if (i < params->w)
578 return "at least one column contains more numbers than will fit";
579 else
580 return "at least one row contains more numbers than will fit";
581 }
582 } while (*desc++ == '.');
583 } else {
584 desc++; /* expect a slash immediately */
585 }
586
587 if (desc[-1] == '/') {
588 if (i+1 == params->w + params->h)
589 return "too many row/column specifications";
590 } else if (desc[-1] == '\0') {
591 if (i+1 < params->w + params->h)
592 return "too few row/column specifications";
593 } else
594 return "unrecognised character in game specification";
595 }
596
597 return NULL;
598 }
599
600 static game_state *new_game(midend_data *me, game_params *params, char *desc)
601 {
602 int i;
603 char *p;
604 game_state *state = snew(game_state);
605
606 state->w = params->w;
607 state->h = params->h;
608
609 state->grid = snewn(state->w * state->h, unsigned char);
610 memset(state->grid, GRID_UNKNOWN, state->w * state->h);
611
612 state->rowsize = max(state->w, state->h);
613 state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
614 state->rowlen = snewn(state->w + state->h, int);
615
616 state->completed = state->cheated = FALSE;
617
618 for (i = 0; i < params->w + params->h; i++) {
619 state->rowlen[i] = 0;
620 if (*desc && isdigit((unsigned char)*desc)) {
621 do {
622 p = desc;
623 while (desc && isdigit((unsigned char)*desc)) desc++;
624 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
625 atoi(p);
626 } while (*desc++ == '.');
627 } else {
628 desc++; /* expect a slash immediately */
629 }
630 }
631
632 return state;
633 }
634
635 static game_state *dup_game(game_state *state)
636 {
637 game_state *ret = snew(game_state);
638
639 ret->w = state->w;
640 ret->h = state->h;
641
642 ret->grid = snewn(ret->w * ret->h, unsigned char);
643 memcpy(ret->grid, state->grid, ret->w * ret->h);
644
645 ret->rowsize = state->rowsize;
646 ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
647 ret->rowlen = snewn(ret->w + ret->h, int);
648 memcpy(ret->rowdata, state->rowdata,
649 ret->rowsize * (ret->w + ret->h) * sizeof(int));
650 memcpy(ret->rowlen, state->rowlen,
651 (ret->w + ret->h) * sizeof(int));
652
653 ret->completed = state->completed;
654 ret->cheated = state->cheated;
655
656 return ret;
657 }
658
659 static void free_game(game_state *state)
660 {
661 sfree(state->rowdata);
662 sfree(state->rowlen);
663 sfree(state->grid);
664 sfree(state);
665 }
666
667 static char *solve_game(game_state *state, game_state *currstate,
668 game_aux_info *ai, char **error)
669 {
670 unsigned char *matrix;
671 int matrix_needs_freeing;
672 int full, empty;
673 int w = state->w, h = state->h;
674 int i;
675 char *ret;
676
677 /*
678 * If we already have the solved state in an aux_info, copy it
679 * out.
680 */
681 if (ai) {
682 assert(ai->w == w && ai->h == h);
683
684 matrix = ai->grid;
685 matrix_needs_freeing = FALSE;
686 full = GRID_FULL;
687 empty = GRID_EMPTY;
688 } else {
689 int done_any, max;
690 unsigned char *workspace;
691 int *rowdata;
692
693 matrix = snewn(w*h, unsigned char);
694 max = max(w, h);
695 workspace = snewn(max*3, unsigned char);
696 rowdata = snewn(max+1, int);
697
698 memset(matrix, 0, w*h);
699
700 do {
701 done_any = 0;
702 for (i=0; i<h; i++) {
703 memcpy(rowdata, state->rowdata + state->rowsize*(w+i),
704 max*sizeof(int));
705 rowdata[state->rowlen[w+i]] = 0;
706 done_any |= do_row(workspace, workspace+max, workspace+2*max,
707 matrix+i*w, w, 1, rowdata);
708 }
709 for (i=0; i<w; i++) {
710 memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
711 rowdata[state->rowlen[i]] = 0;
712 done_any |= do_row(workspace, workspace+max, workspace+2*max,
713 matrix+i, h, w, rowdata);
714 }
715 } while (done_any);
716
717 sfree(workspace);
718 sfree(rowdata);
719
720 for (i = 0; i < w*h; i++) {
721 if (matrix[i] != BLOCK && matrix[i] != DOT) {
722 sfree(matrix);
723 *error = "Solving algorithm cannot complete this puzzle";
724 return NULL;
725 }
726 }
727
728 matrix_needs_freeing = TRUE;
729 full = BLOCK;
730 empty = DOT;
731 }
732
733 ret = snewn(w*h+2, char);
734 ret[0] = 'S';
735 for (i = 0; i < w*h; i++) {
736 assert(matrix[i] == full || matrix[i] == empty);
737 ret[i+1] = (matrix[i] == full ? '1' : '0');
738 }
739 ret[w*h+1] = '\0';
740
741 if (matrix_needs_freeing)
742 sfree(matrix);
743
744 return ret;
745 }
746
747 static char *game_text_format(game_state *state)
748 {
749 return NULL;
750 }
751
752 struct game_ui {
753 int dragging;
754 int drag_start_x;
755 int drag_start_y;
756 int drag_end_x;
757 int drag_end_y;
758 int drag, release, state;
759 };
760
761 static game_ui *new_ui(game_state *state)
762 {
763 game_ui *ret;
764
765 ret = snew(game_ui);
766 ret->dragging = FALSE;
767
768 return ret;
769 }
770
771 static void free_ui(game_ui *ui)
772 {
773 sfree(ui);
774 }
775
776 static void game_changed_state(game_ui *ui, game_state *oldstate,
777 game_state *newstate)
778 {
779 }
780
781 struct game_drawstate {
782 int started;
783 int w, h;
784 int tilesize;
785 unsigned char *visible;
786 };
787
788 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
789 int x, int y, int button)
790 {
791 button &= ~MOD_MASK;
792
793 x = FROMCOORD(state->w, x);
794 y = FROMCOORD(state->h, y);
795
796 if (x >= 0 && x < state->w && y >= 0 && y < state->h &&
797 (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
798 button == MIDDLE_BUTTON)) {
799
800 ui->dragging = TRUE;
801
802 if (button == LEFT_BUTTON) {
803 ui->drag = LEFT_DRAG;
804 ui->release = LEFT_RELEASE;
805 ui->state = GRID_FULL;
806 } else if (button == RIGHT_BUTTON) {
807 ui->drag = RIGHT_DRAG;
808 ui->release = RIGHT_RELEASE;
809 ui->state = GRID_EMPTY;
810 } else /* if (button == MIDDLE_BUTTON) */ {
811 ui->drag = MIDDLE_DRAG;
812 ui->release = MIDDLE_RELEASE;
813 ui->state = GRID_UNKNOWN;
814 }
815
816 ui->drag_start_x = ui->drag_end_x = x;
817 ui->drag_start_y = ui->drag_end_y = y;
818
819 return ""; /* UI activity occurred */
820 }
821
822 if (ui->dragging && button == ui->drag) {
823 /*
824 * There doesn't seem much point in allowing a rectangle
825 * drag; people will generally only want to drag a single
826 * horizontal or vertical line, so we make that easy by
827 * snapping to it.
828 *
829 * Exception: if we're _middle_-button dragging to tag
830 * things as UNKNOWN, we may well want to trash an entire
831 * area and start over!
832 */
833 if (ui->state != GRID_UNKNOWN) {
834 if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
835 y = ui->drag_start_y;
836 else
837 x = ui->drag_start_x;
838 }
839
840 if (x < 0) x = 0;
841 if (y < 0) y = 0;
842 if (x >= state->w) x = state->w - 1;
843 if (y >= state->h) y = state->h - 1;
844
845 ui->drag_end_x = x;
846 ui->drag_end_y = y;
847
848 return ""; /* UI activity occurred */
849 }
850
851 if (ui->dragging && button == ui->release) {
852 int x1, x2, y1, y2, xx, yy;
853 int move_needed = FALSE;
854
855 x1 = min(ui->drag_start_x, ui->drag_end_x);
856 x2 = max(ui->drag_start_x, ui->drag_end_x);
857 y1 = min(ui->drag_start_y, ui->drag_end_y);
858 y2 = max(ui->drag_start_y, ui->drag_end_y);
859
860 for (yy = y1; yy <= y2; yy++)
861 for (xx = x1; xx <= x2; xx++)
862 if (state->grid[yy * state->w + xx] != ui->state)
863 move_needed = TRUE;
864
865 ui->dragging = FALSE;
866
867 if (move_needed) {
868 char buf[80];
869 sprintf(buf, "%c%d,%d,%d,%d",
870 (ui->state == GRID_FULL ? 'F' :
871 ui->state == GRID_EMPTY ? 'E' : 'U'),
872 x1, y1, x2-x1+1, y2-y1+1);
873 return dupstr(buf);
874 } else
875 return ""; /* UI activity occurred */
876 }
877
878 return NULL;
879 }
880
881 static game_state *execute_move(game_state *from, char *move)
882 {
883 game_state *ret;
884 int x1, x2, y1, y2, xx, yy;
885 int val;
886
887 if (move[0] == 'S' && strlen(move) == from->w * from->h + 1) {
888 int i;
889
890 ret = dup_game(from);
891
892 for (i = 0; i < ret->w * ret->h; i++)
893 ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
894
895 ret->completed = ret->cheated = TRUE;
896
897 return ret;
898 } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
899 sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
900 x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
901 y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
902
903 x2 += x1;
904 y2 += y1;
905 val = (move[0] == 'F' ? GRID_FULL :
906 move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
907
908 ret = dup_game(from);
909 for (yy = y1; yy < y2; yy++)
910 for (xx = x1; xx < x2; xx++)
911 ret->grid[yy * ret->w + xx] = val;
912
913 /*
914 * An actual change, so check to see if we've completed the
915 * game.
916 */
917 if (!ret->completed) {
918 int *rowdata = snewn(ret->rowsize, int);
919 int i, len;
920
921 ret->completed = TRUE;
922
923 for (i=0; i<ret->w; i++) {
924 len = compute_rowdata(rowdata,
925 ret->grid+i, ret->h, ret->w);
926 if (len != ret->rowlen[i] ||
927 memcmp(ret->rowdata+i*ret->rowsize, rowdata,
928 len * sizeof(int))) {
929 ret->completed = FALSE;
930 break;
931 }
932 }
933 for (i=0; i<ret->h; i++) {
934 len = compute_rowdata(rowdata,
935 ret->grid+i*ret->w, ret->w, 1);
936 if (len != ret->rowlen[i+ret->w] ||
937 memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
938 len * sizeof(int))) {
939 ret->completed = FALSE;
940 break;
941 }
942 }
943
944 sfree(rowdata);
945 }
946
947 return ret;
948 } else
949 return NULL;
950 }
951
952 /* ----------------------------------------------------------------------
953 * Drawing routines.
954 */
955
956 static void game_size(game_params *params, game_drawstate *ds,
957 int *x, int *y, int expand)
958 {
959 int ts;
960
961 ts = min(GETTILESIZE(params->w, *x), GETTILESIZE(params->h, *y));
962 if (expand)
963 ds->tilesize = ts;
964 else
965 ds->tilesize = min(ts, PREFERRED_TILE_SIZE);
966
967 *x = SIZE(params->w);
968 *y = SIZE(params->h);
969 }
970
971 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
972 {
973 float *ret = snewn(3 * NCOLOURS, float);
974
975 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
976
977 ret[COL_GRID * 3 + 0] = 0.3F;
978 ret[COL_GRID * 3 + 1] = 0.3F;
979 ret[COL_GRID * 3 + 2] = 0.3F;
980
981 ret[COL_UNKNOWN * 3 + 0] = 0.5F;
982 ret[COL_UNKNOWN * 3 + 1] = 0.5F;
983 ret[COL_UNKNOWN * 3 + 2] = 0.5F;
984
985 ret[COL_FULL * 3 + 0] = 0.0F;
986 ret[COL_FULL * 3 + 1] = 0.0F;
987 ret[COL_FULL * 3 + 2] = 0.0F;
988
989 ret[COL_EMPTY * 3 + 0] = 1.0F;
990 ret[COL_EMPTY * 3 + 1] = 1.0F;
991 ret[COL_EMPTY * 3 + 2] = 1.0F;
992
993 *ncolours = NCOLOURS;
994 return ret;
995 }
996
997 static game_drawstate *game_new_drawstate(game_state *state)
998 {
999 struct game_drawstate *ds = snew(struct game_drawstate);
1000
1001 ds->started = FALSE;
1002 ds->w = state->w;
1003 ds->h = state->h;
1004 ds->visible = snewn(ds->w * ds->h, unsigned char);
1005 ds->tilesize = 0; /* not decided yet */
1006 memset(ds->visible, 255, ds->w * ds->h);
1007
1008 return ds;
1009 }
1010
1011 static void game_free_drawstate(game_drawstate *ds)
1012 {
1013 sfree(ds->visible);
1014 sfree(ds);
1015 }
1016
1017 static void grid_square(frontend *fe, game_drawstate *ds,
1018 int y, int x, int state)
1019 {
1020 int xl, xr, yt, yb;
1021
1022 draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1023 TILE_SIZE, TILE_SIZE, COL_GRID);
1024
1025 xl = (x % 5 == 0 ? 1 : 0);
1026 yt = (y % 5 == 0 ? 1 : 0);
1027 xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1028 yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1029
1030 draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
1031 TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
1032 (state == GRID_FULL ? COL_FULL :
1033 state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1034
1035 draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1036 TILE_SIZE, TILE_SIZE);
1037 }
1038
1039 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1040 game_state *state, int dir, game_ui *ui,
1041 float animtime, float flashtime)
1042 {
1043 int i, j;
1044 int x1, x2, y1, y2;
1045
1046 if (!ds->started) {
1047 /*
1048 * The initial contents of the window are not guaranteed
1049 * and can vary with front ends. To be on the safe side,
1050 * all games should start by drawing a big background-
1051 * colour rectangle covering the whole window.
1052 */
1053 draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1054
1055 /*
1056 * Draw the numbers.
1057 */
1058 for (i = 0; i < ds->w + ds->h; i++) {
1059 int rowlen = state->rowlen[i];
1060 int *rowdata = state->rowdata + state->rowsize * i;
1061 int nfit;
1062
1063 /*
1064 * Normally I space the numbers out by the same
1065 * distance as the tile size. However, if there are
1066 * more numbers than available spaces, I have to squash
1067 * them up a bit.
1068 */
1069 nfit = max(rowlen, TLBORDER(ds->h))-1;
1070 assert(nfit > 0);
1071
1072 for (j = 0; j < rowlen; j++) {
1073 int x, y;
1074 char str[80];
1075
1076 if (i < ds->w) {
1077 x = TOCOORD(ds->w, i);
1078 y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
1079 y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1080 } else {
1081 y = TOCOORD(ds->h, i - ds->w);
1082 x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
1083 x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1084 }
1085
1086 sprintf(str, "%d", rowdata[j]);
1087 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1088 TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
1089 COL_FULL, str); /* FIXME: COL_TEXT */
1090 }
1091 }
1092
1093 /*
1094 * Draw the grid outline.
1095 */
1096 draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1097 ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1098 COL_GRID);
1099
1100 ds->started = TRUE;
1101
1102 draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
1103 }
1104
1105 if (ui->dragging) {
1106 x1 = min(ui->drag_start_x, ui->drag_end_x);
1107 x2 = max(ui->drag_start_x, ui->drag_end_x);
1108 y1 = min(ui->drag_start_y, ui->drag_end_y);
1109 y2 = max(ui->drag_start_y, ui->drag_end_y);
1110 } else {
1111 x1 = x2 = y1 = y2 = -1; /* placate gcc warnings */
1112 }
1113
1114 /*
1115 * Now draw any grid squares which have changed since last
1116 * redraw.
1117 */
1118 for (i = 0; i < ds->h; i++) {
1119 for (j = 0; j < ds->w; j++) {
1120 int val;
1121
1122 /*
1123 * Work out what state this square should be drawn in,
1124 * taking any current drag operation into account.
1125 */
1126 if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1127 val = ui->state;
1128 else
1129 val = state->grid[i * state->w + j];
1130
1131 /*
1132 * Briefly invert everything twice during a completion
1133 * flash.
1134 */
1135 if (flashtime > 0 &&
1136 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1137 val != GRID_UNKNOWN)
1138 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1139
1140 if (ds->visible[i * ds->w + j] != val) {
1141 grid_square(fe, ds, i, j, val);
1142 ds->visible[i * ds->w + j] = val;
1143 }
1144 }
1145 }
1146 }
1147
1148 static float game_anim_length(game_state *oldstate,
1149 game_state *newstate, int dir, game_ui *ui)
1150 {
1151 return 0.0F;
1152 }
1153
1154 static float game_flash_length(game_state *oldstate,
1155 game_state *newstate, int dir, game_ui *ui)
1156 {
1157 if (!oldstate->completed && newstate->completed &&
1158 !oldstate->cheated && !newstate->cheated)
1159 return FLASH_TIME;
1160 return 0.0F;
1161 }
1162
1163 static int game_wants_statusbar(void)
1164 {
1165 return FALSE;
1166 }
1167
1168 static int game_timing_state(game_state *state)
1169 {
1170 return TRUE;
1171 }
1172
1173 #ifdef COMBINED
1174 #define thegame pattern
1175 #endif
1176
1177 const struct game thegame = {
1178 "Pattern", "games.pattern",
1179 default_params,
1180 game_fetch_preset,
1181 decode_params,
1182 encode_params,
1183 free_params,
1184 dup_params,
1185 TRUE, game_configure, custom_params,
1186 validate_params,
1187 new_game_desc,
1188 game_free_aux_info,
1189 validate_desc,
1190 new_game,
1191 dup_game,
1192 free_game,
1193 TRUE, solve_game,
1194 FALSE, game_text_format,
1195 new_ui,
1196 free_ui,
1197 game_changed_state,
1198 interpret_move,
1199 execute_move,
1200 game_size,
1201 game_colours,
1202 game_new_drawstate,
1203 game_free_drawstate,
1204 game_redraw,
1205 game_anim_length,
1206 game_flash_length,
1207 game_wants_statusbar,
1208 FALSE, game_timing_state,
1209 0, /* mouse_priorities */
1210 };
1211
1212 #ifdef STANDALONE_SOLVER
1213
1214 /*
1215 * gcc -DSTANDALONE_SOLVER -o patternsolver pattern.c malloc.c
1216 */
1217
1218 #include <stdarg.h>
1219
1220 void frontend_default_colour(frontend *fe, float *output) {}
1221 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1222 int align, int colour, char *text) {}
1223 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
1224 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
1225 void draw_polygon(frontend *fe, int *coords, int npoints,
1226 int fill, int colour) {}
1227 void clip(frontend *fe, int x, int y, int w, int h) {}
1228 void unclip(frontend *fe) {}
1229 void start_draw(frontend *fe) {}
1230 void draw_update(frontend *fe, int x, int y, int w, int h) {}
1231 void end_draw(frontend *fe) {}
1232 unsigned long random_upto(random_state *state, unsigned long limit)
1233 { assert(!"Shouldn't get randomness"); return 0; }
1234
1235 void fatal(char *fmt, ...)
1236 {
1237 va_list ap;
1238
1239 fprintf(stderr, "fatal error: ");
1240
1241 va_start(ap, fmt);
1242 vfprintf(stderr, fmt, ap);
1243 va_end(ap);
1244
1245 fprintf(stderr, "\n");
1246 exit(1);
1247 }
1248
1249 int main(int argc, char **argv)
1250 {
1251 game_params *p;
1252 game_state *s;
1253 int recurse = TRUE;
1254 char *id = NULL, *desc, *err;
1255 int y, x;
1256 int grade = FALSE;
1257
1258 while (--argc > 0) {
1259 char *p = *++argv;
1260 if (*p == '-') {
1261 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
1262 return 1;
1263 } else {
1264 id = p;
1265 }
1266 }
1267
1268 if (!id) {
1269 fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1270 return 1;
1271 }
1272
1273 desc = strchr(id, ':');
1274 if (!desc) {
1275 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1276 return 1;
1277 }
1278 *desc++ = '\0';
1279
1280 p = default_params();
1281 decode_params(p, id);
1282 err = validate_desc(p, desc);
1283 if (err) {
1284 fprintf(stderr, "%s: %s\n", argv[0], err);
1285 return 1;
1286 }
1287 s = new_game(NULL, p, desc);
1288
1289 {
1290 int w = p->w, h = p->h, i, j, done_any, max;
1291 unsigned char *matrix, *workspace;
1292 int *rowdata;
1293
1294 matrix = snewn(w*h, unsigned char);
1295 max = max(w, h);
1296 workspace = snewn(max*3, unsigned char);
1297 rowdata = snewn(max+1, int);
1298
1299 memset(matrix, 0, w*h);
1300
1301 do {
1302 done_any = 0;
1303 for (i=0; i<h; i++) {
1304 memcpy(rowdata, s->rowdata + s->rowsize*(w+i),
1305 max*sizeof(int));
1306 rowdata[s->rowlen[w+i]] = 0;
1307 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1308 matrix+i*w, w, 1, rowdata);
1309 }
1310 for (i=0; i<w; i++) {
1311 memcpy(rowdata, s->rowdata + s->rowsize*i, max*sizeof(int));
1312 rowdata[s->rowlen[i]] = 0;
1313 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1314 matrix+i, h, w, rowdata);
1315 }
1316 } while (done_any);
1317
1318 for (i = 0; i < h; i++) {
1319 for (j = 0; j < w; j++) {
1320 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1321 matrix[i*w+j] == BLOCK ? '#' :
1322 matrix[i*w+j] == DOT ? '.' :
1323 '!');
1324 putchar(c);
1325 }
1326 printf("\n");
1327 }
1328 }
1329
1330 return 0;
1331 }
1332
1333 #endif