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