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