Miscellaneous fixes from James Harvey's PalmOS porting work:
[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 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 game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
762 int x, int y, int button) {
763 game_state *ret;
764
765 button &= ~MOD_MASK;
766
767 x = FROMCOORD(from->w, x);
768 y = FROMCOORD(from->h, y);
769
770 if (x >= 0 && x < from->w && y >= 0 && y < from->h &&
771 (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
772 button == MIDDLE_BUTTON)) {
773
774 ui->dragging = TRUE;
775
776 if (button == LEFT_BUTTON) {
777 ui->drag = LEFT_DRAG;
778 ui->release = LEFT_RELEASE;
779 ui->state = GRID_FULL;
780 } else if (button == RIGHT_BUTTON) {
781 ui->drag = RIGHT_DRAG;
782 ui->release = RIGHT_RELEASE;
783 ui->state = GRID_EMPTY;
784 } else /* if (button == MIDDLE_BUTTON) */ {
785 ui->drag = MIDDLE_DRAG;
786 ui->release = MIDDLE_RELEASE;
787 ui->state = GRID_UNKNOWN;
788 }
789
790 ui->drag_start_x = ui->drag_end_x = x;
791 ui->drag_start_y = ui->drag_end_y = y;
792
793 return from; /* UI activity occurred */
794 }
795
796 if (ui->dragging && button == ui->drag) {
797 /*
798 * There doesn't seem much point in allowing a rectangle
799 * drag; people will generally only want to drag a single
800 * horizontal or vertical line, so we make that easy by
801 * snapping to it.
802 *
803 * Exception: if we're _middle_-button dragging to tag
804 * things as UNKNOWN, we may well want to trash an entire
805 * area and start over!
806 */
807 if (ui->state != GRID_UNKNOWN) {
808 if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
809 y = ui->drag_start_y;
810 else
811 x = ui->drag_start_x;
812 }
813
814 if (x < 0) x = 0;
815 if (y < 0) y = 0;
816 if (x >= from->w) x = from->w - 1;
817 if (y >= from->h) y = from->h - 1;
818
819 ui->drag_end_x = x;
820 ui->drag_end_y = y;
821
822 return from; /* UI activity occurred */
823 }
824
825 if (ui->dragging && button == ui->release) {
826 int x1, x2, y1, y2, xx, yy;
827 int move_needed = FALSE;
828
829 x1 = min(ui->drag_start_x, ui->drag_end_x);
830 x2 = max(ui->drag_start_x, ui->drag_end_x);
831 y1 = min(ui->drag_start_y, ui->drag_end_y);
832 y2 = max(ui->drag_start_y, ui->drag_end_y);
833
834 for (yy = y1; yy <= y2; yy++)
835 for (xx = x1; xx <= x2; xx++)
836 if (from->grid[yy * from->w + xx] != ui->state)
837 move_needed = TRUE;
838
839 ui->dragging = FALSE;
840
841 if (move_needed) {
842 ret = dup_game(from);
843 for (yy = y1; yy <= y2; yy++)
844 for (xx = x1; xx <= x2; xx++)
845 ret->grid[yy * ret->w + xx] = ui->state;
846
847 /*
848 * An actual change, so check to see if we've completed
849 * the game.
850 */
851 if (!ret->completed) {
852 int *rowdata = snewn(ret->rowsize, int);
853 int i, len;
854
855 ret->completed = TRUE;
856
857 for (i=0; i<ret->w; i++) {
858 len = compute_rowdata(rowdata,
859 ret->grid+i, ret->h, ret->w);
860 if (len != ret->rowlen[i] ||
861 memcmp(ret->rowdata+i*ret->rowsize, rowdata,
862 len * sizeof(int))) {
863 ret->completed = FALSE;
864 break;
865 }
866 }
867 for (i=0; i<ret->h; i++) {
868 len = compute_rowdata(rowdata,
869 ret->grid+i*ret->w, ret->w, 1);
870 if (len != ret->rowlen[i+ret->w] ||
871 memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
872 len * sizeof(int))) {
873 ret->completed = FALSE;
874 break;
875 }
876 }
877
878 sfree(rowdata);
879 }
880
881 return ret;
882 } else
883 return from; /* UI activity occurred */
884 }
885
886 return NULL;
887 }
888
889 /* ----------------------------------------------------------------------
890 * Drawing routines.
891 */
892
893 struct game_drawstate {
894 int started;
895 int w, h;
896 unsigned char *visible;
897 };
898
899 static void game_size(game_params *params, int *x, int *y)
900 {
901 *x = SIZE(params->w);
902 *y = SIZE(params->h);
903 }
904
905 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
906 {
907 float *ret = snewn(3 * NCOLOURS, float);
908
909 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
910
911 ret[COL_GRID * 3 + 0] = 0.3F;
912 ret[COL_GRID * 3 + 1] = 0.3F;
913 ret[COL_GRID * 3 + 2] = 0.3F;
914
915 ret[COL_UNKNOWN * 3 + 0] = 0.5F;
916 ret[COL_UNKNOWN * 3 + 1] = 0.5F;
917 ret[COL_UNKNOWN * 3 + 2] = 0.5F;
918
919 ret[COL_FULL * 3 + 0] = 0.0F;
920 ret[COL_FULL * 3 + 1] = 0.0F;
921 ret[COL_FULL * 3 + 2] = 0.0F;
922
923 ret[COL_EMPTY * 3 + 0] = 1.0F;
924 ret[COL_EMPTY * 3 + 1] = 1.0F;
925 ret[COL_EMPTY * 3 + 2] = 1.0F;
926
927 *ncolours = NCOLOURS;
928 return ret;
929 }
930
931 static game_drawstate *game_new_drawstate(game_state *state)
932 {
933 struct game_drawstate *ds = snew(struct game_drawstate);
934
935 ds->started = FALSE;
936 ds->w = state->w;
937 ds->h = state->h;
938 ds->visible = snewn(ds->w * ds->h, unsigned char);
939 memset(ds->visible, 255, ds->w * ds->h);
940
941 return ds;
942 }
943
944 static void game_free_drawstate(game_drawstate *ds)
945 {
946 sfree(ds->visible);
947 sfree(ds);
948 }
949
950 static void grid_square(frontend *fe, game_drawstate *ds,
951 int y, int x, int state)
952 {
953 int xl, xr, yt, yb;
954
955 draw_rect(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
956 TILE_SIZE, TILE_SIZE, COL_GRID);
957
958 xl = (x % 5 == 0 ? 1 : 0);
959 yt = (y % 5 == 0 ? 1 : 0);
960 xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
961 yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
962
963 draw_rect(fe, TOCOORD(ds->w, x) + 1 + xl, TOCOORD(ds->h, y) + 1 + yt,
964 TILE_SIZE - xl - xr - 1, TILE_SIZE - yt - yb - 1,
965 (state == GRID_FULL ? COL_FULL :
966 state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
967
968 draw_update(fe, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
969 TILE_SIZE, TILE_SIZE);
970 }
971
972 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
973 game_state *state, int dir, game_ui *ui,
974 float animtime, float flashtime)
975 {
976 int i, j;
977 int x1, x2, y1, y2;
978
979 if (!ds->started) {
980 /*
981 * The initial contents of the window are not guaranteed
982 * and can vary with front ends. To be on the safe side,
983 * all games should start by drawing a big background-
984 * colour rectangle covering the whole window.
985 */
986 draw_rect(fe, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
987
988 /*
989 * Draw the numbers.
990 */
991 for (i = 0; i < ds->w + ds->h; i++) {
992 int rowlen = state->rowlen[i];
993 int *rowdata = state->rowdata + state->rowsize * i;
994 int nfit;
995
996 /*
997 * Normally I space the numbers out by the same
998 * distance as the tile size. However, if there are
999 * more numbers than available spaces, I have to squash
1000 * them up a bit.
1001 */
1002 nfit = max(rowlen, TLBORDER(ds->h))-1;
1003 assert(nfit > 0);
1004
1005 for (j = 0; j < rowlen; j++) {
1006 int x, y;
1007 char str[80];
1008
1009 if (i < ds->w) {
1010 x = TOCOORD(ds->w, i);
1011 y = BORDER + TILE_SIZE * (TLBORDER(ds->h)-1);
1012 y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1013 } else {
1014 y = TOCOORD(ds->h, i - ds->w);
1015 x = BORDER + TILE_SIZE * (TLBORDER(ds->w)-1);
1016 x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(ds->h)-1) / nfit;
1017 }
1018
1019 sprintf(str, "%d", rowdata[j]);
1020 draw_text(fe, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1021 TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE,
1022 COL_FULL, str); /* FIXME: COL_TEXT */
1023 }
1024 }
1025
1026 /*
1027 * Draw the grid outline.
1028 */
1029 draw_rect(fe, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1030 ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1031 COL_GRID);
1032
1033 ds->started = TRUE;
1034
1035 draw_update(fe, 0, 0, SIZE(ds->w), SIZE(ds->h));
1036 }
1037
1038 if (ui->dragging) {
1039 x1 = min(ui->drag_start_x, ui->drag_end_x);
1040 x2 = max(ui->drag_start_x, ui->drag_end_x);
1041 y1 = min(ui->drag_start_y, ui->drag_end_y);
1042 y2 = max(ui->drag_start_y, ui->drag_end_y);
1043 } else {
1044 x1 = x2 = y1 = y2 = -1; /* placate gcc warnings */
1045 }
1046
1047 /*
1048 * Now draw any grid squares which have changed since last
1049 * redraw.
1050 */
1051 for (i = 0; i < ds->h; i++) {
1052 for (j = 0; j < ds->w; j++) {
1053 int val;
1054
1055 /*
1056 * Work out what state this square should be drawn in,
1057 * taking any current drag operation into account.
1058 */
1059 if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1060 val = ui->state;
1061 else
1062 val = state->grid[i * state->w + j];
1063
1064 /*
1065 * Briefly invert everything twice during a completion
1066 * flash.
1067 */
1068 if (flashtime > 0 &&
1069 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1070 val != GRID_UNKNOWN)
1071 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1072
1073 if (ds->visible[i * ds->w + j] != val) {
1074 grid_square(fe, ds, i, j, val);
1075 ds->visible[i * ds->w + j] = val;
1076 }
1077 }
1078 }
1079 }
1080
1081 static float game_anim_length(game_state *oldstate,
1082 game_state *newstate, int dir, game_ui *ui)
1083 {
1084 return 0.0F;
1085 }
1086
1087 static float game_flash_length(game_state *oldstate,
1088 game_state *newstate, int dir, game_ui *ui)
1089 {
1090 if (!oldstate->completed && newstate->completed &&
1091 !oldstate->cheated && !newstate->cheated)
1092 return FLASH_TIME;
1093 return 0.0F;
1094 }
1095
1096 static int game_wants_statusbar(void)
1097 {
1098 return FALSE;
1099 }
1100
1101 static int game_timing_state(game_state *state)
1102 {
1103 return TRUE;
1104 }
1105
1106 #ifdef COMBINED
1107 #define thegame pattern
1108 #endif
1109
1110 const struct game thegame = {
1111 "Pattern", "games.pattern",
1112 default_params,
1113 game_fetch_preset,
1114 decode_params,
1115 encode_params,
1116 free_params,
1117 dup_params,
1118 TRUE, game_configure, custom_params,
1119 validate_params,
1120 new_game_desc,
1121 game_free_aux_info,
1122 validate_desc,
1123 new_game,
1124 dup_game,
1125 free_game,
1126 TRUE, solve_game,
1127 FALSE, game_text_format,
1128 new_ui,
1129 free_ui,
1130 make_move,
1131 game_size,
1132 game_colours,
1133 game_new_drawstate,
1134 game_free_drawstate,
1135 game_redraw,
1136 game_anim_length,
1137 game_flash_length,
1138 game_wants_statusbar,
1139 FALSE, game_timing_state,
1140 0, /* mouse_priorities */
1141 };
1142
1143 #ifdef STANDALONE_SOLVER
1144
1145 /*
1146 * gcc -DSTANDALONE_SOLVER -o patternsolver pattern.c malloc.c
1147 */
1148
1149 #include <stdarg.h>
1150
1151 void frontend_default_colour(frontend *fe, float *output) {}
1152 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
1153 int align, int colour, char *text) {}
1154 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
1155 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
1156 void draw_polygon(frontend *fe, int *coords, int npoints,
1157 int fill, int colour) {}
1158 void clip(frontend *fe, int x, int y, int w, int h) {}
1159 void unclip(frontend *fe) {}
1160 void start_draw(frontend *fe) {}
1161 void draw_update(frontend *fe, int x, int y, int w, int h) {}
1162 void end_draw(frontend *fe) {}
1163 unsigned long random_upto(random_state *state, unsigned long limit)
1164 { assert(!"Shouldn't get randomness"); return 0; }
1165
1166 void fatal(char *fmt, ...)
1167 {
1168 va_list ap;
1169
1170 fprintf(stderr, "fatal error: ");
1171
1172 va_start(ap, fmt);
1173 vfprintf(stderr, fmt, ap);
1174 va_end(ap);
1175
1176 fprintf(stderr, "\n");
1177 exit(1);
1178 }
1179
1180 int main(int argc, char **argv)
1181 {
1182 game_params *p;
1183 game_state *s;
1184 int recurse = TRUE;
1185 char *id = NULL, *desc, *err;
1186 int y, x;
1187 int grade = FALSE;
1188
1189 while (--argc > 0) {
1190 char *p = *++argv;
1191 if (*p == '-') {
1192 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
1193 return 1;
1194 } else {
1195 id = p;
1196 }
1197 }
1198
1199 if (!id) {
1200 fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1201 return 1;
1202 }
1203
1204 desc = strchr(id, ':');
1205 if (!desc) {
1206 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1207 return 1;
1208 }
1209 *desc++ = '\0';
1210
1211 p = default_params();
1212 decode_params(p, id);
1213 err = validate_desc(p, desc);
1214 if (err) {
1215 fprintf(stderr, "%s: %s\n", argv[0], err);
1216 return 1;
1217 }
1218 s = new_game(NULL, p, desc);
1219
1220 {
1221 int w = p->w, h = p->h, i, j, done_any, max;
1222 unsigned char *matrix, *workspace;
1223 int *rowdata;
1224
1225 matrix = snewn(w*h, unsigned char);
1226 max = max(w, h);
1227 workspace = snewn(max*3, unsigned char);
1228 rowdata = snewn(max+1, int);
1229
1230 memset(matrix, 0, w*h);
1231
1232 do {
1233 done_any = 0;
1234 for (i=0; i<h; i++) {
1235 memcpy(rowdata, s->rowdata + s->rowsize*(w+i),
1236 max*sizeof(int));
1237 rowdata[s->rowlen[w+i]] = 0;
1238 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1239 matrix+i*w, w, 1, rowdata);
1240 }
1241 for (i=0; i<w; i++) {
1242 memcpy(rowdata, s->rowdata + s->rowsize*i, max*sizeof(int));
1243 rowdata[s->rowlen[i]] = 0;
1244 done_any |= do_row(workspace, workspace+max, workspace+2*max,
1245 matrix+i, h, w, rowdata);
1246 }
1247 } while (done_any);
1248
1249 for (i = 0; i < h; i++) {
1250 for (j = 0; j < w; j++) {
1251 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1252 matrix[i*w+j] == BLOCK ? '#' :
1253 matrix[i*w+j] == DOT ? '.' :
1254 '!');
1255 putchar(c);
1256 }
1257 printf("\n");
1258 }
1259 }
1260
1261 return 0;
1262 }
1263
1264 #endif