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