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