2 * sixteen.c: `16-puzzle', a sliding-tiles jigsaw which differs
3 * from the 15-puzzle in that you toroidally rotate a row or column
16 #define PREFERRED_TILE_SIZE 48
17 #define TILE_SIZE (ds->tilesize)
18 #define BORDER TILE_SIZE
19 #define HIGHLIGHT_WIDTH (TILE_SIZE / 20)
20 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
21 #define FROMCOORD(x) ( ((x) - BORDER + 2*TILE_SIZE) / TILE_SIZE - 2 )
23 #define ANIM_TIME 0.13F
24 #define FLASH_FRAME 0.13F
26 #define X(state, i) ( (i) % (state)->w )
27 #define Y(state, i) ( (i) / (state)->w )
28 #define C(state, x, y) ( (y) * (state)->w + (x) )
47 int used_solve; /* used to suppress completion flash */
48 int movecount, movetarget;
49 int last_movement_sense;
52 static game_params *default_params(void)
54 game_params *ret = snew(game_params);
62 static int game_fetch_preset(int i, char **name, game_params **params)
69 case 0: w = 3, h = 3; break;
70 case 1: w = 4, h = 3; break;
71 case 2: w = 4, h = 4; break;
72 case 3: w = 5, h = 4; break;
73 case 4: w = 5, h = 5; break;
74 default: return FALSE;
77 sprintf(buf, "%dx%d", w, h);
79 *params = ret = snew(game_params);
86 static void free_params(game_params *params)
91 static game_params *dup_params(game_params *params)
93 game_params *ret = snew(game_params);
94 *ret = *params; /* structure copy */
98 static void decode_params(game_params *ret, char const *string)
100 ret->w = ret->h = atoi(string);
102 while (*string && isdigit((unsigned char)*string)) string++;
103 if (*string == 'x') {
105 ret->h = atoi(string);
106 while (*string && isdigit((unsigned char)*string))
109 if (*string == 'm') {
111 ret->movetarget = atoi(string);
112 while (*string && isdigit((unsigned char)*string))
117 static char *encode_params(game_params *params, int full)
121 sprintf(data, "%dx%d", params->w, params->h);
122 /* Shuffle limit is part of the limited parameters, because we have to
123 * supply the target move count. */
124 if (params->movetarget)
125 sprintf(data + strlen(data), "m%d", params->movetarget);
130 static config_item *game_configure(game_params *params)
135 ret = snewn(4, config_item);
137 ret[0].name = "Width";
138 ret[0].type = C_STRING;
139 sprintf(buf, "%d", params->w);
140 ret[0].sval = dupstr(buf);
143 ret[1].name = "Height";
144 ret[1].type = C_STRING;
145 sprintf(buf, "%d", params->h);
146 ret[1].sval = dupstr(buf);
149 ret[2].name = "Number of shuffling moves";
150 ret[2].type = C_STRING;
151 sprintf(buf, "%d", params->movetarget);
152 ret[2].sval = dupstr(buf);
163 static game_params *custom_params(config_item *cfg)
165 game_params *ret = snew(game_params);
167 ret->w = atoi(cfg[0].sval);
168 ret->h = atoi(cfg[1].sval);
169 ret->movetarget = atoi(cfg[2].sval);
174 static char *validate_params(game_params *params, int full)
176 if (params->w < 2 || params->h < 2)
177 return "Width and height must both be at least two";
182 static int perm_parity(int *perm, int n)
188 for (i = 0; i < n-1; i++)
189 for (j = i+1; j < n; j++)
190 if (perm[i] > perm[j])
196 static char *new_game_desc(game_params *params, random_state *rs,
197 char **aux, int interactive)
205 n = params->w * params->h;
207 tiles = snewn(n, int);
209 if (params->movetarget) {
211 int max = (params->w > params->h ? params->w : params->h);
212 int *prevmoves = snewn(max, int);
215 * Shuffle the old-fashioned way, by making a series of
216 * single moves on the grid.
219 for (i = 0; i < n; i++)
222 for (i = 0; i < params->movetarget; i++) {
223 int start, offset, len, direction, index;
227 * Choose a move to make. We can choose from any row
231 j = random_upto(rs, params->w + params->h);
241 index = j - params->w;
242 start = index * params->w;
247 direction = -1 + 2 * random_upto(rs, 2);
250 * To at least _try_ to avoid boring cases, check
251 * that this move doesn't directly undo a previous
252 * one, or repeat it so many times as to turn it
253 * into fewer moves in the opposite direction. (For
254 * example, in a row of length 4, we're allowed to
255 * move it the same way twice, but not three
258 * We track this for each individual row/column,
259 * and clear all the counters as soon as a
260 * perpendicular move is made. This isn't perfect
261 * (it _can't_ guaranteeably be perfect - there
262 * will always come a move count beyond which a
263 * shorter solution will be possible than the one
264 * which constructed the position) but it should
265 * sort out all the obvious cases.
267 if (offset == prevoffset) {
268 tmp = prevmoves[index] + direction;
269 if (abs(2*tmp) > len || abs(tmp) < abs(prevmoves[index]))
273 /* If we didn't `continue', we've found an OK move to make. */
274 if (offset != prevoffset) {
276 for (i = 0; i < max; i++)
280 prevmoves[index] += direction;
288 start += (len-1) * offset;
292 for (j = 0; j+1 < len; j++)
293 tiles[start + j*offset] = tiles[start + (j+1)*offset];
294 tiles[start + (len-1) * offset] = tmp;
301 used = snewn(n, int);
303 for (i = 0; i < n; i++) {
309 * If both dimensions are odd, there is a parity
312 if (params->w & params->h & 1)
318 * Place everything except (possibly) the last two tiles.
320 for (x = 0, i = n; i > stop; i--) {
321 int k = i > 1 ? random_upto(rs, i) : 0;
324 for (j = 0; j < n; j++)
325 if (!used[j] && (k-- == 0))
328 assert(j < n && !used[j]);
331 while (tiles[x] >= 0)
339 * Find the last two locations, and the last two
342 while (tiles[x] >= 0)
347 while (tiles[x] >= 0)
352 for (i = 0; i < n; i++)
356 for (i = p1+1; i < n; i++)
362 * Try the last two tiles one way round. If that fails,
367 if (perm_parity(tiles, n) != 0) {
370 assert(perm_parity(tiles, n) == 0);
378 * Now construct the game description, by describing the tile
379 * array as a simple sequence of comma-separated integers.
383 for (i = 0; i < n; i++) {
387 k = sprintf(buf, "%d,", tiles[i]+1);
389 ret = sresize(ret, retlen + k + 1, char);
390 strcpy(ret + retlen, buf);
393 ret[retlen-1] = '\0'; /* delete last comma */
401 static char *validate_desc(game_params *params, char *desc)
407 area = params->w * params->h;
411 used = snewn(area, int);
412 for (i = 0; i < area; i++)
415 for (i = 0; i < area; i++) {
419 if (*p < '0' || *p > '9') {
420 err = "Not enough numbers in string";
423 while (*p >= '0' && *p <= '9')
425 if (i < area-1 && *p != ',') {
426 err = "Expected comma after number";
429 else if (i == area-1 && *p) {
430 err = "Excess junk at end of string";
434 if (n < 1 || n > area) {
435 err = "Number out of range";
439 err = "Number used twice";
444 if (*p) p++; /* eat comma */
452 static game_state *new_game(midend *me, game_params *params, char *desc)
454 game_state *state = snew(game_state);
458 state->w = params->w;
459 state->h = params->h;
460 state->n = params->w * params->h;
461 state->tiles = snewn(state->n, int);
465 for (i = 0; i < state->n; i++) {
467 state->tiles[i] = atoi(p);
468 while (*p && *p != ',')
470 if (*p) p++; /* eat comma */
474 state->completed = state->movecount = 0;
475 state->movetarget = params->movetarget;
476 state->used_solve = FALSE;
477 state->last_movement_sense = 0;
482 static game_state *dup_game(game_state *state)
484 game_state *ret = snew(game_state);
489 ret->tiles = snewn(state->w * state->h, int);
490 memcpy(ret->tiles, state->tiles, state->w * state->h * sizeof(int));
491 ret->completed = state->completed;
492 ret->movecount = state->movecount;
493 ret->movetarget = state->movetarget;
494 ret->used_solve = state->used_solve;
495 ret->last_movement_sense = state->last_movement_sense;
500 static void free_game(game_state *state)
506 static char *solve_game(game_state *state, game_state *currstate,
507 char *aux, char **error)
512 static int game_can_format_as_text_now(game_params *params)
517 static char *game_text_format(game_state *state)
519 char *ret, *p, buf[80];
520 int x, y, col, maxlen;
523 * First work out how many characters we need to display each
526 col = sprintf(buf, "%d", state->n);
529 * Now we know the exact total size of the grid we're going to
530 * produce: it's got h rows, each containing w lots of col, w-1
531 * spaces and a trailing newline.
533 maxlen = state->h * state->w * (col+1);
535 ret = snewn(maxlen+1, char);
538 for (y = 0; y < state->h; y++) {
539 for (x = 0; x < state->w; x++) {
540 int v = state->tiles[state->w*y+x];
541 sprintf(buf, "%*d", col, v);
551 assert(p - ret == maxlen);
561 static game_ui *new_ui(game_state *state)
563 game_ui *ui = snew(game_ui);
566 ui->cur_visible = FALSE;
571 static void free_ui(game_ui *ui)
576 static char *encode_ui(game_ui *ui)
581 static void decode_ui(game_ui *ui, char *encoding)
585 static void game_changed_state(game_ui *ui, game_state *oldstate,
586 game_state *newstate)
590 struct game_drawstate {
598 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
599 int x, int y, int button)
601 int cx = -1, cy = -1, dx, dy;
606 if (IS_CURSOR_MOVE(button)) {
607 /* right/down rotates cursor clockwise,
608 * left/up rotates anticlockwise. */
610 cpos = c2pos(state->w, state->h, ui->cur_x, ui->cur_y);
611 diff = c2diff(state->w, state->h, ui->cur_x, ui->cur_y, button);
614 pos2c(state->w, state->h, cpos, &ui->cur_x, &ui->cur_y);
620 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
624 } else if (IS_CURSOR_SELECT(button)) {
625 if (ui->cur_visible) {
636 if (cx == -1 && cy >= 0 && cy < state->h)
638 else if (cx == state->w && cy >= 0 && cy < state->h)
640 else if (cy == -1 && cx >= 0 && cx < state->w)
642 else if (cy == state->h && cx >= 0 && cx < state->w)
645 return ""; /* invalid click location */
647 /* reverse direction if right hand button is pressed */
648 if (button == RIGHT_BUTTON || button == CURSOR_SELECT2) {
654 sprintf(buf, "R%d,%d", cy, dx);
656 sprintf(buf, "C%d,%d", cx, dy);
660 static game_state *execute_move(game_state *from, char *move)
666 if (!strcmp(move, "S")) {
669 ret = dup_game(from);
672 * Simply replace the grid with a solved one. For this game,
673 * this isn't a useful operation for actually telling the user
674 * what they should have done, but it is useful for
675 * conveniently being able to get hold of a clean state from
676 * which to practise manoeuvres.
678 for (i = 0; i < ret->n; i++)
680 ret->used_solve = TRUE;
681 ret->completed = ret->movecount = 1;
686 if (move[0] == 'R' && sscanf(move+1, "%d,%d", &cy, &dx) == 2 &&
687 cy >= 0 && cy < from->h) {
690 } else if (move[0] == 'C' && sscanf(move+1, "%d,%d", &cx, &dy) == 2 &&
691 cx >= 0 && cx < from->w) {
697 ret = dup_game(from);
700 tx = (cx - dx + from->w) % from->w;
701 ty = (cy - dy + from->h) % from->h;
702 ret->tiles[C(ret, cx, cy)] = from->tiles[C(from, tx, ty)];
709 ret->last_movement_sense = dx+dy;
712 * See if the game has been completed.
714 if (!ret->completed) {
715 ret->completed = ret->movecount;
716 for (n = 0; n < ret->n; n++)
717 if (ret->tiles[n] != n+1)
718 ret->completed = FALSE;
724 /* ----------------------------------------------------------------------
728 static void game_compute_size(game_params *params, int tilesize,
731 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
732 struct { int tilesize; } ads, *ds = &ads;
733 ads.tilesize = tilesize;
735 *x = TILE_SIZE * params->w + 2 * BORDER;
736 *y = TILE_SIZE * params->h + 2 * BORDER;
739 static void game_set_size(drawing *dr, game_drawstate *ds,
740 game_params *params, int tilesize)
742 ds->tilesize = tilesize;
745 static float *game_colours(frontend *fe, int *ncolours)
747 float *ret = snewn(3 * NCOLOURS, float);
750 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
752 for (i = 0; i < 3; i++)
753 ret[COL_TEXT * 3 + i] = 0.0;
755 *ncolours = NCOLOURS;
759 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
761 struct game_drawstate *ds = snew(struct game_drawstate);
767 ds->bgcolour = COL_BACKGROUND;
768 ds->tiles = snewn(ds->w*ds->h, int);
769 ds->tilesize = 0; /* haven't decided yet */
770 for (i = 0; i < ds->w*ds->h; i++)
772 ds->cur_x = ds->cur_y = -1;
777 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
783 static void draw_tile(drawing *dr, game_drawstate *ds,
784 game_state *state, int x, int y,
785 int tile, int flash_colour)
788 draw_rect(dr, x, y, TILE_SIZE, TILE_SIZE,
794 coords[0] = x + TILE_SIZE - 1;
795 coords[1] = y + TILE_SIZE - 1;
796 coords[2] = x + TILE_SIZE - 1;
799 coords[5] = y + TILE_SIZE - 1;
800 draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
804 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
806 draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
807 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
810 sprintf(str, "%d", tile);
811 draw_text(dr, x + TILE_SIZE/2, y + TILE_SIZE/2,
812 FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
815 draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
818 static void draw_arrow(drawing *dr, game_drawstate *ds,
819 int x, int y, int xdx, int xdy, int cur)
822 int ydy = -xdx, ydx = xdy;
824 #define POINT(n, xx, yy) ( \
825 coords[2*(n)+0] = x + (xx)*xdx + (yy)*ydx, \
826 coords[2*(n)+1] = y + (xx)*xdy + (yy)*ydy)
828 POINT(0, TILE_SIZE / 2, 3 * TILE_SIZE / 4); /* top of arrow */
829 POINT(1, 3 * TILE_SIZE / 4, TILE_SIZE / 2); /* right corner */
830 POINT(2, 5 * TILE_SIZE / 8, TILE_SIZE / 2); /* right concave */
831 POINT(3, 5 * TILE_SIZE / 8, TILE_SIZE / 4); /* bottom right */
832 POINT(4, 3 * TILE_SIZE / 8, TILE_SIZE / 4); /* bottom left */
833 POINT(5, 3 * TILE_SIZE / 8, TILE_SIZE / 2); /* left concave */
834 POINT(6, TILE_SIZE / 4, TILE_SIZE / 2); /* left corner */
836 draw_polygon(dr, coords, 7, cur ? COL_HIGHLIGHT : COL_LOWLIGHT, COL_TEXT);
839 static void draw_arrow_for_cursor(drawing *dr, game_drawstate *ds,
840 int cur_x, int cur_y, int cur)
842 if (cur_x == -1 && cur_y == -1)
843 return; /* 'no cursur here */
844 else if (cur_x == -1) /* LH column. */
845 draw_arrow(dr, ds, COORD(0), COORD(cur_y+1), 0, -1, cur);
846 else if (cur_x == ds->w) /* RH column */
847 draw_arrow(dr, ds, COORD(ds->w), COORD(cur_y), 0, +1, cur);
848 else if (cur_y == -1) /* Top row */
849 draw_arrow(dr, ds, COORD(cur_x), COORD(0), +1, 0, cur);
850 else if (cur_y == ds->h) /* Bottom row */
851 draw_arrow(dr, ds, COORD(cur_x+1), COORD(ds->h), -1, 0, cur);
853 assert(!"Invalid cursor position");
855 draw_update(dr, COORD(cur_x), COORD(cur_y),
856 TILE_SIZE, TILE_SIZE);
859 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
860 game_state *state, int dir, game_ui *ui,
861 float animtime, float flashtime)
864 int cur_x = -1, cur_y = -1;
867 int frame = (int)(flashtime / FLASH_FRAME);
868 bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
870 bgcolour = COL_BACKGROUND;
876 TILE_SIZE * state->w + 2 * BORDER,
877 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
878 draw_update(dr, 0, 0,
879 TILE_SIZE * state->w + 2 * BORDER,
880 TILE_SIZE * state->h + 2 * BORDER);
883 * Recessed area containing the whole puzzle.
885 coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
886 coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
887 coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
888 coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
889 coords[4] = coords[2] - TILE_SIZE;
890 coords[5] = coords[3] + TILE_SIZE;
891 coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
892 coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
893 coords[6] = coords[8] + TILE_SIZE;
894 coords[7] = coords[9] - TILE_SIZE;
895 draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
897 coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
898 coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
899 draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
902 * Arrows for making moves.
904 for (i = 0; i < state->w; i++) {
905 draw_arrow(dr, ds, COORD(i), COORD(0), +1, 0, 0);
906 draw_arrow(dr, ds, COORD(i+1), COORD(state->h), -1, 0, 0);
908 for (i = 0; i < state->h; i++) {
909 draw_arrow(dr, ds, COORD(state->w), COORD(i), 0, +1, 0);
910 draw_arrow(dr, ds, COORD(0), COORD(i+1), 0, -1, 0);
916 * Cursor (highlighted arrow around edge)
918 if (ui->cur_visible) {
919 cur_x = ui->cur_x; cur_y = ui->cur_y;
921 if (cur_x != ds->cur_x || cur_y != ds->cur_y) {
922 /* Cursor has changed; redraw two (prev and curr) arrows. */
923 draw_arrow_for_cursor(dr, ds, cur_x, cur_y, 1);
924 draw_arrow_for_cursor(dr, ds, ds->cur_x, ds->cur_y, 0);
925 ds->cur_x = cur_x; ds->cur_y = cur_y;
929 * Now draw each tile.
932 clip(dr, COORD(0), COORD(0), TILE_SIZE*state->w, TILE_SIZE*state->h);
934 for (i = 0; i < state->n; i++) {
937 * Figure out what should be displayed at this
938 * location. It's either a simple tile, or it's a
939 * transition between two tiles (in which case we say
940 * -1 because it must always be drawn).
943 if (oldstate && oldstate->tiles[i] != state->tiles[i])
950 if (ds->bgcolour != bgcolour || /* always redraw when flashing */
951 ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1) {
955 * Figure out what to _actually_ draw, and where to
959 int x0, y0, x1, y1, dx, dy;
966 sense = -oldstate->last_movement_sense;
968 sense = state->last_movement_sense;
974 * FIXME: must be prepared to draw a double
975 * tile in some situations.
979 * Find the coordinates of this tile in the old and
982 x1 = COORD(X(state, i));
983 y1 = COORD(Y(state, i));
984 for (j = 0; j < oldstate->n; j++)
985 if (oldstate->tiles[j] == state->tiles[i])
987 assert(j < oldstate->n);
988 x0 = COORD(X(state, j));
989 y0 = COORD(Y(state, j));
993 dx != TILE_SIZE * sense) {
994 dx = (dx < 0 ? dx + TILE_SIZE * state->w :
995 dx - TILE_SIZE * state->w);
996 assert(abs(dx) == TILE_SIZE);
1000 dy != TILE_SIZE * sense) {
1001 dy = (dy < 0 ? dy + TILE_SIZE * state->h :
1002 dy - TILE_SIZE * state->h);
1003 assert(abs(dy) == TILE_SIZE);
1006 c = (animtime / ANIM_TIME);
1007 if (c < 0.0F) c = 0.0F;
1008 if (c > 1.0F) c = 1.0F;
1010 x = x0 + (int)(c * dx);
1011 y = y0 + (int)(c * dy);
1012 x2 = x1 - dx + (int)(c * dx);
1013 y2 = y1 - dy + (int)(c * dy);
1015 x = COORD(X(state, i));
1016 y = COORD(Y(state, i));
1020 draw_tile(dr, ds, state, x, y, t, bgcolour);
1021 if (x2 != -1 || y2 != -1)
1022 draw_tile(dr, ds, state, x2, y2, t, bgcolour);
1029 ds->bgcolour = bgcolour;
1032 * Update the status bar.
1035 char statusbuf[256];
1038 * Don't show the new status until we're also showing the
1039 * new _state_ - after the game animation is complete.
1044 if (state->used_solve)
1045 sprintf(statusbuf, "Moves since auto-solve: %d",
1046 state->movecount - state->completed);
1048 sprintf(statusbuf, "%sMoves: %d",
1049 (state->completed ? "COMPLETED! " : ""),
1050 (state->completed ? state->completed : state->movecount));
1051 if (state->movetarget)
1052 sprintf(statusbuf+strlen(statusbuf), " (target %d)",
1056 status_bar(dr, statusbuf);
1060 static float game_anim_length(game_state *oldstate,
1061 game_state *newstate, int dir, game_ui *ui)
1066 static float game_flash_length(game_state *oldstate,
1067 game_state *newstate, int dir, game_ui *ui)
1069 if (!oldstate->completed && newstate->completed &&
1070 !oldstate->used_solve && !newstate->used_solve)
1071 return 2 * FLASH_FRAME;
1076 static int game_status(game_state *state)
1078 return state->completed ? +1 : 0;
1081 static int game_timing_state(game_state *state, game_ui *ui)
1086 static void game_print_size(game_params *params, float *x, float *y)
1090 static void game_print(drawing *dr, game_state *state, int tilesize)
1095 #define thegame sixteen
1098 const struct game thegame = {
1099 "Sixteen", "games.sixteen", "sixteen",
1106 TRUE, game_configure, custom_params,
1114 TRUE, game_can_format_as_text_now, game_text_format,
1122 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1125 game_free_drawstate,
1130 FALSE, FALSE, game_print_size, game_print,
1131 TRUE, /* wants_statusbar */
1132 FALSE, game_timing_state,
1136 /* vim: set shiftwidth=4 tabstop=8: */