chiark / gitweb /
Introduce the concept of a `game_aux_info' structure. This is
[sgt-puzzles.git] / twiddle.c
1 /*
2  * twiddle.c: Puzzle involving rearranging a grid of squares by
3  * rotating subsquares. Adapted and generalised from a
4  * door-unlocking puzzle in Metroid Prime 2 (the one in the Main
5  * Gyro Chamber).
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <assert.h>
12 #include <ctype.h>
13 #include <math.h>
14
15 #include "puzzles.h"
16
17 #define TILE_SIZE 48
18 #define BORDER    (TILE_SIZE / 2)
19 #define HIGHLIGHT_WIDTH (TILE_SIZE / 20)
20 #define COORD(x)  ( (x) * TILE_SIZE + BORDER )
21 #define FROMCOORD(x)  ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
22
23 #define PI 3.141592653589793238462643383279502884197169399
24
25 #define ANIM_PER_RADIUS_UNIT 0.13F
26 #define FLASH_FRAME 0.13F
27
28 enum {
29     COL_BACKGROUND,
30     COL_TEXT,
31     COL_HIGHLIGHT,
32     COL_HIGHLIGHT_GENTLE,
33     COL_LOWLIGHT,
34     COL_LOWLIGHT_GENTLE,
35     NCOLOURS
36 };
37
38 struct game_params {
39     int w, h, n;
40     int rowsonly;
41     int orientable;
42 };
43
44 struct game_state {
45     int w, h, n;
46     int orientable;
47     int *grid;
48     int completed;
49     int movecount;
50     int lastx, lasty, lastr;           /* coordinates of last rotation */
51 };
52
53 static game_params *default_params(void)
54 {
55     game_params *ret = snew(game_params);
56
57     ret->w = ret->h = 3;
58     ret->n = 2;
59     ret->rowsonly = ret->orientable = FALSE;
60
61     return ret;
62 }
63
64
65 static void free_params(game_params *params)
66 {
67     sfree(params);
68 }
69
70 static 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 static int game_fetch_preset(int i, char **name, game_params **params)
78 {
79     static struct {
80         char *title;
81         game_params params;
82     } presets[] = {
83         { "3x3 rows only", { 3, 3, 2, TRUE, FALSE } },
84         { "3x3 normal", { 3, 3, 2, FALSE, FALSE } },
85         { "3x3 orientable", { 3, 3, 2, FALSE, TRUE } },
86         { "4x4 normal", { 4, 4, 2, FALSE } },
87         { "4x4 orientable", { 4, 4, 2, FALSE, TRUE } },
88         { "4x4 radius 3", { 4, 4, 3, FALSE } },
89         { "5x5 radius 3", { 5, 5, 3, FALSE } },
90         { "6x6 radius 4", { 6, 6, 4, FALSE } },
91     };
92
93     if (i < 0 || i >= lenof(presets))
94         return FALSE;
95
96     *name = dupstr(presets[i].title);
97     *params = dup_params(&presets[i].params);
98
99     return TRUE;
100 }
101
102 static game_params *decode_params(char const *string)
103 {
104     game_params *ret = snew(game_params);
105
106     ret->w = ret->h = atoi(string);
107     ret->n = 2;
108     ret->rowsonly = ret->orientable = FALSE;
109     while (*string && isdigit(*string)) string++;
110     if (*string == 'x') {
111         string++;
112         ret->h = atoi(string);
113         while (*string && isdigit(*string)) string++;
114     }
115     if (*string == 'n') {
116         string++;
117         ret->n = atoi(string);
118         while (*string && isdigit(*string)) string++;
119     }
120     while (*string) {
121         if (*string == 'r') {
122             ret->rowsonly = TRUE;
123         } else if (*string == 'o') {
124             ret->orientable = TRUE;
125         }
126         string++;
127     }
128
129     return ret;
130 }
131
132 static char *encode_params(game_params *params)
133 {
134     char buf[256];
135     sprintf(buf, "%dx%dn%d%s%s", params->w, params->h, params->n,
136             params->rowsonly ? "r" : "",
137             params->orientable ? "o" : "");
138     return dupstr(buf);
139 }
140
141 static config_item *game_configure(game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(6, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].sval = dupstr(buf);
152     ret[0].ival = 0;
153
154     ret[1].name = "Height";
155     ret[1].type = C_STRING;
156     sprintf(buf, "%d", params->h);
157     ret[1].sval = dupstr(buf);
158     ret[1].ival = 0;
159
160     ret[2].name = "Rotation radius";
161     ret[2].type = C_STRING;
162     sprintf(buf, "%d", params->n);
163     ret[2].sval = dupstr(buf);
164     ret[2].ival = 0;
165
166     ret[3].name = "One number per row";
167     ret[3].type = C_BOOLEAN;
168     ret[3].sval = NULL;
169     ret[3].ival = params->rowsonly;
170
171     ret[4].name = "Orientation matters";
172     ret[4].type = C_BOOLEAN;
173     ret[4].sval = NULL;
174     ret[4].ival = params->orientable;
175
176     ret[5].name = NULL;
177     ret[5].type = C_END;
178     ret[5].sval = NULL;
179     ret[5].ival = 0;
180
181     return ret;
182 }
183
184 static game_params *custom_params(config_item *cfg)
185 {
186     game_params *ret = snew(game_params);
187
188     ret->w = atoi(cfg[0].sval);
189     ret->h = atoi(cfg[1].sval);
190     ret->n = atoi(cfg[2].sval);
191     ret->rowsonly = cfg[3].ival;
192     ret->orientable = cfg[4].ival;
193
194     return ret;
195 }
196
197 static char *validate_params(game_params *params)
198 {
199     if (params->n < 2)
200         return "Rotation radius must be at least two";
201     if (params->w < params->n)
202         return "Width must be at least the rotation radius";
203     if (params->h < params->n)
204         return "Height must be at least the rotation radius";
205     return NULL;
206 }
207
208 /*
209  * This function actually performs a rotation on a grid. The `x'
210  * and `y' coordinates passed in are the coordinates of the _top
211  * left corner_ of the rotated region. (Using the centre would have
212  * involved half-integers and been annoyingly fiddly. Clicking in
213  * the centre is good for a user interface, but too inconvenient to
214  * use internally.)
215  */
216 static void do_rotate(int *grid, int w, int h, int n, int orientable,
217                       int x, int y, int dir)
218 {
219     int i, j;
220
221     assert(x >= 0 && x+n <= w);
222     assert(y >= 0 && y+n <= h);
223     dir &= 3;
224     if (dir == 0)
225         return;                        /* nothing to do */
226
227     grid += y*w+x;                     /* translate region to top corner */
228
229     /*
230      * If we were leaving the result of the rotation in a separate
231      * grid, the simple thing to do would be to loop over each
232      * square within the rotated region and assign it from its
233      * source square. However, to do it in place without taking
234      * O(n^2) memory, we need to be marginally more clever. What
235      * I'm going to do is loop over about one _quarter_ of the
236      * rotated region and permute each element within that quarter
237      * with its rotational coset.
238      * 
239      * The size of the region I need to loop over is (n+1)/2 by
240      * n/2, which is an obvious exact quarter for even n and is a
241      * rectangle for odd n. (For odd n, this technique leaves out
242      * one element of the square, which is of course the central
243      * one that never moves anyway.)
244      */
245     for (i = 0; i < (n+1)/2; i++) {
246         for (j = 0; j < n/2; j++) {
247             int k;
248             int g[4];
249             int p[4] = {
250                 j*w+i,
251                 i*w+(n-j-1),
252                 (n-j-1)*w+(n-i-1),
253                 (n-i-1)*w+j
254             };
255
256             for (k = 0; k < 4; k++)
257                 g[k] = grid[p[k]];
258
259             for (k = 0; k < 4; k++) {
260                 int v = g[(k+dir) & 3];
261                 if (orientable)
262                     v ^= ((v+dir) ^ v) & 3;  /* alter orientation */
263                 grid[p[k]] = v;
264             }
265         }
266     }
267
268     /*
269      * Don't forget the orientation on the centre square, if n is
270      * odd.
271      */
272     if (orientable && (n & 1)) {
273         int v = grid[n/2*(w+1)];
274         v ^= ((v+dir) ^ v) & 3;  /* alter orientation */
275         grid[n/2*(w+1)] = v;
276     }
277 }
278
279 static int grid_complete(int *grid, int wh, int orientable)
280 {
281     int ok = TRUE;
282     int i;
283     for (i = 1; i < wh; i++)
284         if (grid[i] < grid[i-1])
285             ok = FALSE;
286     if (orientable) {
287         for (i = 0; i < wh; i++)
288             if (grid[i] & 3)
289                 ok = FALSE;
290     }
291     return ok;
292 }
293
294 static char *new_game_seed(game_params *params, random_state *rs,
295                            game_aux_info **aux)
296 {
297     int *grid;
298     int w = params->w, h = params->h, n = params->n, wh = w*h;
299     int i;
300     char *ret;
301     int retlen;
302     int total_moves;
303
304     /*
305      * Set up a solved grid.
306      */
307     grid = snewn(wh, int);
308     for (i = 0; i < wh; i++)
309         grid[i] = ((params->rowsonly ? i/w : i) + 1) * 4;
310
311     /*
312      * Shuffle it. This game is complex enough that I don't feel up
313      * to analysing its full symmetry properties (particularly at
314      * n=4 and above!), so I'm going to do it the pedestrian way
315      * and simply shuffle the grid by making a long sequence of
316      * randomly chosen moves.
317      */
318     total_moves = w*h*n*n*2;
319     for (i = 0; i < total_moves; i++) {
320         int x, y;
321
322         x = random_upto(rs, w - n + 1);
323         y = random_upto(rs, h - n + 1);
324         do_rotate(grid, w, h, n, params->orientable,
325                   x, y, 1 + random_upto(rs, 3));
326
327         /*
328          * Optionally one more move in case the entire grid has
329          * happened to come out solved.
330          */
331         if (i == total_moves - 1 && grid_complete(grid, wh,
332                                                   params->orientable))
333             i--;
334     }
335
336     /*
337      * Now construct the game seed, by describing the grid as a
338      * simple sequence of integers. They're comma-separated, unless
339      * the puzzle is orientable in which case they're separated by
340      * orientation letters `u', `d', `l' and `r'.
341      */
342     ret = NULL;
343     retlen = 0;
344     for (i = 0; i < wh; i++) {
345         char buf[80];
346         int k;
347
348         k = sprintf(buf, "%d%c", grid[i] / 4,
349                     params->orientable ? "uldr"[grid[i] & 3] : ',');
350
351         ret = sresize(ret, retlen + k + 1, char);
352         strcpy(ret + retlen, buf);
353         retlen += k;
354     }
355     if (!params->orientable)
356         ret[retlen-1] = '\0';          /* delete last comma */
357
358     sfree(grid);
359     return ret;
360 }
361
362 void game_free_aux_info(game_aux_info *aux)
363 {
364     assert(!"Shouldn't happen");
365 }
366
367 static char *validate_seed(game_params *params, char *seed)
368 {
369     char *p, *err;
370     int w = params->w, h = params->h, wh = w*h;
371     int i;
372
373     p = seed;
374     err = NULL;
375
376     for (i = 0; i < wh; i++) {
377         if (*p < '0' || *p > '9')
378             return "Not enough numbers in string";
379         while (*p >= '0' && *p <= '9')
380             p++;
381         if (!params->orientable && i < wh-1) {
382             if (*p != ',')
383                 return "Expected comma after number";
384         } else if (params->orientable && i < wh) {
385             if (*p != 'l' && *p != 'r' && *p != 'u' && *p != 'd')
386                 return "Expected orientation letter after number";
387         } else if (i == wh-1 && *p) {
388             return "Excess junk at end of string";
389         }
390
391         if (*p) p++;                   /* eat comma */
392     }
393
394     return NULL;
395 }
396
397 static game_state *new_game(game_params *params, char *seed)
398 {
399     game_state *state = snew(game_state);
400     int w = params->w, h = params->h, n = params->n, wh = w*h;
401     int i;
402     char *p;
403
404     state->w = w;
405     state->h = h;
406     state->n = n;
407     state->orientable = params->orientable;
408     state->completed = 0;
409     state->movecount = 0;
410     state->lastx = state->lasty = state->lastr = -1;
411
412     state->grid = snewn(wh, int);
413
414     p = seed;
415
416     for (i = 0; i < wh; i++) {
417         state->grid[i] = 4 * atoi(p);
418         while (*p >= '0' && *p <= '9')
419             p++;
420         if (*p) {
421             if (params->orientable) {
422                 switch (*p) {
423                   case 'l': state->grid[i] |= 1; break;
424                   case 'd': state->grid[i] |= 2; break;
425                   case 'r': state->grid[i] |= 3; break;
426                 }
427             }
428             p++;
429         }
430     }
431
432     return state;
433 }
434
435 static game_state *dup_game(game_state *state)
436 {
437     game_state *ret = snew(game_state);
438
439     ret->w = state->w;
440     ret->h = state->h;
441     ret->n = state->n;
442     ret->orientable = state->orientable;
443     ret->completed = state->completed;
444     ret->movecount = state->movecount;
445     ret->lastx = state->lastx;
446     ret->lasty = state->lasty;
447     ret->lastr = state->lastr;
448
449     ret->grid = snewn(ret->w * ret->h, int);
450     memcpy(ret->grid, state->grid, ret->w * ret->h * sizeof(int));
451
452     return ret;
453 }
454
455 static void free_game(game_state *state)
456 {
457     sfree(state->grid);
458     sfree(state);
459 }
460
461 static char *game_text_format(game_state *state)
462 {
463     char *ret, *p, buf[80];
464     int i, x, y, col, o, maxlen;
465
466     /*
467      * First work out how many characters we need to display each
468      * number. We're pretty flexible on grid contents here, so we
469      * have to scan the entire grid.
470      */
471     col = 0;
472     for (i = 0; i < state->w * state->h; i++) {
473         x = sprintf(buf, "%d", state->grid[i] / 4);
474         if (col < x) col = x;
475     }
476     o = (state->orientable ? 1 : 0);
477
478     /*
479      * Now we know the exact total size of the grid we're going to
480      * produce: it's got h rows, each containing w lots of col+o,
481      * w-1 spaces and a trailing newline.
482      */
483     maxlen = state->h * state->w * (col+o+1);
484
485     ret = snewn(maxlen, char);
486     p = ret;
487
488     for (y = 0; y < state->h; y++) {
489         for (x = 0; x < state->w; x++) {
490             int v = state->grid[state->w*y+x];
491             sprintf(buf, "%*d", col, v/4);
492             memcpy(p, buf, col);
493             p += col;
494             if (o)
495                 *p++ = "^<v>"[v & 3];
496             if (x+1 == state->w)
497                 *p++ = '\n';
498             else
499                 *p++ = ' ';
500         }
501     }
502
503     assert(p - ret == maxlen);
504     *p = '\0';
505     return ret;
506 }
507
508 static game_ui *new_ui(game_state *state)
509 {
510     return NULL;
511 }
512
513 static void free_ui(game_ui *ui)
514 {
515 }
516
517 static game_state *make_move(game_state *from, game_ui *ui, int x, int y,
518                              int button)
519 {
520     int w = from->w, h = from->h, n = from->n, wh = w*h;
521     game_state *ret;
522     int dir;
523
524     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
525         /*
526          * Determine the coordinates of the click. We offset by n-1
527          * half-blocks so that the user must click at the centre of
528          * a rotation region rather than at the corner.
529          */
530         x -= (n-1) * TILE_SIZE / 2;
531         y -= (n-1) * TILE_SIZE / 2;
532         x = FROMCOORD(x);
533         y = FROMCOORD(y);
534         if (x < 0 || x > w-n || y < 0 || y > w-n)
535             return NULL;
536
537         /*
538          * This is a valid move. Make it.
539          */
540         ret = dup_game(from);
541         ret->movecount++;
542         dir = (button == LEFT_BUTTON ? 1 : -1);
543         do_rotate(ret->grid, w, h, n, ret->orientable, x, y, dir);
544         ret->lastx = x;
545         ret->lasty = y;
546         ret->lastr = dir;
547
548         /*
549          * See if the game has been completed. To do this we simply
550          * test that the grid contents are in increasing order.
551          */
552         if (!ret->completed && grid_complete(ret->grid, wh, ret->orientable))
553             ret->completed = ret->movecount;
554         return ret;
555     }
556     return NULL;
557 }
558
559 /* ----------------------------------------------------------------------
560  * Drawing routines.
561  */
562
563 struct game_drawstate {
564     int started;
565     int w, h, bgcolour;
566     int *grid;
567 };
568
569 static void game_size(game_params *params, int *x, int *y)
570 {
571     *x = TILE_SIZE * params->w + 2 * BORDER;
572     *y = TILE_SIZE * params->h + 2 * BORDER;
573 }
574
575 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
576 {
577     float *ret = snewn(3 * NCOLOURS, float);
578     int i;
579     float max;
580
581     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
582
583     /*
584      * Drop the background colour so that the highlight is
585      * noticeably brighter than it while still being under 1.
586      */
587     max = ret[COL_BACKGROUND*3];
588     for (i = 1; i < 3; i++)
589         if (ret[COL_BACKGROUND*3+i] > max)
590             max = ret[COL_BACKGROUND*3+i];
591     if (max * 1.2F > 1.0F) {
592         for (i = 0; i < 3; i++)
593             ret[COL_BACKGROUND*3+i] /= (max * 1.2F);
594     }
595
596     for (i = 0; i < 3; i++) {
597         ret[COL_HIGHLIGHT * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 1.2F;
598         ret[COL_HIGHLIGHT_GENTLE * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 1.1F;
599         ret[COL_LOWLIGHT * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
600         ret[COL_LOWLIGHT_GENTLE * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.9F;
601         ret[COL_TEXT * 3 + i] = 0.0;
602     }
603
604     *ncolours = NCOLOURS;
605     return ret;
606 }
607
608 static game_drawstate *game_new_drawstate(game_state *state)
609 {
610     struct game_drawstate *ds = snew(struct game_drawstate);
611     int i;
612
613     ds->started = FALSE;
614     ds->w = state->w;
615     ds->h = state->h;
616     ds->bgcolour = COL_BACKGROUND;
617     ds->grid = snewn(ds->w*ds->h, int);
618     for (i = 0; i < ds->w*ds->h; i++)
619         ds->grid[i] = -1;
620
621     return ds;
622 }
623
624 static void game_free_drawstate(game_drawstate *ds)
625 {
626     sfree(ds);
627 }
628
629 struct rotation {
630     int cx, cy, cw, ch;                /* clip region */
631     int ox, oy;                        /* rotation origin */
632     float c, s;                        /* cos and sin of rotation angle */
633     int lc, rc, tc, bc;                /* colours of tile edges */
634 };
635
636 static void rotate(int *xy, struct rotation *rot)
637 {
638     if (rot) {
639         float xf = xy[0] - rot->ox, yf = xy[1] - rot->oy;
640         float xf2, yf2;
641
642         xf2 = rot->c * xf + rot->s * yf;
643         yf2 = - rot->s * xf + rot->c * yf;
644
645         xy[0] = xf2 + rot->ox + 0.5;   /* round to nearest */
646         xy[1] = yf2 + rot->oy + 0.5;   /* round to nearest */
647     }
648 }
649
650 static void draw_tile(frontend *fe, game_state *state, int x, int y,
651                       int tile, int flash_colour, struct rotation *rot)
652 {
653     int coords[8];
654     char str[40];
655
656     if (rot)
657         clip(fe, rot->cx, rot->cy, rot->cw, rot->ch);
658
659     /*
660      * We must draw each side of the tile's highlight separately,
661      * because in some cases (during rotation) they will all need
662      * to be different colours.
663      */
664
665     /* The centre point is common to all sides. */
666     coords[4] = x + TILE_SIZE / 2;
667     coords[5] = y + TILE_SIZE / 2;
668     rotate(coords+4, rot);
669
670     /* Right side. */
671     coords[0] = x + TILE_SIZE - 1;
672     coords[1] = y + TILE_SIZE - 1;
673     rotate(coords+0, rot);
674     coords[2] = x + TILE_SIZE - 1;
675     coords[3] = y;
676     rotate(coords+2, rot);
677     draw_polygon(fe, coords, 3, TRUE, rot ? rot->rc : COL_LOWLIGHT);
678     draw_polygon(fe, coords, 3, FALSE, rot ? rot->rc : COL_LOWLIGHT);
679
680     /* Bottom side. */
681     coords[2] = x;
682     coords[3] = y + TILE_SIZE - 1;
683     rotate(coords+2, rot);
684     draw_polygon(fe, coords, 3, TRUE, rot ? rot->bc : COL_LOWLIGHT);
685     draw_polygon(fe, coords, 3, FALSE, rot ? rot->bc : COL_LOWLIGHT);
686
687     /* Left side. */
688     coords[0] = x;
689     coords[1] = y;
690     rotate(coords+0, rot);
691     draw_polygon(fe, coords, 3, TRUE, rot ? rot->lc : COL_HIGHLIGHT);
692     draw_polygon(fe, coords, 3, FALSE, rot ? rot->lc : COL_HIGHLIGHT);
693
694     /* Top side. */
695     coords[2] = x + TILE_SIZE - 1;
696     coords[3] = y;
697     rotate(coords+2, rot);
698     draw_polygon(fe, coords, 3, TRUE, rot ? rot->tc : COL_HIGHLIGHT);
699     draw_polygon(fe, coords, 3, FALSE, rot ? rot->tc : COL_HIGHLIGHT);
700
701     /*
702      * Now the main blank area in the centre of the tile.
703      */
704     if (rot) {
705         coords[0] = x + HIGHLIGHT_WIDTH;
706         coords[1] = y + HIGHLIGHT_WIDTH;
707         rotate(coords+0, rot);
708         coords[2] = x + HIGHLIGHT_WIDTH;
709         coords[3] = y + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
710         rotate(coords+2, rot);
711         coords[4] = x + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
712         coords[5] = y + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
713         rotate(coords+4, rot);
714         coords[6] = x + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
715         coords[7] = y + HIGHLIGHT_WIDTH;
716         rotate(coords+6, rot);
717         draw_polygon(fe, coords, 4, TRUE, flash_colour);
718         draw_polygon(fe, coords, 4, FALSE, flash_colour);
719     } else {
720         draw_rect(fe, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
721                   TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
722                   flash_colour);
723     }
724
725     /*
726      * Next, the colour bars for orientation.
727      */
728     if (state->orientable) {
729         int xdx, xdy, ydx, ydy;
730         int cx, cy, displ, displ2;
731         switch (tile & 3) {
732           case 0:
733             xdx = 1, xdy = 0;
734             ydx = 0, ydy = 1;
735             break;
736           case 1:
737             xdx = 0, xdy = -1;
738             ydx = 1, ydy = 0;
739             break;
740           case 2:
741             xdx = -1, xdy = 0;
742             ydx = 0, ydy = -1;
743             break;
744           default /* case 3 */:
745             xdx = 0, xdy = 1;
746             ydx = -1, ydy = 0;
747             break;
748         }
749
750         cx = x + TILE_SIZE / 2;
751         cy = y + TILE_SIZE / 2;
752         displ = TILE_SIZE / 2 - HIGHLIGHT_WIDTH - 2;
753         displ2 = TILE_SIZE / 3 - HIGHLIGHT_WIDTH;
754
755         coords[0] = cx - displ * xdx + displ2 * ydx;
756         coords[1] = cy - displ * xdy + displ2 * ydy;
757         rotate(coords+0, rot);
758         coords[2] = cx + displ * xdx + displ2 * ydx;
759         coords[3] = cy + displ * xdy + displ2 * ydy;
760         rotate(coords+2, rot);
761         coords[4] = cx - displ * ydx;
762         coords[5] = cy - displ * ydy;
763         rotate(coords+4, rot);
764         draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT_GENTLE);
765         draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT_GENTLE);
766     }
767
768     coords[0] = x + TILE_SIZE/2;
769     coords[1] = y + TILE_SIZE/2;
770     rotate(coords+0, rot);
771     sprintf(str, "%d", tile / 4);
772     draw_text(fe, coords[0], coords[1],
773               FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
774               COL_TEXT, str);
775
776     if (rot)
777         unclip(fe);
778
779     draw_update(fe, x, y, TILE_SIZE, TILE_SIZE);
780 }
781
782 static int highlight_colour(float angle)
783 {
784     int colours[32] = {
785         COL_LOWLIGHT,
786         COL_LOWLIGHT_GENTLE,
787         COL_LOWLIGHT_GENTLE,
788         COL_LOWLIGHT_GENTLE,
789         COL_HIGHLIGHT_GENTLE,
790         COL_HIGHLIGHT_GENTLE,
791         COL_HIGHLIGHT_GENTLE,
792         COL_HIGHLIGHT,
793         COL_HIGHLIGHT,
794         COL_HIGHLIGHT,
795         COL_HIGHLIGHT,
796         COL_HIGHLIGHT,
797         COL_HIGHLIGHT,
798         COL_HIGHLIGHT,
799         COL_HIGHLIGHT,
800         COL_HIGHLIGHT,
801         COL_HIGHLIGHT,
802         COL_HIGHLIGHT_GENTLE,
803         COL_HIGHLIGHT_GENTLE,
804         COL_HIGHLIGHT_GENTLE,
805         COL_LOWLIGHT_GENTLE,
806         COL_LOWLIGHT_GENTLE,
807         COL_LOWLIGHT_GENTLE,
808         COL_LOWLIGHT,
809         COL_LOWLIGHT,
810         COL_LOWLIGHT,
811         COL_LOWLIGHT,
812         COL_LOWLIGHT,
813         COL_LOWLIGHT,
814         COL_LOWLIGHT,
815         COL_LOWLIGHT,
816         COL_LOWLIGHT,
817     };
818
819     return colours[(int)((angle + 2*PI) / (PI/16)) & 31];
820 }
821
822 static float game_anim_length(game_state *oldstate, game_state *newstate,
823                               int dir)
824 {
825     return ANIM_PER_RADIUS_UNIT * sqrt(newstate->n-1);
826 }
827
828 static float game_flash_length(game_state *oldstate, game_state *newstate,
829                                int dir)
830 {
831     if (!oldstate->completed && newstate->completed)
832         return 2 * FLASH_FRAME;
833     else
834         return 0.0F;
835 }
836
837 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
838                         game_state *state, int dir, game_ui *ui,
839                         float animtime, float flashtime)
840 {
841     int i, bgcolour;
842     struct rotation srot, *rot;
843     int lastx = -1, lasty = -1, lastr = -1;
844
845     if (flashtime > 0) {
846         int frame = (int)(flashtime / FLASH_FRAME);
847         bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
848     } else
849         bgcolour = COL_BACKGROUND;
850
851     if (!ds->started) {
852         int coords[6];
853
854         draw_rect(fe, 0, 0,
855                   TILE_SIZE * state->w + 2 * BORDER,
856                   TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
857         draw_update(fe, 0, 0,
858                     TILE_SIZE * state->w + 2 * BORDER,
859                     TILE_SIZE * state->h + 2 * BORDER);
860
861         /*
862          * Recessed area containing the whole puzzle.
863          */
864         coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
865         coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
866         coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
867         coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
868         coords[4] = COORD(0) - HIGHLIGHT_WIDTH;
869         coords[5] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
870         draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT);
871         draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT);
872
873         coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
874         coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
875         draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT);
876         draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT);
877
878         ds->started = TRUE;
879     }
880
881     /*
882      * If we're drawing any rotated tiles, sort out the rotation
883      * parameters, and also zap the rotation region to the
884      * background colour before doing anything else.
885      */
886     if (oldstate) {
887         float angle;
888         float anim_max = game_anim_length(oldstate, state, dir);
889
890         if (dir > 0) {
891             lastx = state->lastx;
892             lasty = state->lasty;
893             lastr = state->lastr;
894         } else {
895             lastx = oldstate->lastx;
896             lasty = oldstate->lasty;
897             lastr = -oldstate->lastr;
898         }
899
900         rot = &srot;
901         rot->cx = COORD(lastx);
902         rot->cy = COORD(lasty);
903         rot->cw = rot->ch = TILE_SIZE * state->n;
904         rot->ox = rot->cx + rot->cw/2;
905         rot->oy = rot->cy + rot->ch/2;
906         angle = (-PI/2 * lastr) * (1.0 - animtime / anim_max);
907         rot->c = cos(angle);
908         rot->s = sin(angle);
909
910         /*
911          * Sort out the colours of the various sides of the tile.
912          */
913         rot->lc = highlight_colour(PI + angle);
914         rot->rc = highlight_colour(angle);
915         rot->tc = highlight_colour(PI/2 + angle);
916         rot->bc = highlight_colour(-PI/2 + angle);
917
918         draw_rect(fe, rot->cx, rot->cy, rot->cw, rot->ch, bgcolour);
919     } else
920         rot = NULL;
921
922     /*
923      * Now draw each tile.
924      */
925     for (i = 0; i < state->w * state->h; i++) {
926         int t;
927         int tx = i % state->w, ty = i / state->w;
928
929         /*
930          * Figure out what should be displayed at this location.
931          * Usually it will be state->grid[i], unless we're in the
932          * middle of animating an actual rotation and this cell is
933          * within the rotation region, in which case we set -1
934          * (always display).
935          */
936         if (oldstate && lastx >= 0 && lasty >= 0 &&
937             tx >= lastx && tx < lastx + state->n &&
938             ty >= lasty && ty < lasty + state->n)
939             t = -1;
940         else
941             t = state->grid[i];
942
943         if (ds->bgcolour != bgcolour ||   /* always redraw when flashing */
944             ds->grid[i] != t || ds->grid[i] == -1 || t == -1) {
945             int x = COORD(tx), y = COORD(ty);
946
947             draw_tile(fe, state, x, y, state->grid[i], bgcolour, rot);
948             ds->grid[i] = t;
949         }
950     }
951     ds->bgcolour = bgcolour;
952
953     /*
954      * Update the status bar.
955      */
956     {
957         char statusbuf[256];
958
959         /*
960          * Don't show the new status until we're also showing the
961          * new _state_ - after the game animation is complete.
962          */
963         if (oldstate)
964             state = oldstate;
965
966         sprintf(statusbuf, "%sMoves: %d",
967                 (state->completed ? "COMPLETED! " : ""),
968                 (state->completed ? state->completed : state->movecount));
969
970         status_bar(fe, statusbuf);
971     }
972 }
973
974 static int game_wants_statusbar(void)
975 {
976     return TRUE;
977 }
978
979 #ifdef COMBINED
980 #define thegame twiddle
981 #endif
982
983 const struct game thegame = {
984     "Twiddle", "games.twiddle",
985     default_params,
986     game_fetch_preset,
987     decode_params,
988     encode_params,
989     free_params,
990     dup_params,
991     TRUE, game_configure, custom_params,
992     validate_params,
993     new_game_seed,
994     game_free_aux_info,
995     validate_seed,
996     new_game,
997     dup_game,
998     free_game,
999     TRUE, game_text_format,
1000     new_ui,
1001     free_ui,
1002     make_move,
1003     game_size,
1004     game_colours,
1005     game_new_drawstate,
1006     game_free_drawstate,
1007     game_redraw,
1008     game_anim_length,
1009     game_flash_length,
1010     game_wants_statusbar,
1011 };