Copy-to-clipboard facility for Fifteen, Sixteen and Twiddle.
[sgt/puzzles] / fifteen.c
1 /*
2 * fifteen.c: standard 15-puzzle.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13
14 #define TILE_SIZE 48
15 #define BORDER (TILE_SIZE / 2)
16 #define HIGHLIGHT_WIDTH (TILE_SIZE / 20)
17 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
18 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
19
20 #define ANIM_TIME 0.13F
21 #define FLASH_FRAME 0.13F
22
23 #define X(state, i) ( (i) % (state)->w )
24 #define Y(state, i) ( (i) / (state)->w )
25 #define C(state, x, y) ( (y) * (state)->w + (x) )
26
27 enum {
28 COL_BACKGROUND,
29 COL_TEXT,
30 COL_HIGHLIGHT,
31 COL_LOWLIGHT,
32 NCOLOURS
33 };
34
35 struct game_params {
36 int w, h;
37 };
38
39 struct game_state {
40 int w, h, n;
41 int *tiles;
42 int gap_pos;
43 int completed;
44 int movecount;
45 };
46
47 static game_params *default_params(void)
48 {
49 game_params *ret = snew(game_params);
50
51 ret->w = ret->h = 4;
52
53 return ret;
54 }
55
56 static int game_fetch_preset(int i, char **name, game_params **params)
57 {
58 return FALSE;
59 }
60
61 static void free_params(game_params *params)
62 {
63 sfree(params);
64 }
65
66 static game_params *dup_params(game_params *params)
67 {
68 game_params *ret = snew(game_params);
69 *ret = *params; /* structure copy */
70 return ret;
71 }
72
73 static game_params *decode_params(char const *string)
74 {
75 game_params *ret = default_params();
76
77 ret->w = ret->h = atoi(string);
78 while (*string && isdigit(*string)) string++;
79 if (*string == 'x') {
80 string++;
81 ret->h = atoi(string);
82 }
83
84 return ret;
85 }
86
87 static char *encode_params(game_params *params)
88 {
89 char data[256];
90
91 sprintf(data, "%dx%d", params->w, params->h);
92
93 return dupstr(data);
94 }
95
96 static config_item *game_configure(game_params *params)
97 {
98 config_item *ret;
99 char buf[80];
100
101 ret = snewn(3, config_item);
102
103 ret[0].name = "Width";
104 ret[0].type = C_STRING;
105 sprintf(buf, "%d", params->w);
106 ret[0].sval = dupstr(buf);
107 ret[0].ival = 0;
108
109 ret[1].name = "Height";
110 ret[1].type = C_STRING;
111 sprintf(buf, "%d", params->h);
112 ret[1].sval = dupstr(buf);
113 ret[1].ival = 0;
114
115 ret[2].name = NULL;
116 ret[2].type = C_END;
117 ret[2].sval = NULL;
118 ret[2].ival = 0;
119
120 return ret;
121 }
122
123 static game_params *custom_params(config_item *cfg)
124 {
125 game_params *ret = snew(game_params);
126
127 ret->w = atoi(cfg[0].sval);
128 ret->h = atoi(cfg[1].sval);
129
130 return ret;
131 }
132
133 static char *validate_params(game_params *params)
134 {
135 if (params->w < 2 && params->h < 2)
136 return "Width and height must both be at least two";
137
138 return NULL;
139 }
140
141 static int perm_parity(int *perm, int n)
142 {
143 int i, j, ret;
144
145 ret = 0;
146
147 for (i = 0; i < n-1; i++)
148 for (j = i+1; j < n; j++)
149 if (perm[i] > perm[j])
150 ret = !ret;
151
152 return ret;
153 }
154
155 static char *new_game_seed(game_params *params, random_state *rs)
156 {
157 int gap, n, i, x;
158 int x1, x2, p1, p2, parity;
159 int *tiles, *used;
160 char *ret;
161 int retlen;
162
163 n = params->w * params->h;
164
165 tiles = snewn(n, int);
166 used = snewn(n, int);
167
168 for (i = 0; i < n; i++) {
169 tiles[i] = -1;
170 used[i] = FALSE;
171 }
172
173 gap = random_upto(rs, n);
174 tiles[gap] = 0;
175 used[0] = TRUE;
176
177 /*
178 * Place everything else except the last two tiles.
179 */
180 for (x = 0, i = n-1; i > 2; i--) {
181 int k = random_upto(rs, i);
182 int j;
183
184 for (j = 0; j < n; j++)
185 if (!used[j] && (k-- == 0))
186 break;
187
188 assert(j < n && !used[j]);
189 used[j] = TRUE;
190
191 while (tiles[x] >= 0)
192 x++;
193 assert(x < n);
194 tiles[x] = j;
195 }
196
197 /*
198 * Find the last two locations, and the last two pieces.
199 */
200 while (tiles[x] >= 0)
201 x++;
202 assert(x < n);
203 x1 = x;
204 x++;
205 while (tiles[x] >= 0)
206 x++;
207 assert(x < n);
208 x2 = x;
209
210 for (i = 0; i < n; i++)
211 if (!used[i])
212 break;
213 p1 = i;
214 for (i = p1+1; i < n; i++)
215 if (!used[i])
216 break;
217 p2 = i;
218
219 /*
220 * Determine the required parity of the overall permutation.
221 * This is the XOR of:
222 *
223 * - The chessboard parity ((x^y)&1) of the gap square. The
224 * bottom right counts as even.
225 *
226 * - The parity of n. (The target permutation is 1,...,n-1,0
227 * rather than 0,...,n-1; this is a cyclic permutation of
228 * the starting point and hence is odd iff n is even.)
229 */
230 parity = ((X(params, gap) - (params->w-1)) ^
231 (Y(params, gap) - (params->h-1)) ^
232 (n+1)) & 1;
233
234 /*
235 * Try the last two tiles one way round. If that fails, swap
236 * them.
237 */
238 tiles[x1] = p1;
239 tiles[x2] = p2;
240 if (perm_parity(tiles, n) != parity) {
241 tiles[x1] = p2;
242 tiles[x2] = p1;
243 assert(perm_parity(tiles, n) == parity);
244 }
245
246 /*
247 * Now construct the game seed, by describing the tile array as
248 * a simple sequence of comma-separated integers.
249 */
250 ret = NULL;
251 retlen = 0;
252 for (i = 0; i < n; i++) {
253 char buf[80];
254 int k;
255
256 k = sprintf(buf, "%d,", tiles[i]);
257
258 ret = sresize(ret, retlen + k + 1, char);
259 strcpy(ret + retlen, buf);
260 retlen += k;
261 }
262 ret[retlen-1] = '\0'; /* delete last comma */
263
264 sfree(tiles);
265 sfree(used);
266
267 return ret;
268 }
269
270 static char *validate_seed(game_params *params, char *seed)
271 {
272 char *p, *err;
273 int i, area;
274 int *used;
275
276 area = params->w * params->h;
277 p = seed;
278 err = NULL;
279
280 used = snewn(area, int);
281 for (i = 0; i < area; i++)
282 used[i] = FALSE;
283
284 for (i = 0; i < area; i++) {
285 char *q = p;
286 int n;
287
288 if (*p < '0' || *p > '9') {
289 err = "Not enough numbers in string";
290 goto leave;
291 }
292 while (*p >= '0' && *p <= '9')
293 p++;
294 if (i < area-1 && *p != ',') {
295 err = "Expected comma after number";
296 goto leave;
297 }
298 else if (i == area-1 && *p) {
299 err = "Excess junk at end of string";
300 goto leave;
301 }
302 n = atoi(q);
303 if (n < 0 || n >= area) {
304 err = "Number out of range";
305 goto leave;
306 }
307 if (used[n]) {
308 err = "Number used twice";
309 goto leave;
310 }
311 used[n] = TRUE;
312
313 if (*p) p++; /* eat comma */
314 }
315
316 leave:
317 sfree(used);
318 return err;
319 }
320
321 static game_state *new_game(game_params *params, char *seed)
322 {
323 game_state *state = snew(game_state);
324 int i;
325 char *p;
326
327 state->w = params->w;
328 state->h = params->h;
329 state->n = params->w * params->h;
330 state->tiles = snewn(state->n, int);
331
332 state->gap_pos = 0;
333 p = seed;
334 i = 0;
335 for (i = 0; i < state->n; i++) {
336 assert(*p);
337 state->tiles[i] = atoi(p);
338 if (state->tiles[i] == 0)
339 state->gap_pos = i;
340 while (*p && *p != ',')
341 p++;
342 if (*p) p++; /* eat comma */
343 }
344 assert(!*p);
345 assert(state->tiles[state->gap_pos] == 0);
346
347 state->completed = state->movecount = 0;
348
349 return state;
350 }
351
352 static game_state *dup_game(game_state *state)
353 {
354 game_state *ret = snew(game_state);
355
356 ret->w = state->w;
357 ret->h = state->h;
358 ret->n = state->n;
359 ret->tiles = snewn(state->w * state->h, int);
360 memcpy(ret->tiles, state->tiles, state->w * state->h * sizeof(int));
361 ret->gap_pos = state->gap_pos;
362 ret->completed = state->completed;
363 ret->movecount = state->movecount;
364
365 return ret;
366 }
367
368 static void free_game(game_state *state)
369 {
370 sfree(state);
371 }
372
373 static char *game_text_format(game_state *state)
374 {
375 char *ret, *p, buf[80];
376 int x, y, col, maxlen;
377
378 /*
379 * First work out how many characters we need to display each
380 * number.
381 */
382 col = sprintf(buf, "%d", state->n-1);
383
384 /*
385 * Now we know the exact total size of the grid we're going to
386 * produce: it's got h rows, each containing w lots of col, w-1
387 * spaces and a trailing newline.
388 */
389 maxlen = state->h * state->w * (col+1);
390
391 ret = snewn(maxlen, char);
392 p = ret;
393
394 for (y = 0; y < state->h; y++) {
395 for (x = 0; x < state->w; x++) {
396 int v = state->tiles[state->w*y+x];
397 if (v == 0)
398 sprintf(buf, "%*s", col, "");
399 else
400 sprintf(buf, "%*d", col, v);
401 memcpy(p, buf, col);
402 p += col;
403 if (x+1 == state->w)
404 *p++ = '\n';
405 else
406 *p++ = ' ';
407 }
408 }
409
410 assert(p - ret == maxlen);
411 *p = '\0';
412 return ret;
413 }
414
415 static game_ui *new_ui(game_state *state)
416 {
417 return NULL;
418 }
419
420 static void free_ui(game_ui *ui)
421 {
422 }
423
424 static game_state *make_move(game_state *from, game_ui *ui,
425 int x, int y, int button)
426 {
427 int gx, gy, dx, dy, ux, uy, up, p;
428 game_state *ret;
429
430 gx = X(from, from->gap_pos);
431 gy = Y(from, from->gap_pos);
432
433 if (button == CURSOR_RIGHT && gx > 0)
434 dx = gx - 1, dy = gy;
435 else if (button == CURSOR_LEFT && gx < from->w-1)
436 dx = gx + 1, dy = gy;
437 else if (button == CURSOR_DOWN && gy > 0)
438 dy = gy - 1, dx = gx;
439 else if (button == CURSOR_UP && gy < from->h-1)
440 dy = gy + 1, dx = gx;
441 else if (button == LEFT_BUTTON) {
442 dx = FROMCOORD(x);
443 dy = FROMCOORD(y);
444 if (dx < 0 || dx >= from->w || dy < 0 || dy >= from->h)
445 return NULL; /* out of bounds */
446 /*
447 * Any click location should be equal to the gap location
448 * in _precisely_ one coordinate.
449 */
450 if ((dx == gx && dy == gy) || (dx != gx && dy != gy))
451 return NULL;
452 } else
453 return NULL; /* no move */
454
455 /*
456 * Find the unit displacement from the original gap
457 * position towards this one.
458 */
459 ux = (dx < gx ? -1 : dx > gx ? +1 : 0);
460 uy = (dy < gy ? -1 : dy > gy ? +1 : 0);
461 up = C(from, ux, uy);
462
463 ret = dup_game(from);
464
465 ret->gap_pos = C(from, dx, dy);
466 assert(ret->gap_pos >= 0 && ret->gap_pos < ret->n);
467
468 ret->tiles[ret->gap_pos] = 0;
469
470 for (p = from->gap_pos; p != ret->gap_pos; p += up) {
471 assert(p >= 0 && p < from->n);
472 ret->tiles[p] = from->tiles[p + up];
473 ret->movecount++;
474 }
475
476 /*
477 * See if the game has been completed.
478 */
479 if (!ret->completed) {
480 ret->completed = ret->movecount;
481 for (p = 0; p < ret->n; p++)
482 if (ret->tiles[p] != (p < ret->n-1 ? p+1 : 0))
483 ret->completed = 0;
484 }
485
486 return ret;
487 }
488
489 /* ----------------------------------------------------------------------
490 * Drawing routines.
491 */
492
493 struct game_drawstate {
494 int started;
495 int w, h, bgcolour;
496 int *tiles;
497 };
498
499 static void game_size(game_params *params, int *x, int *y)
500 {
501 *x = TILE_SIZE * params->w + 2 * BORDER;
502 *y = TILE_SIZE * params->h + 2 * BORDER;
503 }
504
505 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
506 {
507 float *ret = snewn(3 * NCOLOURS, float);
508 int i;
509 float max;
510
511 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
512
513 /*
514 * Drop the background colour so that the highlight is
515 * noticeably brighter than it while still being under 1.
516 */
517 max = ret[COL_BACKGROUND*3];
518 for (i = 1; i < 3; i++)
519 if (ret[COL_BACKGROUND*3+i] > max)
520 max = ret[COL_BACKGROUND*3+i];
521 if (max * 1.2F > 1.0F) {
522 for (i = 0; i < 3; i++)
523 ret[COL_BACKGROUND*3+i] /= (max * 1.2F);
524 }
525
526 for (i = 0; i < 3; i++) {
527 ret[COL_HIGHLIGHT * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 1.2F;
528 ret[COL_LOWLIGHT * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
529 ret[COL_TEXT * 3 + i] = 0.0;
530 }
531
532 *ncolours = NCOLOURS;
533 return ret;
534 }
535
536 static game_drawstate *game_new_drawstate(game_state *state)
537 {
538 struct game_drawstate *ds = snew(struct game_drawstate);
539 int i;
540
541 ds->started = FALSE;
542 ds->w = state->w;
543 ds->h = state->h;
544 ds->bgcolour = COL_BACKGROUND;
545 ds->tiles = snewn(ds->w*ds->h, int);
546 for (i = 0; i < ds->w*ds->h; i++)
547 ds->tiles[i] = -1;
548
549 return ds;
550 }
551
552 static void game_free_drawstate(game_drawstate *ds)
553 {
554 sfree(ds->tiles);
555 sfree(ds);
556 }
557
558 static void draw_tile(frontend *fe, game_state *state, int x, int y,
559 int tile, int flash_colour)
560 {
561 if (tile == 0) {
562 draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
563 flash_colour);
564 } else {
565 int coords[6];
566 char str[40];
567
568 coords[0] = x + TILE_SIZE - 1;
569 coords[1] = y + TILE_SIZE - 1;
570 coords[2] = x + TILE_SIZE - 1;
571 coords[3] = y;
572 coords[4] = x;
573 coords[5] = y + TILE_SIZE - 1;
574 draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT);
575 draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT);
576
577 coords[0] = x;
578 coords[1] = y;
579 draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT);
580 draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT);
581
582 draw_rect(fe, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
583 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
584 flash_colour);
585
586 sprintf(str, "%d", tile);
587 draw_text(fe, x + TILE_SIZE/2, y + TILE_SIZE/2,
588 FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
589 COL_TEXT, str);
590 }
591 draw_update(fe, x, y, TILE_SIZE, TILE_SIZE);
592 }
593
594 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
595 game_state *state, int dir, game_ui *ui,
596 float animtime, float flashtime)
597 {
598 int i, pass, bgcolour;
599
600 if (flashtime > 0) {
601 int frame = (int)(flashtime / FLASH_FRAME);
602 bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
603 } else
604 bgcolour = COL_BACKGROUND;
605
606 if (!ds->started) {
607 int coords[6];
608
609 draw_rect(fe, 0, 0,
610 TILE_SIZE * state->w + 2 * BORDER,
611 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
612 draw_update(fe, 0, 0,
613 TILE_SIZE * state->w + 2 * BORDER,
614 TILE_SIZE * state->h + 2 * BORDER);
615
616 /*
617 * Recessed area containing the whole puzzle.
618 */
619 coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
620 coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
621 coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
622 coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
623 coords[4] = COORD(0) - HIGHLIGHT_WIDTH;
624 coords[5] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
625 draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT);
626 draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT);
627
628 coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
629 coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
630 draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT);
631 draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT);
632
633 ds->started = TRUE;
634 }
635
636 /*
637 * Now draw each tile. We do this in two passes to make
638 * animation easy.
639 */
640 for (pass = 0; pass < 2; pass++) {
641 for (i = 0; i < state->n; i++) {
642 int t, t0;
643 /*
644 * Figure out what should be displayed at this
645 * location. It's either a simple tile, or it's a
646 * transition between two tiles (in which case we say
647 * -1 because it must always be drawn).
648 */
649
650 if (oldstate && oldstate->tiles[i] != state->tiles[i])
651 t = -1;
652 else
653 t = state->tiles[i];
654
655 t0 = t;
656
657 if (ds->bgcolour != bgcolour || /* always redraw when flashing */
658 ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1) {
659 int x, y;
660
661 /*
662 * Figure out what to _actually_ draw, and where to
663 * draw it.
664 */
665 if (t == -1) {
666 int x0, y0, x1, y1;
667 int j;
668
669 /*
670 * On the first pass, just blank the tile.
671 */
672 if (pass == 0) {
673 x = COORD(X(state, i));
674 y = COORD(Y(state, i));
675 t = 0;
676 } else {
677 float c;
678
679 t = state->tiles[i];
680
681 /*
682 * Don't bother moving the gap; just don't
683 * draw it.
684 */
685 if (t == 0)
686 continue;
687
688 /*
689 * Find the coordinates of this tile in the old and
690 * new states.
691 */
692 x1 = COORD(X(state, i));
693 y1 = COORD(Y(state, i));
694 for (j = 0; j < oldstate->n; j++)
695 if (oldstate->tiles[j] == state->tiles[i])
696 break;
697 assert(j < oldstate->n);
698 x0 = COORD(X(state, j));
699 y0 = COORD(Y(state, j));
700
701 c = (animtime / ANIM_TIME);
702 if (c < 0.0F) c = 0.0F;
703 if (c > 1.0F) c = 1.0F;
704
705 x = x0 + (int)(c * (x1 - x0));
706 y = y0 + (int)(c * (y1 - y0));
707 }
708
709 } else {
710 if (pass == 0)
711 continue;
712 x = COORD(X(state, i));
713 y = COORD(Y(state, i));
714 }
715
716 draw_tile(fe, state, x, y, t, bgcolour);
717 }
718 ds->tiles[i] = t0;
719 }
720 }
721 ds->bgcolour = bgcolour;
722
723 /*
724 * Update the status bar.
725 */
726 {
727 char statusbuf[256];
728
729 /*
730 * Don't show the new status until we're also showing the
731 * new _state_ - after the game animation is complete.
732 */
733 if (oldstate)
734 state = oldstate;
735
736 sprintf(statusbuf, "%sMoves: %d",
737 (state->completed ? "COMPLETED! " : ""),
738 (state->completed ? state->completed : state->movecount));
739
740 status_bar(fe, statusbuf);
741 }
742 }
743
744 static float game_anim_length(game_state *oldstate,
745 game_state *newstate, int dir)
746 {
747 return ANIM_TIME;
748 }
749
750 static float game_flash_length(game_state *oldstate,
751 game_state *newstate, int dir)
752 {
753 if (!oldstate->completed && newstate->completed)
754 return 2 * FLASH_FRAME;
755 else
756 return 0.0F;
757 }
758
759 static int game_wants_statusbar(void)
760 {
761 return TRUE;
762 }
763
764 #ifdef COMBINED
765 #define thegame fifteen
766 #endif
767
768 const struct game thegame = {
769 "Fifteen", "games.fifteen",
770 default_params,
771 game_fetch_preset,
772 decode_params,
773 encode_params,
774 free_params,
775 dup_params,
776 TRUE, game_configure, custom_params,
777 validate_params,
778 new_game_seed,
779 validate_seed,
780 new_game,
781 dup_game,
782 free_game,
783 TRUE, game_text_format,
784 new_ui,
785 free_ui,
786 make_move,
787 game_size,
788 game_colours,
789 game_new_drawstate,
790 game_free_drawstate,
791 game_redraw,
792 game_anim_length,
793 game_flash_length,
794 game_wants_statusbar,
795 };