2 * pattern.c: the pattern-reconstruction game known as `nonograms'.
26 #define PREFERRED_TILE_SIZE 24
27 #define TILE_SIZE (ds->tilesize)
28 #define BORDER (3 * TILE_SIZE / 4)
29 #define TLBORDER(d) ( (d) / 5 + 2 )
30 #define GUTTER (TILE_SIZE / 2)
32 #define FROMCOORD(d, x) \
33 ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
35 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
36 #define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
38 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
44 #define GRID_UNKNOWN 2
52 int *rowdata, *rowlen;
53 int completed, cheated;
56 #define FLASH_TIME 0.13F
58 static game_params *default_params(void)
60 game_params *ret = snew(game_params);
67 static const struct game_params pattern_presets[] = {
77 static int game_fetch_preset(int i, char **name, game_params **params)
82 if (i < 0 || i >= lenof(pattern_presets))
85 ret = snew(game_params);
86 *ret = pattern_presets[i];
88 sprintf(str, "%dx%d", ret->w, ret->h);
95 static void free_params(game_params *params)
100 static game_params *dup_params(game_params *params)
102 game_params *ret = snew(game_params);
103 *ret = *params; /* structure copy */
107 static void decode_params(game_params *ret, char const *string)
109 char const *p = string;
112 while (*p && isdigit((unsigned char)*p)) p++;
116 while (*p && isdigit((unsigned char)*p)) p++;
122 static char *encode_params(game_params *params, int full)
127 len = sprintf(ret, "%dx%d", params->w, params->h);
128 assert(len < lenof(ret));
134 static config_item *game_configure(game_params *params)
139 ret = snewn(3, config_item);
141 ret[0].name = "Width";
142 ret[0].type = C_STRING;
143 sprintf(buf, "%d", params->w);
144 ret[0].sval = dupstr(buf);
147 ret[1].name = "Height";
148 ret[1].type = C_STRING;
149 sprintf(buf, "%d", params->h);
150 ret[1].sval = dupstr(buf);
161 static game_params *custom_params(config_item *cfg)
163 game_params *ret = snew(game_params);
165 ret->w = atoi(cfg[0].sval);
166 ret->h = atoi(cfg[1].sval);
171 static char *validate_params(game_params *params, int full)
173 if (params->w <= 0 || params->h <= 0)
174 return "Width and height must both be greater than zero";
178 /* ----------------------------------------------------------------------
179 * Puzzle generation code.
181 * For this particular puzzle, it seemed important to me to ensure
182 * a unique solution. I do this the brute-force way, by having a
183 * solver algorithm alongside the generator, and repeatedly
184 * generating a random grid until I find one whose solution is
185 * unique. It turns out that this isn't too onerous on a modern PC
186 * provided you keep grid size below around 30. Any offers of
187 * better algorithms, however, will be very gratefully received.
189 * Another annoyance of this approach is that it limits the
190 * available puzzles to those solvable by the algorithm I've used.
191 * My algorithm only ever considers a single row or column at any
192 * one time, which means it's incapable of solving the following
193 * difficult example (found by Bella Image around 1995/6, when she
194 * and I were both doing maths degrees):
208 * Obviously this cannot be solved by a one-row-or-column-at-a-time
209 * algorithm (it would require at least one row or column reading
210 * `2 1', `1 2', `3' or `4' to get started). However, it can be
211 * proved to have a unique solution: if the top left square were
212 * empty, then the only option for the top row would be to fill the
213 * two squares in the 1 columns, which would imply the squares
214 * below those were empty, leaving no place for the 2 in the second
215 * row. Contradiction. Hence the top left square is full, and the
216 * unique solution follows easily from that starting point.
218 * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
219 * it's useful to anyone.)
222 static int float_compare(const void *av, const void *bv)
224 const float *a = (const float *)av;
225 const float *b = (const float *)bv;
234 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
241 fgrid = snewn(w*h, float);
243 for (i = 0; i < h; i++) {
244 for (j = 0; j < w; j++) {
245 fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
250 * The above gives a completely random splattering of black and
251 * white cells. We want to gently bias this in favour of _some_
252 * reasonably thick areas of white and black, while retaining
253 * some randomness and fine detail.
255 * So we evolve the starting grid using a cellular automaton.
256 * Currently, I'm doing something very simple indeed, which is
257 * to set each square to the average of the surrounding nine
258 * cells (or the average of fewer, if we're on a corner).
260 for (step = 0; step < 1; step++) {
261 fgrid2 = snewn(w*h, float);
263 for (i = 0; i < h; i++) {
264 for (j = 0; j < w; j++) {
269 * Compute the average of the surrounding cells.
273 for (p = -1; p <= +1; p++) {
274 for (q = -1; q <= +1; q++) {
275 if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
278 * An additional special case not mentioned
279 * above: if a grid dimension is 2xn then
280 * we do not average across that dimension
281 * at all. Otherwise a 2x2 grid would
282 * contain four identical squares.
284 if ((h==2 && p!=0) || (w==2 && q!=0))
287 sx += fgrid[(i+p)*w+(j+q)];
292 fgrid2[i*w+j] = xbar;
300 fgrid2 = snewn(w*h, float);
301 memcpy(fgrid2, fgrid, w*h*sizeof(float));
302 qsort(fgrid2, w*h, sizeof(float), float_compare);
303 threshold = fgrid2[w*h/2];
306 for (i = 0; i < h; i++) {
307 for (j = 0; j < w; j++) {
308 retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
316 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
322 for (i = 0; i < len; i++) {
323 if (start[i*step] == GRID_FULL) {
325 while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
331 if (i < len && start[i*step] == GRID_UNKNOWN)
341 #define STILL_UNKNOWN 3
343 #ifdef STANDALONE_SOLVER
347 static int do_recurse(unsigned char *known, unsigned char *deduced,
349 unsigned char *minpos_done, unsigned char *maxpos_done,
350 unsigned char *minpos_ok, unsigned char *maxpos_ok,
352 int freespace, int ndone, int lowest)
357 /* This algorithm basically tries all possible ways the given rows of
358 * black blocks can be laid out in the row/column being examined.
359 * Special care is taken to avoid checking the tail of a row/column
360 * if the same conditions have already been checked during this recursion
361 * The algorithm also takes care to cut its losses as soon as an
362 * invalid (partial) solution is detected.
365 if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
366 if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
367 for (i=0; i<lowest; i++)
368 deduced[i] |= row[i];
370 return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
372 if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
373 if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
375 for (i=0; i<=freespace; i++) {
377 for (k=0; k<i; k++) {
378 if (known[j] == BLOCK) goto next_iter;
381 for (k=0; k<data[ndone]; k++) {
382 if (known[j] == DOT) goto next_iter;
386 if (known[j] == BLOCK) goto next_iter;
389 if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
390 minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
391 if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
392 if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
393 if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
398 return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
400 for (i=lowest; i<len; i++) {
401 if (known[i] == BLOCK) return FALSE;
404 for (i=0; i<len; i++)
405 deduced[i] |= row[i];
411 static int do_row(unsigned char *known, unsigned char *deduced,
413 unsigned char *minpos_done, unsigned char *maxpos_done,
414 unsigned char *minpos_ok, unsigned char *maxpos_ok,
415 unsigned char *start, int len, int step, int *data,
416 unsigned int *changed
417 #ifdef STANDALONE_SOLVER
418 , const char *rowcol, int index, int cluewid
422 int rowlen, i, freespace, done_any;
425 for (rowlen = 0; data[rowlen]; rowlen++) {
426 minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
427 maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
428 freespace -= data[rowlen]+1;
431 for (i = 0; i < len; i++) {
432 known[i] = start[i*step];
435 for (i = len - 1; i >= 0 && known[i] == DOT; i--)
438 do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok, maxpos_ok, data, len, freespace, 0, 0);
441 for (i=0; i<len; i++)
442 if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
443 start[i*step] = deduced[i];
444 if (changed) changed[i]++;
447 #ifdef STANDALONE_SOLVER
448 if (verbose && done_any) {
451 printf("%s %2d: [", rowcol, index);
452 for (thiscluewid = -1, i = 0; data[i]; i++)
453 thiscluewid += sprintf(buf, " %d", data[i]);
454 printf("%*s", cluewid - thiscluewid, "");
455 for (i = 0; data[i]; i++)
456 printf(" %d", data[i]);
458 for (i = 0; i < len; i++)
459 putchar(known[i] == BLOCK ? '#' :
460 known[i] == DOT ? '.' : '?');
462 for (i = 0; i < len; i++)
463 putchar(start[i*step] == BLOCK ? '#' :
464 start[i*step] == DOT ? '.' : '?');
471 static int solve_puzzle(game_state *state, unsigned char *grid, int w, int h,
472 unsigned char *matrix, unsigned char *workspace,
473 unsigned int *changed_h, unsigned int *changed_w,
475 #ifdef STANDALONE_SOLVER
485 assert((state!=NULL) ^ (grid!=NULL));
489 memset(matrix, 0, w*h);
491 /* For each column, compute how many squares can be deduced
492 * from just the row-data.
493 * Later, changed_* will hold how many squares were changed
494 * in every row/column in the previous iteration
495 * Changed_* is used to choose the next rows / cols to re-examine
497 for (i=0; i<h; i++) {
500 memcpy(rowdata, state->rowdata + state->rowsize*(w+i), max*sizeof(int));
501 rowdata[state->rowlen[w+i]] = 0;
503 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
505 for (j=0, freespace=w+1; rowdata[j]; j++) freespace -= rowdata[j] + 1;
506 for (j=0, changed_h[i]=0; rowdata[j]; j++)
507 if (rowdata[j] > freespace)
508 changed_h[i] += rowdata[j] - freespace;
510 for (i=0,max_h=0; i<h; i++)
511 if (changed_h[i] > max_h)
512 max_h = changed_h[i];
513 for (i=0; i<w; i++) {
516 memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
517 rowdata[state->rowlen[i]] = 0;
519 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
521 for (j=0, freespace=h+1; rowdata[j]; j++) freespace -= rowdata[j] + 1;
522 for (j=0, changed_w[i]=0; rowdata[j]; j++)
523 if (rowdata[j] > freespace)
524 changed_w[i] += rowdata[j] - freespace;
526 for (i=0,max_w=0; i<w; i++)
527 if (changed_w[i] > max_w)
528 max_w = changed_w[i];
531 * Process rows/columns individually. Deductions involving more than one
532 * row and/or column at a time are not supported.
533 * Take care to only process rows/columns which have been changed since they
534 * were previously processed.
535 * Also, prioritize rows/columns which have had the most changes since their
536 * previous processing, as they promise the greatest benefit.
537 * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
540 for (; max_h && max_h >= max_w; max_h--) {
541 for (i=0; i<h; i++) {
542 if (changed_h[i] >= max_h) {
544 memcpy(rowdata, state->rowdata + state->rowsize*(w+i), max*sizeof(int));
545 rowdata[state->rowlen[w+i]] = 0;
547 rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
549 do_row(workspace, workspace+max, workspace+2*max,
550 workspace+3*max, workspace+4*max,
551 workspace+5*max, workspace+6*max,
552 matrix+i*w, w, 1, rowdata, changed_w
553 #ifdef STANDALONE_SOLVER
554 , "row", i+1, cluewid
560 for (i=0,max_w=0; i<w; i++)
561 if (changed_w[i] > max_w)
562 max_w = changed_w[i];
564 for (; max_w && max_w >= max_h; max_w--) {
565 for (i=0; i<w; i++) {
566 if (changed_w[i] >= max_w) {
568 memcpy(rowdata, state->rowdata + state->rowsize*i, max*sizeof(int));
569 rowdata[state->rowlen[i]] = 0;
571 rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
573 do_row(workspace, workspace+max, workspace+2*max,
574 workspace+3*max, workspace+4*max,
575 workspace+5*max, workspace+6*max,
576 matrix+i, h, w, rowdata, changed_h
577 #ifdef STANDALONE_SOLVER
578 , "col", i+1, cluewid
584 for (i=0,max_h=0; i<h; i++)
585 if (changed_h[i] > max_h)
586 max_h = changed_h[i];
588 } while (max_h>0 || max_w>0);
591 for (i=0; i<h; i++) {
592 for (j=0; j<w; j++) {
593 if (matrix[i*w+j] == UNKNOWN)
601 static unsigned char *generate_soluble(random_state *rs, int w, int h)
603 int i, j, ok, ntries, max;
604 unsigned char *grid, *matrix, *workspace;
605 unsigned int *changed_h, *changed_w;
610 grid = snewn(w*h, unsigned char);
611 /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
612 matrix = snewn(w*h, unsigned char);
613 workspace = snewn(max*7, unsigned char);
614 changed_h = snewn(max+1, unsigned int);
615 changed_w = snewn(max+1, unsigned int);
616 rowdata = snewn(max+1, int);
623 generate(rs, w, h, grid);
626 * The game is a bit too easy if any row or column is
627 * completely black or completely white. An exception is
628 * made for rows/columns that are under 3 squares,
629 * otherwise nothing will ever be successfully generated.
633 for (i = 0; i < h; i++) {
635 for (j = 0; j < w; j++)
636 colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
642 for (j = 0; j < w; j++) {
644 for (i = 0; i < h; i++)
645 colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
653 ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
654 changed_h, changed_w, rowdata, 0);
665 static char *new_game_desc(const game_params *params, random_state *rs,
666 char **aux, int interactive)
669 int i, j, max, rowlen, *rowdata;
670 char intbuf[80], *desc;
671 int desclen, descpos;
673 grid = generate_soluble(rs, params->w, params->h);
674 max = max(params->w, params->h);
675 rowdata = snewn(max, int);
678 * Save the solved game in aux.
681 char *ai = snewn(params->w * params->h + 2, char);
684 * String format is exactly the same as a solve move, so we
685 * can just dupstr this in solve_game().
690 for (i = 0; i < params->w * params->h; i++)
691 ai[i+1] = grid[i] ? '1' : '0';
693 ai[params->w * params->h + 1] = '\0';
699 * Seed is a slash-separated list of row contents; each row
700 * contents section is a dot-separated list of integers. Row
701 * contents are listed in the order (columns left to right,
702 * then rows top to bottom).
704 * Simplest way to handle memory allocation is to make two
705 * passes, first computing the seed size and then writing it
709 for (i = 0; i < params->w + params->h; i++) {
711 rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
713 rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
716 for (j = 0; j < rowlen; j++) {
717 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
723 desc = snewn(desclen, char);
725 for (i = 0; i < params->w + params->h; i++) {
727 rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
729 rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
732 for (j = 0; j < rowlen; j++) {
733 int len = sprintf(desc+descpos, "%d", rowdata[j]);
735 desc[descpos + len] = '.';
737 desc[descpos + len] = '/';
741 desc[descpos++] = '/';
744 assert(descpos == desclen);
745 assert(desc[desclen-1] == '/');
746 desc[desclen-1] = '\0';
752 static char *validate_desc(const game_params *params, char *desc)
757 for (i = 0; i < params->w + params->h; i++) {
759 rowspace = params->h + 1;
761 rowspace = params->w + 1;
763 if (*desc && isdigit((unsigned char)*desc)) {
766 while (*desc && isdigit((unsigned char)*desc)) desc++;
772 return "at least one column contains more numbers than will fit";
774 return "at least one row contains more numbers than will fit";
776 } while (*desc++ == '.');
778 desc++; /* expect a slash immediately */
781 if (desc[-1] == '/') {
782 if (i+1 == params->w + params->h)
783 return "too many row/column specifications";
784 } else if (desc[-1] == '\0') {
785 if (i+1 < params->w + params->h)
786 return "too few row/column specifications";
788 return "unrecognised character in game specification";
794 static game_state *new_game(midend *me, game_params *params, char *desc)
798 game_state *state = snew(game_state);
800 state->w = params->w;
801 state->h = params->h;
803 state->grid = snewn(state->w * state->h, unsigned char);
804 memset(state->grid, GRID_UNKNOWN, state->w * state->h);
806 state->rowsize = max(state->w, state->h);
807 state->rowdata = snewn(state->rowsize * (state->w + state->h), int);
808 state->rowlen = snewn(state->w + state->h, int);
810 state->completed = state->cheated = FALSE;
812 for (i = 0; i < params->w + params->h; i++) {
813 state->rowlen[i] = 0;
814 if (*desc && isdigit((unsigned char)*desc)) {
817 while (*desc && isdigit((unsigned char)*desc)) desc++;
818 state->rowdata[state->rowsize * i + state->rowlen[i]++] =
820 } while (*desc++ == '.');
822 desc++; /* expect a slash immediately */
829 static game_state *dup_game(game_state *state)
831 game_state *ret = snew(game_state);
836 ret->grid = snewn(ret->w * ret->h, unsigned char);
837 memcpy(ret->grid, state->grid, ret->w * ret->h);
839 ret->rowsize = state->rowsize;
840 ret->rowdata = snewn(ret->rowsize * (ret->w + ret->h), int);
841 ret->rowlen = snewn(ret->w + ret->h, int);
842 memcpy(ret->rowdata, state->rowdata,
843 ret->rowsize * (ret->w + ret->h) * sizeof(int));
844 memcpy(ret->rowlen, state->rowlen,
845 (ret->w + ret->h) * sizeof(int));
847 ret->completed = state->completed;
848 ret->cheated = state->cheated;
853 static void free_game(game_state *state)
855 sfree(state->rowdata);
856 sfree(state->rowlen);
861 static char *solve_game(game_state *state, game_state *currstate,
862 char *ai, char **error)
864 unsigned char *matrix;
865 int w = state->w, h = state->h;
869 unsigned char *workspace;
870 unsigned int *changed_h, *changed_w;
874 * If we already have the solved state in ai, copy it out.
880 matrix = snewn(w*h, unsigned char);
881 workspace = snewn(max*7, unsigned char);
882 changed_h = snewn(max+1, unsigned int);
883 changed_w = snewn(max+1, unsigned int);
884 rowdata = snewn(max+1, int);
886 ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
887 changed_h, changed_w, rowdata, 0);
896 *error = "Solving algorithm cannot complete this puzzle";
900 ret = snewn(w*h+2, char);
902 for (i = 0; i < w*h; i++) {
903 assert(matrix[i] == BLOCK || matrix[i] == DOT);
904 ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
913 static int game_can_format_as_text_now(game_params *params)
918 static char *game_text_format(game_state *state)
929 int drag, release, state;
930 int cur_x, cur_y, cur_visible;
933 static game_ui *new_ui(game_state *state)
938 ret->dragging = FALSE;
939 ret->cur_x = ret->cur_y = ret->cur_visible = 0;
944 static void free_ui(game_ui *ui)
949 static char *encode_ui(game_ui *ui)
954 static void decode_ui(game_ui *ui, char *encoding)
958 static void game_changed_state(game_ui *ui, game_state *oldstate,
959 game_state *newstate)
963 struct game_drawstate {
967 unsigned char *visible, *numcolours;
971 static char *interpret_move(game_state *state, game_ui *ui, const game_drawstate *ds,
972 int x, int y, int button)
976 x = FROMCOORD(state->w, x);
977 y = FROMCOORD(state->h, y);
979 if (x >= 0 && x < state->w && y >= 0 && y < state->h &&
980 (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
981 button == MIDDLE_BUTTON)) {
983 int currstate = state->grid[y * state->w + x];
988 if (button == LEFT_BUTTON) {
989 ui->drag = LEFT_DRAG;
990 ui->release = LEFT_RELEASE;
992 ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
994 ui->state = GRID_FULL;
996 } else if (button == RIGHT_BUTTON) {
997 ui->drag = RIGHT_DRAG;
998 ui->release = RIGHT_RELEASE;
1000 ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1002 ui->state = GRID_EMPTY;
1004 } else /* if (button == MIDDLE_BUTTON) */ {
1005 ui->drag = MIDDLE_DRAG;
1006 ui->release = MIDDLE_RELEASE;
1007 ui->state = GRID_UNKNOWN;
1010 ui->drag_start_x = ui->drag_end_x = x;
1011 ui->drag_start_y = ui->drag_end_y = y;
1012 ui->cur_visible = 0;
1014 return ""; /* UI activity occurred */
1017 if (ui->dragging && button == ui->drag) {
1019 * There doesn't seem much point in allowing a rectangle
1020 * drag; people will generally only want to drag a single
1021 * horizontal or vertical line, so we make that easy by
1024 * Exception: if we're _middle_-button dragging to tag
1025 * things as UNKNOWN, we may well want to trash an entire
1026 * area and start over!
1028 if (ui->state != GRID_UNKNOWN) {
1029 if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1030 y = ui->drag_start_y;
1032 x = ui->drag_start_x;
1037 if (x >= state->w) x = state->w - 1;
1038 if (y >= state->h) y = state->h - 1;
1043 return ""; /* UI activity occurred */
1046 if (ui->dragging && button == ui->release) {
1047 int x1, x2, y1, y2, xx, yy;
1048 int move_needed = FALSE;
1050 x1 = min(ui->drag_start_x, ui->drag_end_x);
1051 x2 = max(ui->drag_start_x, ui->drag_end_x);
1052 y1 = min(ui->drag_start_y, ui->drag_end_y);
1053 y2 = max(ui->drag_start_y, ui->drag_end_y);
1055 for (yy = y1; yy <= y2; yy++)
1056 for (xx = x1; xx <= x2; xx++)
1057 if (state->grid[yy * state->w + xx] != ui->state)
1060 ui->dragging = FALSE;
1064 sprintf(buf, "%c%d,%d,%d,%d",
1065 (char)(ui->state == GRID_FULL ? 'F' :
1066 ui->state == GRID_EMPTY ? 'E' : 'U'),
1067 x1, y1, x2-x1+1, y2-y1+1);
1070 return ""; /* UI activity occurred */
1073 if (IS_CURSOR_MOVE(button)) {
1074 move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, 0);
1075 ui->cur_visible = 1;
1078 if (IS_CURSOR_SELECT(button)) {
1079 int currstate = state->grid[ui->cur_y * state->w + ui->cur_x];
1083 if (!ui->cur_visible) {
1084 ui->cur_visible = 1;
1088 if (button == CURSOR_SELECT2)
1089 newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1090 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1092 newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1093 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1095 sprintf(buf, "%c%d,%d,%d,%d",
1096 (char)(newstate == GRID_FULL ? 'F' :
1097 newstate == GRID_EMPTY ? 'E' : 'U'),
1098 ui->cur_x, ui->cur_y, 1, 1);
1105 static game_state *execute_move(game_state *from, char *move)
1108 int x1, x2, y1, y2, xx, yy;
1111 if (move[0] == 'S' && strlen(move) == from->w * from->h + 1) {
1114 ret = dup_game(from);
1116 for (i = 0; i < ret->w * ret->h; i++)
1117 ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1119 ret->completed = ret->cheated = TRUE;
1122 } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1123 sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1124 x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
1125 y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
1129 val = (move[0] == 'F' ? GRID_FULL :
1130 move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1132 ret = dup_game(from);
1133 for (yy = y1; yy < y2; yy++)
1134 for (xx = x1; xx < x2; xx++)
1135 ret->grid[yy * ret->w + xx] = val;
1138 * An actual change, so check to see if we've completed the
1141 if (!ret->completed) {
1142 int *rowdata = snewn(ret->rowsize, int);
1145 ret->completed = TRUE;
1147 for (i=0; i<ret->w; i++) {
1148 len = compute_rowdata(rowdata,
1149 ret->grid+i, ret->h, ret->w);
1150 if (len != ret->rowlen[i] ||
1151 memcmp(ret->rowdata+i*ret->rowsize, rowdata,
1152 len * sizeof(int))) {
1153 ret->completed = FALSE;
1157 for (i=0; i<ret->h; i++) {
1158 len = compute_rowdata(rowdata,
1159 ret->grid+i*ret->w, ret->w, 1);
1160 if (len != ret->rowlen[i+ret->w] ||
1161 memcmp(ret->rowdata+(i+ret->w)*ret->rowsize, rowdata,
1162 len * sizeof(int))) {
1163 ret->completed = FALSE;
1176 /* ----------------------------------------------------------------------
1177 * Error-checking during gameplay.
1181 * The difficulty in error-checking Pattern is to make the error check
1182 * _weak_ enough. The most obvious way would be to check each row and
1183 * column by calling (a modified form of) do_row() to recursively
1184 * analyse the row contents against the clue set and see if the
1185 * GRID_UNKNOWNs could be filled in in any way that would end up
1186 * correct. However, this turns out to be such a strong error check as
1187 * to constitute a spoiler in many situations: you make a typo while
1188 * trying to fill in one row, and not only does the row light up to
1189 * indicate an error, but several columns crossed by the move also
1190 * light up and draw your attention to deductions you hadn't even
1191 * noticed you could make.
1193 * So instead I restrict error-checking to 'complete runs' within a
1194 * row, by which I mean contiguous sequences of GRID_FULL bounded at
1195 * both ends by either GRID_EMPTY or the ends of the row. We identify
1196 * all the complete runs in a row, and verify that _those_ are
1197 * consistent with the row's clue list. Sequences of complete runs
1198 * separated by solid GRID_EMPTY are required to match contiguous
1199 * sequences in the clue list, whereas if there's at least one
1200 * GRID_UNKNOWN between any two complete runs then those two need not
1201 * be contiguous in the clue list.
1203 * To simplify the edge cases, I pretend that the clue list for the
1204 * row is extended with a 0 at each end, and I also pretend that the
1205 * grid data for the row is extended with a GRID_EMPTY and a
1206 * zero-length run at each end. This permits the contiguity checker to
1207 * handle the fiddly end effects (e.g. if the first contiguous
1208 * sequence of complete runs in the grid matches _something_ in the
1209 * clue list but not at the beginning, this is allowable iff there's a
1210 * GRID_UNKNOWN before the first one) with minimal faff, since the end
1211 * effects just drop out as special cases of the normal inter-run
1212 * handling (in this code the above case is not 'at the end of the
1213 * clue list' at all, but between the implicit initial zero run and
1214 * the first nonzero one).
1216 * We must also be a little careful about how we search for a
1217 * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1218 * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1219 * for 1 in the clue list and find it at the very beginning. But now
1220 * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1221 * can't naively look at the next clue from the 1 we found, because
1222 * that'll be the second 1 and won't match. Instead, we must backtrack
1223 * by observing that the 2 we've just found must be contiguous with
1224 * the 1 we've already seen, so we search for the sequence (1 2) and
1225 * find it starting at the second 1. Now if we see a 3, we must
1226 * rethink again and search for (1 2 3).
1229 struct errcheck_state {
1231 * rowdata and rowlen point at the clue data for this row in the
1237 * rowpos indicates the lowest position where it would be valid to
1238 * see our next run length. It might be equal to rowlen,
1239 * indicating that the next run would have to be the terminating 0.
1243 * ncontig indicates how many runs we've seen in a contiguous
1244 * block. This is taken into account when searching for the next
1245 * run we find, unless ncontig is zeroed out first by encountering
1251 static int errcheck_found_run(struct errcheck_state *es, int r)
1253 /* Macro to handle the pretence that rowdata has a 0 at each end */
1254 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1257 * See if we can find this new run length at a position where it
1258 * also matches the last 'ncontig' runs we've seen.
1261 for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1263 if (ROWDATA(newpos) != r)
1266 for (i = 1; i <= es->ncontig; i++)
1267 if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1270 es->rowpos = newpos+1;
1282 static int check_errors(game_state *state, int i)
1284 int start, step, end, j;
1286 struct errcheck_state aes, *es = &aes;
1288 es->rowlen = state->rowlen[i];
1289 es->rowdata = state->rowdata + state->rowsize * i;
1290 /* Pretend that we've already encountered the initial zero run */
1297 end = start + step * state->h;
1299 start = (i - state->w) * state->w;
1301 end = start + step * state->w;
1305 for (j = start - step; j <= end; j += step) {
1306 if (j < start || j == end)
1309 val = state->grid[j];
1311 if (val == GRID_UNKNOWN) {
1314 } else if (val == GRID_FULL) {
1317 } else if (val == GRID_EMPTY) {
1319 if (!errcheck_found_run(es, runlen))
1320 return TRUE; /* error! */
1326 /* Signal end-of-row by sending errcheck_found_run the terminating
1327 * zero run, which will be marked as contiguous with the previous
1328 * run if and only if there hasn't been a GRID_UNKNOWN before. */
1329 if (!errcheck_found_run(es, 0))
1330 return TRUE; /* error at the last minute! */
1332 return FALSE; /* no error */
1335 /* ----------------------------------------------------------------------
1339 static void game_compute_size(game_params *params, int tilesize,
1342 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1343 struct { int tilesize; } ads, *ds = &ads;
1344 ads.tilesize = tilesize;
1346 *x = SIZE(params->w);
1347 *y = SIZE(params->h);
1350 static void game_set_size(drawing *dr, game_drawstate *ds,
1351 game_params *params, int tilesize)
1353 ds->tilesize = tilesize;
1356 static float *game_colours(frontend *fe, int *ncolours)
1358 float *ret = snewn(3 * NCOLOURS, float);
1361 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1363 for (i = 0; i < 3; i++) {
1364 ret[COL_GRID * 3 + i] = 0.3F;
1365 ret[COL_UNKNOWN * 3 + i] = 0.5F;
1366 ret[COL_TEXT * 3 + i] = 0.0F;
1367 ret[COL_FULL * 3 + i] = 0.0F;
1368 ret[COL_EMPTY * 3 + i] = 1.0F;
1370 ret[COL_CURSOR * 3 + 0] = 1.0F;
1371 ret[COL_CURSOR * 3 + 1] = 0.25F;
1372 ret[COL_CURSOR * 3 + 2] = 0.25F;
1373 ret[COL_ERROR * 3 + 0] = 1.0F;
1374 ret[COL_ERROR * 3 + 1] = 0.0F;
1375 ret[COL_ERROR * 3 + 2] = 0.0F;
1377 *ncolours = NCOLOURS;
1381 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1383 struct game_drawstate *ds = snew(struct game_drawstate);
1385 ds->started = FALSE;
1388 ds->visible = snewn(ds->w * ds->h, unsigned char);
1389 ds->tilesize = 0; /* not decided yet */
1390 memset(ds->visible, 255, ds->w * ds->h);
1391 ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1392 memset(ds->numcolours, 255, ds->w + ds->h);
1393 ds->cur_x = ds->cur_y = 0;
1398 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1404 static void grid_square(drawing *dr, game_drawstate *ds,
1405 int y, int x, int state, int cur)
1407 int xl, xr, yt, yb, dx, dy, dw, dh;
1409 draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1410 TILE_SIZE, TILE_SIZE, COL_GRID);
1412 xl = (x % 5 == 0 ? 1 : 0);
1413 yt = (y % 5 == 0 ? 1 : 0);
1414 xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1415 yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1417 dx = TOCOORD(ds->w, x) + 1 + xl;
1418 dy = TOCOORD(ds->h, y) + 1 + yt;
1419 dw = TILE_SIZE - xl - xr - 1;
1420 dh = TILE_SIZE - yt - yb - 1;
1422 draw_rect(dr, dx, dy, dw, dh,
1423 (state == GRID_FULL ? COL_FULL :
1424 state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1426 draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1427 draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1430 draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1431 TILE_SIZE, TILE_SIZE);
1435 * Draw the numbers for a single row or column.
1437 static void draw_numbers(drawing *dr, game_drawstate *ds, game_state *state,
1438 int i, int erase, int colour)
1440 int rowlen = state->rowlen[i];
1441 int *rowdata = state->rowdata + state->rowsize * i;
1447 draw_rect(dr, TOCOORD(state->w, i), 0,
1448 TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE,
1451 draw_rect(dr, 0, TOCOORD(state->h, i - state->w),
1452 BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE,
1458 * Normally I space the numbers out by the same distance as the
1459 * tile size. However, if there are more numbers than available
1460 * spaces, I have to squash them up a bit.
1463 nfit = TLBORDER(state->h);
1465 nfit = TLBORDER(state->w);
1466 nfit = max(rowlen, nfit) - 1;
1469 for (j = 0; j < rowlen; j++) {
1474 x = TOCOORD(state->w, i);
1475 y = BORDER + TILE_SIZE * (TLBORDER(state->h)-1);
1476 y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->h)-1) / nfit;
1478 y = TOCOORD(state->h, i - state->w);
1479 x = BORDER + TILE_SIZE * (TLBORDER(state->w)-1);
1480 x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->w)-1) / nfit;
1483 sprintf(str, "%d", rowdata[j]);
1484 draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1485 TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1489 draw_update(dr, TOCOORD(state->w, i), 0,
1490 TILE_SIZE, BORDER + TLBORDER(state->h) * TILE_SIZE);
1492 draw_update(dr, 0, TOCOORD(state->h, i - state->w),
1493 BORDER + TLBORDER(state->w) * TILE_SIZE, TILE_SIZE);
1497 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1498 game_state *state, int dir, game_ui *ui,
1499 float animtime, float flashtime)
1507 * The initial contents of the window are not guaranteed
1508 * and can vary with front ends. To be on the safe side,
1509 * all games should start by drawing a big background-
1510 * colour rectangle covering the whole window.
1512 draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1515 * Draw the grid outline.
1517 draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1518 ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1523 draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1527 x1 = min(ui->drag_start_x, ui->drag_end_x);
1528 x2 = max(ui->drag_start_x, ui->drag_end_x);
1529 y1 = min(ui->drag_start_y, ui->drag_end_y);
1530 y2 = max(ui->drag_start_y, ui->drag_end_y);
1532 x1 = x2 = y1 = y2 = -1; /* placate gcc warnings */
1535 if (ui->cur_visible) {
1536 cx = ui->cur_x; cy = ui->cur_y;
1540 cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1543 * Now draw any grid squares which have changed since last
1546 for (i = 0; i < ds->h; i++) {
1547 for (j = 0; j < ds->w; j++) {
1551 * Work out what state this square should be drawn in,
1552 * taking any current drag operation into account.
1554 if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2)
1557 val = state->grid[i * state->w + j];
1560 /* the cursor has moved; if we were the old or
1561 * the new cursor position we need to redraw. */
1562 if (j == cx && i == cy) cc = 1;
1563 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1567 * Briefly invert everything twice during a completion
1570 if (flashtime > 0 &&
1571 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1572 val != GRID_UNKNOWN)
1573 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1575 if (ds->visible[i * ds->w + j] != val || cc) {
1576 grid_square(dr, ds, i, j, val,
1577 (j == cx && i == cy));
1578 ds->visible[i * ds->w + j] = val;
1582 ds->cur_x = cx; ds->cur_y = cy;
1585 * Redraw any numbers which have changed their colour due to error
1588 for (i = 0; i < state->w + state->h; i++) {
1589 int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1590 if (ds->numcolours[i] != colour) {
1591 draw_numbers(dr, ds, state, i, TRUE, colour);
1592 ds->numcolours[i] = colour;
1597 static float game_anim_length(game_state *oldstate,
1598 game_state *newstate, int dir, game_ui *ui)
1603 static float game_flash_length(game_state *oldstate,
1604 game_state *newstate, int dir, game_ui *ui)
1606 if (!oldstate->completed && newstate->completed &&
1607 !oldstate->cheated && !newstate->cheated)
1612 static int game_status(game_state *state)
1614 return state->completed ? +1 : 0;
1617 static int game_timing_state(game_state *state, game_ui *ui)
1622 static void game_print_size(game_params *params, float *x, float *y)
1627 * I'll use 5mm squares by default.
1629 game_compute_size(params, 500, &pw, &ph);
1634 static void game_print(drawing *dr, game_state *state, int tilesize)
1636 int w = state->w, h = state->h;
1637 int ink = print_mono_colour(dr, 0);
1640 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1641 game_drawstate ads, *ds = &ads;
1642 game_set_size(dr, ds, NULL, tilesize);
1647 print_line_width(dr, TILE_SIZE / 16);
1648 draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1649 w*TILE_SIZE, h*TILE_SIZE, ink);
1654 for (x = 1; x < w; x++) {
1655 print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1656 draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1657 TOCOORD(w, x), TOCOORD(h, h), ink);
1659 for (y = 1; y < h; y++) {
1660 print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1661 draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1662 TOCOORD(w, w), TOCOORD(h, y), ink);
1668 for (i = 0; i < state->w + state->h; i++)
1669 draw_numbers(dr, ds, state, i, FALSE, ink);
1674 print_line_width(dr, TILE_SIZE / 128);
1675 for (y = 0; y < h; y++)
1676 for (x = 0; x < w; x++) {
1677 if (state->grid[y*w+x] == GRID_FULL)
1678 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1679 TILE_SIZE, TILE_SIZE, ink);
1680 else if (state->grid[y*w+x] == GRID_EMPTY)
1681 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1682 TOCOORD(h, y) + TILE_SIZE/2,
1683 TILE_SIZE/12, ink, ink);
1688 #define thegame pattern
1691 const struct game thegame = {
1692 "Pattern", "games.pattern", "pattern",
1699 TRUE, game_configure, custom_params,
1707 FALSE, game_can_format_as_text_now, game_text_format,
1715 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1718 game_free_drawstate,
1723 TRUE, FALSE, game_print_size, game_print,
1724 FALSE, /* wants_statusbar */
1725 FALSE, game_timing_state,
1726 REQUIRE_RBUTTON, /* flags */
1729 #ifdef STANDALONE_SOLVER
1731 int main(int argc, char **argv)
1735 char *id = NULL, *desc, *err;
1737 while (--argc > 0) {
1740 if (!strcmp(p, "-v")) {
1743 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1752 fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
1756 desc = strchr(id, ':');
1758 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1763 p = default_params();
1764 decode_params(p, id);
1765 err = validate_desc(p, desc);
1767 fprintf(stderr, "%s: %s\n", argv[0], err);
1770 s = new_game(NULL, p, desc);
1773 int w = p->w, h = p->h, i, j, max, cluewid = 0;
1774 unsigned char *matrix, *workspace;
1775 unsigned int *changed_h, *changed_w;
1778 matrix = snewn(w*h, unsigned char);
1780 workspace = snewn(max*7, unsigned char);
1781 changed_h = snewn(max+1, unsigned int);
1782 changed_w = snewn(max+1, unsigned int);
1783 rowdata = snewn(max+1, int);
1788 * Work out the maximum text width of the clue numbers
1789 * in a row or column, so we can print the solver's
1790 * working in a nicely lined up way.
1792 for (i = 0; i < (w+h); i++) {
1794 for (thiswid = -1, j = 0; j < s->rowlen[i]; j++)
1795 thiswid += sprintf(buf, " %d", s->rowdata[s->rowsize*i+j]);
1796 if (cluewid < thiswid)
1801 solve_puzzle(s, NULL, w, h, matrix, workspace,
1802 changed_h, changed_w, rowdata, cluewid);
1804 for (i = 0; i < h; i++) {
1805 for (j = 0; j < w; j++) {
1806 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
1807 matrix[i*w+j] == BLOCK ? '#' :
1808 matrix[i*w+j] == DOT ? '.' :
1821 /* vim: set shiftwidth=4 tabstop=8: */