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