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