2 * fifteen.c: standard 15-puzzle.
14 #define PREFERRED_TILE_SIZE 48
15 #define TILE_SIZE (ds->tilesize)
16 #define BORDER (TILE_SIZE / 2)
17 #define HIGHLIGHT_WIDTH (TILE_SIZE / 20)
18 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
19 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
21 #define ANIM_TIME 0.13F
22 #define FLASH_FRAME 0.13F
24 #define X(state, i) ( (i) % (state)->w )
25 #define Y(state, i) ( (i) / (state)->w )
26 #define C(state, x, y) ( (y) * (state)->w + (x) )
45 int used_solve; /* used to suppress completion flash */
49 static game_params *default_params(void)
51 game_params *ret = snew(game_params);
58 static int game_fetch_preset(int i, char **name, game_params **params)
61 *params = default_params();
62 *name = dupstr("4x4");
68 static void free_params(game_params *params)
73 static game_params *dup_params(const game_params *params)
75 game_params *ret = snew(game_params);
76 *ret = *params; /* structure copy */
80 static void decode_params(game_params *ret, char const *string)
82 ret->w = ret->h = atoi(string);
83 while (*string && isdigit((unsigned char)*string)) string++;
86 ret->h = atoi(string);
90 static char *encode_params(const game_params *params, int full)
94 sprintf(data, "%dx%d", params->w, params->h);
99 static config_item *game_configure(const game_params *params)
104 ret = snewn(3, config_item);
106 ret[0].name = "Width";
107 ret[0].type = C_STRING;
108 sprintf(buf, "%d", params->w);
109 ret[0].sval = dupstr(buf);
112 ret[1].name = "Height";
113 ret[1].type = C_STRING;
114 sprintf(buf, "%d", params->h);
115 ret[1].sval = dupstr(buf);
126 static game_params *custom_params(const config_item *cfg)
128 game_params *ret = snew(game_params);
130 ret->w = atoi(cfg[0].sval);
131 ret->h = atoi(cfg[1].sval);
136 static char *validate_params(const game_params *params, int full)
138 if (params->w < 2 || params->h < 2)
139 return "Width and height must both be at least two";
144 static int perm_parity(int *perm, int n)
150 for (i = 0; i < n-1; i++)
151 for (j = i+1; j < n; j++)
152 if (perm[i] > perm[j])
158 static char *new_game_desc(const game_params *params, random_state *rs,
159 char **aux, int interactive)
162 int x1, x2, p1, p2, parity;
167 n = params->w * params->h;
169 tiles = snewn(n, int);
170 used = snewn(n, int);
172 for (i = 0; i < n; i++) {
177 gap = random_upto(rs, n);
182 * Place everything else except the last two tiles.
184 for (x = 0, i = n-1; i > 2; i--) {
185 int k = random_upto(rs, i);
188 for (j = 0; j < n; j++)
189 if (!used[j] && (k-- == 0))
192 assert(j < n && !used[j]);
195 while (tiles[x] >= 0)
202 * Find the last two locations, and the last two pieces.
204 while (tiles[x] >= 0)
209 while (tiles[x] >= 0)
214 for (i = 0; i < n; i++)
218 for (i = p1+1; i < n; i++)
224 * Determine the required parity of the overall permutation.
225 * This is the XOR of:
227 * - The chessboard parity ((x^y)&1) of the gap square. The
228 * bottom right counts as even.
230 * - The parity of n. (The target permutation is 1,...,n-1,0
231 * rather than 0,...,n-1; this is a cyclic permutation of
232 * the starting point and hence is odd iff n is even.)
234 parity = ((X(params, gap) - (params->w-1)) ^
235 (Y(params, gap) - (params->h-1)) ^
239 * Try the last two tiles one way round. If that fails, swap
244 if (perm_parity(tiles, n) != parity) {
247 assert(perm_parity(tiles, n) == parity);
251 * Now construct the game description, by describing the tile
252 * array as a simple sequence of comma-separated integers.
256 for (i = 0; i < n; i++) {
260 k = sprintf(buf, "%d,", tiles[i]);
262 ret = sresize(ret, retlen + k + 1, char);
263 strcpy(ret + retlen, buf);
266 ret[retlen-1] = '\0'; /* delete last comma */
274 static char *validate_desc(const game_params *params, const char *desc)
281 area = params->w * params->h;
285 used = snewn(area, int);
286 for (i = 0; i < area; i++)
289 for (i = 0; i < area; i++) {
293 if (*p < '0' || *p > '9') {
294 err = "Not enough numbers in string";
297 while (*p >= '0' && *p <= '9')
299 if (i < area-1 && *p != ',') {
300 err = "Expected comma after number";
303 else if (i == area-1 && *p) {
304 err = "Excess junk at end of string";
308 if (n < 0 || n >= area) {
309 err = "Number out of range";
313 err = "Number used twice";
318 if (*p) p++; /* eat comma */
326 static game_state *new_game(midend *me, const game_params *params,
329 game_state *state = snew(game_state);
333 state->w = params->w;
334 state->h = params->h;
335 state->n = params->w * params->h;
336 state->tiles = snewn(state->n, int);
341 for (i = 0; i < state->n; i++) {
343 state->tiles[i] = atoi(p);
344 if (state->tiles[i] == 0)
346 while (*p && *p != ',')
348 if (*p) p++; /* eat comma */
351 assert(state->tiles[state->gap_pos] == 0);
353 state->completed = state->movecount = 0;
354 state->used_solve = FALSE;
359 static game_state *dup_game(const game_state *state)
361 game_state *ret = snew(game_state);
366 ret->tiles = snewn(state->w * state->h, int);
367 memcpy(ret->tiles, state->tiles, state->w * state->h * sizeof(int));
368 ret->gap_pos = state->gap_pos;
369 ret->completed = state->completed;
370 ret->movecount = state->movecount;
371 ret->used_solve = state->used_solve;
376 static void free_game(game_state *state)
382 static char *solve_game(const game_state *state, const game_state *currstate,
383 const char *aux, char **error)
388 static int game_can_format_as_text_now(const game_params *params)
393 static char *game_text_format(const game_state *state)
395 char *ret, *p, buf[80];
396 int x, y, col, maxlen;
399 * First work out how many characters we need to display each
402 col = sprintf(buf, "%d", state->n-1);
405 * Now we know the exact total size of the grid we're going to
406 * produce: it's got h rows, each containing w lots of col, w-1
407 * spaces and a trailing newline.
409 maxlen = state->h * state->w * (col+1);
411 ret = snewn(maxlen+1, char);
414 for (y = 0; y < state->h; y++) {
415 for (x = 0; x < state->w; x++) {
416 int v = state->tiles[state->w*y+x];
418 sprintf(buf, "%*s", col, "");
420 sprintf(buf, "%*d", col, v);
430 assert(p - ret == maxlen);
435 static game_ui *new_ui(const game_state *state)
440 static void free_ui(game_ui *ui)
444 static char *encode_ui(const game_ui *ui)
449 static void decode_ui(game_ui *ui, const char *encoding)
453 static void game_changed_state(game_ui *ui, const game_state *oldstate,
454 const game_state *newstate)
458 struct game_drawstate {
465 static int flip_cursor(int button)
468 case CURSOR_UP: return CURSOR_DOWN;
469 case CURSOR_DOWN: return CURSOR_UP;
470 case CURSOR_LEFT: return CURSOR_RIGHT;
471 case CURSOR_RIGHT: return CURSOR_LEFT;
476 static void next_move_3x2(int ax, int ay, int bx, int by,
477 int gx, int gy, int *dx, int *dy)
479 /* When w = 3 and h = 2 and the tile going in the top left corner
480 * is at (ax, ay) and the tile going in the bottom left corner is
481 * at (bx, by) and the blank tile is at (gx, gy), how do you move? */
483 /* Hard-coded shortest solutions. Sorry. */
484 static const unsigned char move[120] = {
509 static const struct { int dx, dy; } d[4] = {{+1,0},{-1,0},{0,+1},{0,-1}};
511 int ea = 3*ay + ax, eb = 3*by + bx, eg = 3*gy + gx, v;
515 v = move[ea + eb*6 + eg*5*6];
520 static void next_move(int nx, int ny, int ox, int oy, int gx, int gy,
521 int tx, int ty, int w, int *dx, int *dy)
523 const int to_tile_x = (gx < nx ? +1 : -1);
524 const int to_goal_x = (gx < tx ? +1 : -1);
525 const int gap_x_on_goal_side = ((nx-tx) * (nx-gx) > 0);
527 assert (nx != tx || ny != ty); /* not already in place */
528 assert (nx != gx || ny != gy); /* not placing the gap */
529 assert (ty <= ny); /* because we're greedy (and flipping) */
530 assert (ty <= gy); /* because we're greedy (and flipping) */
532 /* TODO: define a termination function. Idea: 0 if solved, or
533 * the number of moves to solve the next piece plus the number of
534 * further unsolved pieces times an upper bound on the number of
535 * moves required to solve any piece. If such a function can be
536 * found, we have (termination && (termination => correctness)).
537 * The catch is our temporary disturbance of 2x3 corners. */
539 /* handles end-of-row, when 3 and 4 are in the top right 2x3 box */
541 ny <= ty + 2 && (nx == tx || nx == tx + 1) &&
542 oy <= ty + 2 && (ox == tx || ox == tx + 1) &&
543 gy <= ty + 2 && (gx == tx || gx == tx + 1))
545 next_move_3x2(oy - ty, tx + 1 - ox,
546 ny - ty, tx + 1 - nx,
547 gy - ty, tx + 1 - gx, dy, dx);
553 if (ny <= ty + 2 && (nx == tx || nx == tx - 1) &&
554 gy <= ty + 2 && (gx == tx || gx == tx - 1)) {
555 next_move_3x2(ny - ty, tx - nx, 0, 1, gy - ty, tx - gx, dy, dx);
559 else if (nx != tx || ny != ty + 1) {
560 next_move((w - 1) - nx, ny, -1, -1, (w - 1) - gx, gy,
561 0, ty + 1, -1, dx, dy);
570 /* note that *dy = -1 is unsafe when gy = ty + 1 and gx < tx */
572 if (nx == gx || (gy == ty && gx == tx))
574 else if (!gap_x_on_goal_side)
576 else if (ny - ty > abs(nx - tx))
581 if (nx == tx) /* then we know ny > ty */
582 if (gx > nx || ny > ty + 1)
583 *dy = -1; /* ... so this is safe */
586 else if (gap_x_on_goal_side)
588 else if (gy == ty || (gy == ty + 1 && gx < tx))
593 else if (nx == tx) /* gy > ny */
600 else if (gap_x_on_goal_side)
601 if (gy == ty + 1 && gx < tx)
606 else if (ny - ty > abs(nx - tx))
612 static int compute_hint(const game_state *state, int *out_x, int *out_y)
614 /* The overall solving process is this:
615 * 1. Find the next piece to be put in its place
616 * 2. Move it diagonally towards its place
617 * 3. Move it horizontally or vertically towards its place
618 * (Modulo the last two tiles at the end of each row/column)
621 int gx = X(state, state->gap_pos);
622 int gy = Y(state, state->gap_pos);
624 int tx, ty, nx, ny, ox, oy, /* {target,next,next2}_{x,y} */ i;
627 /* 1. Find the next piece
628 * if (there are no more unfinished columns than rows) {
629 * fill the top-most row, left to right
630 * } else { fill the left-most column, top to bottom }
632 const int w = state->w, h = state->h, n = w*h;
633 int next_piece = 0, next_piece_2 = 0, solr = 0, solc = 0;
634 int unsolved_rows = h, unsolved_cols = w;
639 while (solr < h && solc < w) {
640 int start, step, stop;
641 if (unsolved_cols <= unsolved_rows)
642 start = solr*w + solc, step = 1, stop = unsolved_cols;
644 start = solr*w + solc, step = w, stop = unsolved_rows;
645 for (i = 0; i < stop; ++i) {
646 const int j = start + i*step;
647 if (state->tiles[j] != j + 1) {
649 next_piece_2 = next_piece + step;
655 (unsolved_cols <= unsolved_rows)
656 ? (++solr, --unsolved_rows)
657 : (++solc, --unsolved_cols);
663 /* 2, 3. Move the next piece towards its place */
665 /* gx, gy already set */
666 tx = X(state, next_piece - 1); /* where we're going */
667 ty = Y(state, next_piece - 1);
668 for (i = 0; i < n && state->tiles[i] != next_piece; ++i);
669 nx = X(state, i); /* where we're at */
671 for (i = 0; i < n && state->tiles[i] != next_piece_2; ++i);
675 if (unsolved_cols <= unsolved_rows)
676 next_move(nx, ny, ox, oy, gx, gy, tx, ty, w, &dx, &dy);
678 next_move(ny, nx, oy, ox, gy, gx, ty, tx, h, &dy, &dx);
687 static char *interpret_move(const game_state *state, game_ui *ui,
688 const game_drawstate *ds,
689 int x, int y, int button)
691 int cx = X(state, state->gap_pos), nx = cx;
692 int cy = Y(state, state->gap_pos), ny = cy;
697 if (button == LEFT_BUTTON) {
700 if (nx < 0 || nx >= state->w || ny < 0 || ny >= state->h)
701 return NULL; /* out of bounds */
702 } else if (IS_CURSOR_MOVE(button)) {
703 static int invert_cursor = -1;
704 if (invert_cursor == -1) {
705 char *env = getenv("FIFTEEN_INVERT_CURSOR");
706 invert_cursor = (env && (env[0] == 'y' || env[0] == 'Y'));
708 button = flip_cursor(button); /* the default */
710 button = flip_cursor(button); /* undoes the first flip */
711 move_cursor(button, &nx, &ny, state->w, state->h, FALSE);
712 } else if ((button == 'h' || button == 'H') && !state->completed) {
713 if (!compute_hint(state, &nx, &ny))
714 return NULL; /* shouldn't happen, since ^^we^^checked^^ */
716 return NULL; /* no move */
719 * Any click location should be equal to the gap location
720 * in _precisely_ one coordinate.
722 if ((cx == nx) ^ (cy == ny)) {
723 sprintf(buf, "M%d,%d", nx, ny);
730 static game_state *execute_move(const game_state *from, const char *move)
732 int gx, gy, dx, dy, ux, uy, up, p;
735 if (!strcmp(move, "S")) {
738 ret = dup_game(from);
741 * Simply replace the grid with a solved one. For this game,
742 * this isn't a useful operation for actually telling the user
743 * what they should have done, but it is useful for
744 * conveniently being able to get hold of a clean state from
745 * which to practise manoeuvres.
747 for (i = 0; i < ret->n; i++)
748 ret->tiles[i] = (i+1) % ret->n;
749 ret->gap_pos = ret->n-1;
750 ret->used_solve = TRUE;
751 ret->completed = ret->movecount = 1;
756 gx = X(from, from->gap_pos);
757 gy = Y(from, from->gap_pos);
759 if (move[0] != 'M' ||
760 sscanf(move+1, "%d,%d", &dx, &dy) != 2 ||
761 (dx == gx && dy == gy) || (dx != gx && dy != gy) ||
762 dx < 0 || dx >= from->w || dy < 0 || dy >= from->h)
766 * Find the unit displacement from the original gap
767 * position towards this one.
769 ux = (dx < gx ? -1 : dx > gx ? +1 : 0);
770 uy = (dy < gy ? -1 : dy > gy ? +1 : 0);
771 up = C(from, ux, uy);
773 ret = dup_game(from);
775 ret->gap_pos = C(from, dx, dy);
776 assert(ret->gap_pos >= 0 && ret->gap_pos < ret->n);
778 ret->tiles[ret->gap_pos] = 0;
780 for (p = from->gap_pos; p != ret->gap_pos; p += up) {
781 assert(p >= 0 && p < from->n);
782 ret->tiles[p] = from->tiles[p + up];
787 * See if the game has been completed.
789 if (!ret->completed) {
790 ret->completed = ret->movecount;
791 for (p = 0; p < ret->n; p++)
792 if (ret->tiles[p] != (p < ret->n-1 ? p+1 : 0))
799 /* ----------------------------------------------------------------------
803 static void game_compute_size(const game_params *params, int tilesize,
806 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
807 struct { int tilesize; } ads, *ds = &ads;
808 ads.tilesize = tilesize;
810 *x = TILE_SIZE * params->w + 2 * BORDER;
811 *y = TILE_SIZE * params->h + 2 * BORDER;
814 static void game_set_size(drawing *dr, game_drawstate *ds,
815 const game_params *params, int tilesize)
817 ds->tilesize = tilesize;
820 static float *game_colours(frontend *fe, int *ncolours)
822 float *ret = snewn(3 * NCOLOURS, float);
825 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
827 for (i = 0; i < 3; i++)
828 ret[COL_TEXT * 3 + i] = 0.0;
830 *ncolours = NCOLOURS;
834 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
836 struct game_drawstate *ds = snew(struct game_drawstate);
842 ds->bgcolour = COL_BACKGROUND;
843 ds->tiles = snewn(ds->w*ds->h, int);
844 ds->tilesize = 0; /* haven't decided yet */
845 for (i = 0; i < ds->w*ds->h; i++)
851 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
857 static void draw_tile(drawing *dr, game_drawstate *ds, const game_state *state,
858 int x, int y, int tile, int flash_colour)
861 draw_rect(dr, x, y, TILE_SIZE, TILE_SIZE,
867 coords[0] = x + TILE_SIZE - 1;
868 coords[1] = y + TILE_SIZE - 1;
869 coords[2] = x + TILE_SIZE - 1;
872 coords[5] = y + TILE_SIZE - 1;
873 draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
877 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
879 draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
880 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
883 sprintf(str, "%d", tile);
884 draw_text(dr, x + TILE_SIZE/2, y + TILE_SIZE/2,
885 FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
888 draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
891 static void game_redraw(drawing *dr, game_drawstate *ds,
892 const game_state *oldstate, const game_state *state,
893 int dir, const game_ui *ui,
894 float animtime, float flashtime)
896 int i, pass, bgcolour;
899 int frame = (int)(flashtime / FLASH_FRAME);
900 bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
902 bgcolour = COL_BACKGROUND;
908 TILE_SIZE * state->w + 2 * BORDER,
909 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
910 draw_update(dr, 0, 0,
911 TILE_SIZE * state->w + 2 * BORDER,
912 TILE_SIZE * state->h + 2 * BORDER);
915 * Recessed area containing the whole puzzle.
917 coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
918 coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
919 coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
920 coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
921 coords[4] = coords[2] - TILE_SIZE;
922 coords[5] = coords[3] + TILE_SIZE;
923 coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
924 coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
925 coords[6] = coords[8] + TILE_SIZE;
926 coords[7] = coords[9] - TILE_SIZE;
927 draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
929 coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
930 coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
931 draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
937 * Now draw each tile. We do this in two passes to make
940 for (pass = 0; pass < 2; pass++) {
941 for (i = 0; i < state->n; i++) {
944 * Figure out what should be displayed at this
945 * location. It's either a simple tile, or it's a
946 * transition between two tiles (in which case we say
947 * -1 because it must always be drawn).
950 if (oldstate && oldstate->tiles[i] != state->tiles[i])
957 if (ds->bgcolour != bgcolour || /* always redraw when flashing */
958 ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1) {
962 * Figure out what to _actually_ draw, and where to
970 * On the first pass, just blank the tile.
973 x = COORD(X(state, i));
974 y = COORD(Y(state, i));
982 * Don't bother moving the gap; just don't
989 * Find the coordinates of this tile in the old and
992 x1 = COORD(X(state, i));
993 y1 = COORD(Y(state, i));
994 for (j = 0; j < oldstate->n; j++)
995 if (oldstate->tiles[j] == state->tiles[i])
997 assert(j < oldstate->n);
998 x0 = COORD(X(state, j));
999 y0 = COORD(Y(state, j));
1001 c = (animtime / ANIM_TIME);
1002 if (c < 0.0F) c = 0.0F;
1003 if (c > 1.0F) c = 1.0F;
1005 x = x0 + (int)(c * (x1 - x0));
1006 y = y0 + (int)(c * (y1 - y0));
1012 x = COORD(X(state, i));
1013 y = COORD(Y(state, i));
1016 draw_tile(dr, ds, state, x, y, t, bgcolour);
1021 ds->bgcolour = bgcolour;
1024 * Update the status bar.
1027 char statusbuf[256];
1030 * Don't show the new status until we're also showing the
1031 * new _state_ - after the game animation is complete.
1036 if (state->used_solve)
1037 sprintf(statusbuf, "Moves since auto-solve: %d",
1038 state->movecount - state->completed);
1040 sprintf(statusbuf, "%sMoves: %d",
1041 (state->completed ? "COMPLETED! " : ""),
1042 (state->completed ? state->completed : state->movecount));
1044 status_bar(dr, statusbuf);
1048 static float game_anim_length(const game_state *oldstate,
1049 const game_state *newstate, int dir, game_ui *ui)
1054 static float game_flash_length(const game_state *oldstate,
1055 const game_state *newstate, int dir, game_ui *ui)
1057 if (!oldstate->completed && newstate->completed &&
1058 !oldstate->used_solve && !newstate->used_solve)
1059 return 2 * FLASH_FRAME;
1064 static int game_status(const game_state *state)
1066 return state->completed ? +1 : 0;
1069 static int game_timing_state(const game_state *state, game_ui *ui)
1074 static void game_print_size(const game_params *params, float *x, float *y)
1078 static void game_print(drawing *dr, const game_state *state, int tilesize)
1083 #define thegame fifteen
1086 const struct game thegame = {
1087 "Fifteen", "games.fifteen", "fifteen",
1094 TRUE, game_configure, custom_params,
1102 TRUE, game_can_format_as_text_now, game_text_format,
1110 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1113 game_free_drawstate,
1118 FALSE, FALSE, game_print_size, game_print,
1119 TRUE, /* wants_statusbar */
1120 FALSE, game_timing_state,