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