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 char *interpret_move(const game_state *state, game_ui *ui,
477 const game_drawstate *ds,
478 int x, int y, int button)
480 int cx = X(state, state->gap_pos), nx = cx;
481 int cy = Y(state, state->gap_pos), ny = cy;
486 if (button == LEFT_BUTTON) {
489 if (nx < 0 || nx >= state->w || ny < 0 || ny >= state->h)
490 return NULL; /* out of bounds */
491 } else if (IS_CURSOR_MOVE(button)) {
492 static int invert_cursor = -1;
493 if (invert_cursor == -1) {
494 char *env = getenv("FIFTEEN_INVERT_CURSOR");
495 invert_cursor = (env && (env[0] == 'y' || env[0] == 'Y'));
497 button = flip_cursor(button); /* the default */
499 button = flip_cursor(button); /* undoes the first flip */
500 move_cursor(button, &nx, &ny, state->w, state->h, FALSE);
502 return NULL; /* no move */
505 * Any click location should be equal to the gap location
506 * in _precisely_ one coordinate.
508 if ((cx == nx) ^ (cy == ny)) {
509 sprintf(buf, "M%d,%d", nx, ny);
516 static game_state *execute_move(const game_state *from, const char *move)
518 int gx, gy, dx, dy, ux, uy, up, p;
521 if (!strcmp(move, "S")) {
524 ret = dup_game(from);
527 * Simply replace the grid with a solved one. For this game,
528 * this isn't a useful operation for actually telling the user
529 * what they should have done, but it is useful for
530 * conveniently being able to get hold of a clean state from
531 * which to practise manoeuvres.
533 for (i = 0; i < ret->n; i++)
534 ret->tiles[i] = (i+1) % ret->n;
535 ret->gap_pos = ret->n-1;
536 ret->used_solve = TRUE;
537 ret->completed = ret->movecount = 1;
542 gx = X(from, from->gap_pos);
543 gy = Y(from, from->gap_pos);
545 if (move[0] != 'M' ||
546 sscanf(move+1, "%d,%d", &dx, &dy) != 2 ||
547 (dx == gx && dy == gy) || (dx != gx && dy != gy) ||
548 dx < 0 || dx >= from->w || dy < 0 || dy >= from->h)
552 * Find the unit displacement from the original gap
553 * position towards this one.
555 ux = (dx < gx ? -1 : dx > gx ? +1 : 0);
556 uy = (dy < gy ? -1 : dy > gy ? +1 : 0);
557 up = C(from, ux, uy);
559 ret = dup_game(from);
561 ret->gap_pos = C(from, dx, dy);
562 assert(ret->gap_pos >= 0 && ret->gap_pos < ret->n);
564 ret->tiles[ret->gap_pos] = 0;
566 for (p = from->gap_pos; p != ret->gap_pos; p += up) {
567 assert(p >= 0 && p < from->n);
568 ret->tiles[p] = from->tiles[p + up];
573 * See if the game has been completed.
575 if (!ret->completed) {
576 ret->completed = ret->movecount;
577 for (p = 0; p < ret->n; p++)
578 if (ret->tiles[p] != (p < ret->n-1 ? p+1 : 0))
585 /* ----------------------------------------------------------------------
589 static void game_compute_size(const game_params *params, int tilesize,
592 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
593 struct { int tilesize; } ads, *ds = &ads;
594 ads.tilesize = tilesize;
596 *x = TILE_SIZE * params->w + 2 * BORDER;
597 *y = TILE_SIZE * params->h + 2 * BORDER;
600 static void game_set_size(drawing *dr, game_drawstate *ds,
601 const game_params *params, int tilesize)
603 ds->tilesize = tilesize;
606 static float *game_colours(frontend *fe, int *ncolours)
608 float *ret = snewn(3 * NCOLOURS, float);
611 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
613 for (i = 0; i < 3; i++)
614 ret[COL_TEXT * 3 + i] = 0.0;
616 *ncolours = NCOLOURS;
620 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
622 struct game_drawstate *ds = snew(struct game_drawstate);
628 ds->bgcolour = COL_BACKGROUND;
629 ds->tiles = snewn(ds->w*ds->h, int);
630 ds->tilesize = 0; /* haven't decided yet */
631 for (i = 0; i < ds->w*ds->h; i++)
637 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
643 static void draw_tile(drawing *dr, game_drawstate *ds, const game_state *state,
644 int x, int y, int tile, int flash_colour)
647 draw_rect(dr, x, y, TILE_SIZE, TILE_SIZE,
653 coords[0] = x + TILE_SIZE - 1;
654 coords[1] = y + TILE_SIZE - 1;
655 coords[2] = x + TILE_SIZE - 1;
658 coords[5] = y + TILE_SIZE - 1;
659 draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
663 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
665 draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
666 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
669 sprintf(str, "%d", tile);
670 draw_text(dr, x + TILE_SIZE/2, y + TILE_SIZE/2,
671 FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
674 draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
677 static void game_redraw(drawing *dr, game_drawstate *ds,
678 const game_state *oldstate, const game_state *state,
679 int dir, const game_ui *ui,
680 float animtime, float flashtime)
682 int i, pass, bgcolour;
685 int frame = (int)(flashtime / FLASH_FRAME);
686 bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
688 bgcolour = COL_BACKGROUND;
694 TILE_SIZE * state->w + 2 * BORDER,
695 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
696 draw_update(dr, 0, 0,
697 TILE_SIZE * state->w + 2 * BORDER,
698 TILE_SIZE * state->h + 2 * BORDER);
701 * Recessed area containing the whole puzzle.
703 coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
704 coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
705 coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
706 coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
707 coords[4] = coords[2] - TILE_SIZE;
708 coords[5] = coords[3] + TILE_SIZE;
709 coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
710 coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
711 coords[6] = coords[8] + TILE_SIZE;
712 coords[7] = coords[9] - TILE_SIZE;
713 draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
715 coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
716 coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
717 draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
723 * Now draw each tile. We do this in two passes to make
726 for (pass = 0; pass < 2; pass++) {
727 for (i = 0; i < state->n; i++) {
730 * Figure out what should be displayed at this
731 * location. It's either a simple tile, or it's a
732 * transition between two tiles (in which case we say
733 * -1 because it must always be drawn).
736 if (oldstate && oldstate->tiles[i] != state->tiles[i])
743 if (ds->bgcolour != bgcolour || /* always redraw when flashing */
744 ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1) {
748 * Figure out what to _actually_ draw, and where to
756 * On the first pass, just blank the tile.
759 x = COORD(X(state, i));
760 y = COORD(Y(state, i));
768 * Don't bother moving the gap; just don't
775 * Find the coordinates of this tile in the old and
778 x1 = COORD(X(state, i));
779 y1 = COORD(Y(state, i));
780 for (j = 0; j < oldstate->n; j++)
781 if (oldstate->tiles[j] == state->tiles[i])
783 assert(j < oldstate->n);
784 x0 = COORD(X(state, j));
785 y0 = COORD(Y(state, j));
787 c = (animtime / ANIM_TIME);
788 if (c < 0.0F) c = 0.0F;
789 if (c > 1.0F) c = 1.0F;
791 x = x0 + (int)(c * (x1 - x0));
792 y = y0 + (int)(c * (y1 - y0));
798 x = COORD(X(state, i));
799 y = COORD(Y(state, i));
802 draw_tile(dr, ds, state, x, y, t, bgcolour);
807 ds->bgcolour = bgcolour;
810 * Update the status bar.
816 * Don't show the new status until we're also showing the
817 * new _state_ - after the game animation is complete.
822 if (state->used_solve)
823 sprintf(statusbuf, "Moves since auto-solve: %d",
824 state->movecount - state->completed);
826 sprintf(statusbuf, "%sMoves: %d",
827 (state->completed ? "COMPLETED! " : ""),
828 (state->completed ? state->completed : state->movecount));
830 status_bar(dr, statusbuf);
834 static float game_anim_length(const game_state *oldstate,
835 const game_state *newstate, int dir, game_ui *ui)
840 static float game_flash_length(const game_state *oldstate,
841 const game_state *newstate, int dir, game_ui *ui)
843 if (!oldstate->completed && newstate->completed &&
844 !oldstate->used_solve && !newstate->used_solve)
845 return 2 * FLASH_FRAME;
850 static int game_status(const game_state *state)
852 return state->completed ? +1 : 0;
855 static int game_timing_state(const game_state *state, game_ui *ui)
860 static void game_print_size(const game_params *params, float *x, float *y)
864 static void game_print(drawing *dr, const game_state *state, int tilesize)
869 #define thegame fifteen
872 const struct game thegame = {
873 "Fifteen", "games.fifteen", "fifteen",
880 TRUE, game_configure, custom_params,
888 TRUE, game_can_format_as_text_now, game_text_format,
896 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
904 FALSE, FALSE, game_print_size, game_print,
905 TRUE, /* wants_statusbar */
906 FALSE, game_timing_state,