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