chiark / gitweb /
Fix completion checking in Killer Solo.
[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         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, 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].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 = "Rotating block size";
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(const 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(const game_params *params, int full)
213 {
214     if (params->n < 2)
215         return "Rotating block size must be at least two";
216     if (params->w < params->n)
217         return "Width must be at least the rotating block size";
218     if (params->h < params->n)
219         return "Height must be at least the rotating block size";
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(const game_params *params, random_state *rs,
310                            char **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                 
367                 /*
368                  * Special case here for w==h==n, in which case
369                  * there is actually no way to _avoid_ all moves
370                  * repeating or undoing previous ones.
371                  */
372             } while ((w != n || h != n) &&
373                      (abs(newtotal) < abs(oldtotal) || abs(newtotal) > 2));
374
375             do_rotate(grid, w, h, n, params->orientable, x, y, r);
376
377             /*
378              * Log the rotation we've just performed at this point,
379              * for inversion detection in the next move.
380              * 
381              * Also zero a section of the prevmoves array, because
382              * any rotation area which _overlaps_ this one is now
383              * entirely safe to perform further moves in.
384              * 
385              * Two rotation areas overlap if their top left
386              * coordinates differ by strictly less than n in both
387              * directions
388              */
389             prevmoves[y*rw+x] += r;
390             for (dy = -n+1; dy <= n-1; dy++) {
391                 if (y + dy < 0 || y + dy >= rh)
392                     continue;
393                 for (dx = -n+1; dx <= n-1; dx++) {
394                     if (x + dx < 0 || x + dx >= rw)
395                         continue;
396                     if (dx == 0 && dy == 0)
397                         continue;
398                     prevmoves[(y+dy)*rw+(x+dx)] = 0;
399                 }
400             }
401         }
402
403         sfree(prevmoves);
404
405     } while (grid_complete(grid, wh, params->orientable));
406
407     /*
408      * Now construct the game description, by describing the grid
409      * as a simple sequence of integers. They're comma-separated,
410      * unless the puzzle is orientable in which case they're
411      * separated by orientation letters `u', `d', `l' and `r'.
412      */
413     ret = NULL;
414     retlen = 0;
415     for (i = 0; i < wh; i++) {
416         char buf[80];
417         int k;
418
419         k = sprintf(buf, "%d%c", grid[i] / 4,
420                     (char)(params->orientable ? "uldr"[grid[i] & 3] : ','));
421
422         ret = sresize(ret, retlen + k + 1, char);
423         strcpy(ret + retlen, buf);
424         retlen += k;
425     }
426     if (!params->orientable)
427         ret[retlen-1] = '\0';          /* delete last comma */
428
429     sfree(grid);
430     return ret;
431 }
432
433 static char *validate_desc(const game_params *params, const char *desc)
434 {
435     const char *p;
436     int w = params->w, h = params->h, wh = w*h;
437     int i;
438
439     p = desc;
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 *me, const game_params *params,
463                             const char *desc)
464 {
465     game_state *state = snew(game_state);
466     int w = params->w, h = params->h, n = params->n, wh = w*h;
467     int i;
468     const char *p;
469
470     state->w = w;
471     state->h = h;
472     state->n = n;
473     state->orientable = params->orientable;
474     state->completed = 0;
475     state->used_solve = FALSE;
476     state->movecount = 0;
477     state->movetarget = params->movetarget;
478     state->lastx = state->lasty = state->lastr = -1;
479
480     state->grid = snewn(wh, int);
481
482     p = desc;
483
484     for (i = 0; i < wh; i++) {
485         state->grid[i] = 4 * atoi(p);
486         while (*p >= '0' && *p <= '9')
487             p++;
488         if (*p) {
489             if (params->orientable) {
490                 switch (*p) {
491                   case 'l': state->grid[i] |= 1; break;
492                   case 'd': state->grid[i] |= 2; break;
493                   case 'r': state->grid[i] |= 3; break;
494                 }
495             }
496             p++;
497         }
498     }
499
500     return state;
501 }
502
503 static game_state *dup_game(const game_state *state)
504 {
505     game_state *ret = snew(game_state);
506
507     ret->w = state->w;
508     ret->h = state->h;
509     ret->n = state->n;
510     ret->orientable = state->orientable;
511     ret->completed = state->completed;
512     ret->movecount = state->movecount;
513     ret->movetarget = state->movetarget;
514     ret->lastx = state->lastx;
515     ret->lasty = state->lasty;
516     ret->lastr = state->lastr;
517     ret->used_solve = state->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 char *solve_game(const game_state *state, const game_state *currstate,
544                         const char *aux, char **error)
545 {
546     return dupstr("S");
547 }
548
549 static int game_can_format_as_text_now(const game_params *params)
550 {
551     return TRUE;
552 }
553
554 static char *game_text_format(const game_state *state)
555 {
556     char *ret, *p, buf[80];
557     int i, x, y, col, o, maxlen;
558
559     /*
560      * First work out how many characters we need to display each
561      * number. We're pretty flexible on grid contents here, so we
562      * have to scan the entire grid.
563      */
564     col = 0;
565     for (i = 0; i < state->w * state->h; i++) {
566         x = sprintf(buf, "%d", state->grid[i] / 4);
567         if (col < x) col = x;
568     }
569     o = (state->orientable ? 1 : 0);
570
571     /*
572      * Now we know the exact total size of the grid we're going to
573      * produce: it's got h rows, each containing w lots of col+o,
574      * w-1 spaces and a trailing newline.
575      */
576     maxlen = state->h * state->w * (col+o+1);
577
578     ret = snewn(maxlen+1, char);
579     p = ret;
580
581     for (y = 0; y < state->h; y++) {
582         for (x = 0; x < state->w; x++) {
583             int v = state->grid[state->w*y+x];
584             sprintf(buf, "%*d", col, v/4);
585             memcpy(p, buf, col);
586             p += col;
587             if (o)
588                 *p++ = "^<v>"[v & 3];
589             if (x+1 == state->w)
590                 *p++ = '\n';
591             else
592                 *p++ = ' ';
593         }
594     }
595
596     assert(p - ret == maxlen);
597     *p = '\0';
598     return ret;
599 }
600
601 struct game_ui {
602     int cur_x, cur_y;
603     int cur_visible;
604 };
605
606 static game_ui *new_ui(const game_state *state)
607 {
608     game_ui *ui = snew(game_ui);
609
610     ui->cur_x = 0;
611     ui->cur_y = 0;
612     ui->cur_visible = FALSE;
613
614     return ui;
615 }
616
617 static void free_ui(game_ui *ui)
618 {
619     sfree(ui);
620 }
621
622 static char *encode_ui(const game_ui *ui)
623 {
624     return NULL;
625 }
626
627 static void decode_ui(game_ui *ui, const char *encoding)
628 {
629 }
630
631 static void game_changed_state(game_ui *ui, const game_state *oldstate,
632                                const game_state *newstate)
633 {
634 }
635
636 struct game_drawstate {
637     int started;
638     int w, h, bgcolour;
639     int *grid;
640     int tilesize;
641     int cur_x, cur_y;
642 };
643
644 static char *interpret_move(const game_state *state, game_ui *ui,
645                             const game_drawstate *ds,
646                             int x, int y, int button)
647 {
648     int w = state->w, h = state->h, n = state->n /* , wh = w*h */;
649     char buf[80];
650     int dir;
651
652     button = button & (~MOD_MASK | MOD_NUM_KEYPAD);
653
654     if (IS_CURSOR_MOVE(button)) {
655         if (button == CURSOR_LEFT && ui->cur_x > 0)
656             ui->cur_x--;
657         if (button == CURSOR_RIGHT && (ui->cur_x+n) < (w))
658             ui->cur_x++;
659         if (button == CURSOR_UP && ui->cur_y > 0)
660             ui->cur_y--;
661         if (button == CURSOR_DOWN && (ui->cur_y+n) < (h))
662             ui->cur_y++;
663         ui->cur_visible = 1;
664         return "";
665     }
666
667     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
668         /*
669          * Determine the coordinates of the click. We offset by n-1
670          * half-blocks so that the user must click at the centre of
671          * a rotation region rather than at the corner.
672          */
673         x -= (n-1) * TILE_SIZE / 2;
674         y -= (n-1) * TILE_SIZE / 2;
675         x = FROMCOORD(x);
676         y = FROMCOORD(y);
677         dir = (button == LEFT_BUTTON ? 1 : -1);
678         if (x < 0 || x > w-n || y < 0 || y > h-n)
679             return NULL;
680         ui->cur_visible = 0;
681     } else if (IS_CURSOR_SELECT(button)) {
682         if (ui->cur_visible) {
683             x = ui->cur_x;
684             y = ui->cur_y;
685             dir = (button == CURSOR_SELECT2) ? -1 : +1;
686         } else {
687             ui->cur_visible = 1;
688             return "";
689         }
690     } else if (button == 'a' || button == 'A' || button==MOD_NUM_KEYPAD+'7') {
691         x = y = 0;
692         dir = (button == 'A' ? -1 : +1);
693     } else if (button == 'b' || button == 'B' || button==MOD_NUM_KEYPAD+'9') {
694         x = w-n;
695         y = 0;
696         dir = (button == 'B' ? -1 : +1);
697     } else if (button == 'c' || button == 'C' || button==MOD_NUM_KEYPAD+'1') {
698         x = 0;
699         y = h-n;
700         dir = (button == 'C' ? -1 : +1);
701     } else if (button == 'd' || button == 'D' || button==MOD_NUM_KEYPAD+'3') {
702         x = w-n;
703         y = h-n;
704         dir = (button == 'D' ? -1 : +1);
705     } else if (button==MOD_NUM_KEYPAD+'8' && (w-n) % 2 == 0) {
706         x = (w-n) / 2;
707         y = 0;
708         dir = +1;
709     } else if (button==MOD_NUM_KEYPAD+'2' && (w-n) % 2 == 0) {
710         x = (w-n) / 2;
711         y = h-n;
712         dir = +1;
713     } else if (button==MOD_NUM_KEYPAD+'4' && (h-n) % 2 == 0) {
714         x = 0;
715         y = (h-n) / 2;
716         dir = +1;
717     } else if (button==MOD_NUM_KEYPAD+'6' && (h-n) % 2 == 0) {
718         x = w-n;
719         y = (h-n) / 2;
720         dir = +1;
721     } else if (button==MOD_NUM_KEYPAD+'5' && (w-n) % 2 == 0 && (h-n) % 2 == 0){
722         x = (w-n) / 2;
723         y = (h-n) / 2;
724         dir = +1;
725     } else {
726         return NULL;                   /* no move to be made */
727     }
728
729     /*
730      * If we reach here, we have a valid move.
731      */
732     sprintf(buf, "M%d,%d,%d", x, y, dir);
733     return dupstr(buf);
734 }
735
736 static game_state *execute_move(const game_state *from, const char *move)
737 {
738     game_state *ret;
739     int w = from->w, h = from->h, n = from->n, wh = w*h;
740     int x, y, dir;
741
742     if (!strcmp(move, "S")) {
743         int i;
744         ret = dup_game(from);
745
746         /*
747          * Simply replace the grid with a solved one. For this game,
748          * this isn't a useful operation for actually telling the user
749          * what they should have done, but it is useful for
750          * conveniently being able to get hold of a clean state from
751          * which to practise manoeuvres.
752          */
753         qsort(ret->grid, ret->w*ret->h, sizeof(int), compare_int);
754         for (i = 0; i < ret->w*ret->h; i++)
755             ret->grid[i] &= ~3;
756         ret->used_solve = TRUE;
757         ret->completed = ret->movecount = 1;
758
759         return ret;
760     }
761
762     if (move[0] != 'M' ||
763         sscanf(move+1, "%d,%d,%d", &x, &y, &dir) != 3 ||
764         x < 0 || y < 0 || x > from->w - n || y > from->h - n)
765         return NULL;                   /* can't parse this move string */
766
767     ret = dup_game(from);
768     ret->movecount++;
769     do_rotate(ret->grid, w, h, n, ret->orientable, x, y, dir);
770     ret->lastx = x;
771     ret->lasty = y;
772     ret->lastr = dir;
773
774     /*
775      * See if the game has been completed. To do this we simply
776      * test that the grid contents are in increasing order.
777      */
778     if (!ret->completed && grid_complete(ret->grid, wh, ret->orientable))
779         ret->completed = ret->movecount;
780     return ret;
781 }
782
783 /* ----------------------------------------------------------------------
784  * Drawing routines.
785  */
786
787 static void game_compute_size(const game_params *params, int tilesize,
788                               int *x, int *y)
789 {
790     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
791     struct { int tilesize; } ads, *ds = &ads;
792     ads.tilesize = tilesize;
793
794     *x = TILE_SIZE * params->w + 2 * BORDER;
795     *y = TILE_SIZE * params->h + 2 * BORDER;
796 }
797
798 static void game_set_size(drawing *dr, game_drawstate *ds,
799                           const game_params *params, int tilesize)
800 {
801     ds->tilesize = tilesize;
802 }
803
804 static float *game_colours(frontend *fe, int *ncolours)
805 {
806     float *ret = snewn(3 * NCOLOURS, float);
807     int i;
808
809     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
810
811     /* cursor is light-background with a red tinge. */
812     ret[COL_HIGHCURSOR * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 1.0F;
813     ret[COL_HIGHCURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.5F;
814     ret[COL_HIGHCURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.5F;
815
816     for (i = 0; i < 3; i++) {
817         ret[COL_HIGHLIGHT_GENTLE * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 1.1F;
818         ret[COL_LOWLIGHT_GENTLE * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.9F;
819         ret[COL_TEXT * 3 + i] = 0.0;
820         ret[COL_LOWCURSOR * 3 + i] = ret[COL_HIGHCURSOR * 3 + i] * 0.6F;
821     }
822
823     *ncolours = NCOLOURS;
824     return ret;
825 }
826
827 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
828 {
829     struct game_drawstate *ds = snew(struct game_drawstate);
830     int i;
831
832     ds->started = FALSE;
833     ds->w = state->w;
834     ds->h = state->h;
835     ds->bgcolour = COL_BACKGROUND;
836     ds->grid = snewn(ds->w*ds->h, int);
837     ds->tilesize = 0;                  /* haven't decided yet */
838     for (i = 0; i < ds->w*ds->h; i++)
839         ds->grid[i] = -1;
840     ds->cur_x = ds->cur_y = -state->n;
841
842     return ds;
843 }
844
845 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
846 {
847     sfree(ds->grid);
848     sfree(ds);
849 }
850
851 struct rotation {
852     int cx, cy, cw, ch;                /* clip region */
853     int ox, oy;                        /* rotation origin */
854     float c, s;                        /* cos and sin of rotation angle */
855     int lc, rc, tc, bc;                /* colours of tile edges */
856 };
857
858 static void rotate(int *xy, struct rotation *rot)
859 {
860     if (rot) {
861         float xf = (float)xy[0] - rot->ox, yf = (float)xy[1] - rot->oy;
862         float xf2, yf2;
863
864         xf2 = rot->c * xf + rot->s * yf;
865         yf2 = - rot->s * xf + rot->c * yf;
866
867         xy[0] = (int)(xf2 + rot->ox + 0.5);   /* round to nearest */
868         xy[1] = (int)(yf2 + rot->oy + 0.5);   /* round to nearest */
869     }
870 }
871
872 #define CUR_TOP         1
873 #define CUR_RIGHT       2
874 #define CUR_BOTTOM      4
875 #define CUR_LEFT        8
876
877 static void draw_tile(drawing *dr, game_drawstate *ds, const game_state *state,
878                       int x, int y, int tile, int flash_colour,
879                       struct rotation *rot, unsigned cedges)
880 {
881     int coords[8];
882     char str[40];
883
884     /*
885      * If we've been passed a rotation region but we're drawing a
886      * tile which is outside it, we must draw it normally. This can
887      * occur if we're cleaning up after a completion flash while a
888      * new move is also being made.
889      */
890     if (rot && (x < rot->cx || y < rot->cy ||
891                 x >= rot->cx+rot->cw || y >= rot->cy+rot->ch))
892         rot = NULL;
893
894     if (rot)
895         clip(dr, rot->cx, rot->cy, rot->cw, rot->ch);
896
897     /*
898      * We must draw each side of the tile's highlight separately,
899      * because in some cases (during rotation) they will all need
900      * to be different colours.
901      */
902
903     /* The centre point is common to all sides. */
904     coords[4] = x + TILE_SIZE / 2;
905     coords[5] = y + TILE_SIZE / 2;
906     rotate(coords+4, rot);
907
908     /* Right side. */
909     coords[0] = x + TILE_SIZE - 1;
910     coords[1] = y + TILE_SIZE - 1;
911     rotate(coords+0, rot);
912     coords[2] = x + TILE_SIZE - 1;
913     coords[3] = y;
914     rotate(coords+2, rot);
915     draw_polygon(dr, coords, 3, rot ? rot->rc : COL_LOWLIGHT,
916                  rot ? rot->rc : (cedges & CUR_RIGHT) ? COL_LOWCURSOR : COL_LOWLIGHT);
917
918     /* Bottom side. */
919     coords[2] = x;
920     coords[3] = y + TILE_SIZE - 1;
921     rotate(coords+2, rot);
922     draw_polygon(dr, coords, 3, rot ? rot->bc : COL_LOWLIGHT,
923                  rot ? rot->bc : (cedges & CUR_BOTTOM) ? COL_LOWCURSOR : COL_LOWLIGHT);
924
925     /* Left side. */
926     coords[0] = x;
927     coords[1] = y;
928     rotate(coords+0, rot);
929     draw_polygon(dr, coords, 3, rot ? rot->lc : COL_HIGHLIGHT,
930                  rot ? rot->lc : (cedges & CUR_LEFT) ? COL_HIGHCURSOR : COL_HIGHLIGHT);
931
932     /* Top side. */
933     coords[2] = x + TILE_SIZE - 1;
934     coords[3] = y;
935     rotate(coords+2, rot);
936     draw_polygon(dr, coords, 3, rot ? rot->tc : COL_HIGHLIGHT,
937                  rot ? rot->tc : (cedges & CUR_TOP) ? COL_HIGHCURSOR : COL_HIGHLIGHT);
938
939     /*
940      * Now the main blank area in the centre of the tile.
941      */
942     if (rot) {
943         coords[0] = x + HIGHLIGHT_WIDTH;
944         coords[1] = y + HIGHLIGHT_WIDTH;
945         rotate(coords+0, rot);
946         coords[2] = x + HIGHLIGHT_WIDTH;
947         coords[3] = y + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
948         rotate(coords+2, rot);
949         coords[4] = x + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
950         coords[5] = y + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
951         rotate(coords+4, rot);
952         coords[6] = x + TILE_SIZE - 1 - HIGHLIGHT_WIDTH;
953         coords[7] = y + HIGHLIGHT_WIDTH;
954         rotate(coords+6, rot);
955         draw_polygon(dr, coords, 4, flash_colour, flash_colour);
956     } else {
957         draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
958                   TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
959                   flash_colour);
960     }
961
962     /*
963      * Next, the triangles for orientation.
964      */
965     if (state->orientable) {
966         int xdx, xdy, ydx, ydy;
967         int cx, cy, displ, displ2;
968         switch (tile & 3) {
969           case 0:
970             xdx = 1, xdy = 0;
971             ydx = 0, ydy = 1;
972             break;
973           case 1:
974             xdx = 0, xdy = -1;
975             ydx = 1, ydy = 0;
976             break;
977           case 2:
978             xdx = -1, xdy = 0;
979             ydx = 0, ydy = -1;
980             break;
981           default /* case 3 */:
982             xdx = 0, xdy = 1;
983             ydx = -1, ydy = 0;
984             break;
985         }
986
987         cx = x + TILE_SIZE / 2;
988         cy = y + TILE_SIZE / 2;
989         displ = TILE_SIZE / 2 - HIGHLIGHT_WIDTH - 2;
990         displ2 = TILE_SIZE / 3 - HIGHLIGHT_WIDTH;
991
992         coords[0] = cx - displ * xdx + displ2 * ydx;
993         coords[1] = cy - displ * xdy + displ2 * ydy;
994         rotate(coords+0, rot);
995         coords[2] = cx + displ * xdx + displ2 * ydx;
996         coords[3] = cy + displ * xdy + displ2 * ydy;
997         rotate(coords+2, rot);
998         coords[4] = cx - displ * ydx;
999         coords[5] = cy - displ * ydy;
1000         rotate(coords+4, rot);
1001         draw_polygon(dr, coords, 3, COL_LOWLIGHT_GENTLE, COL_LOWLIGHT_GENTLE);
1002     }
1003
1004     coords[0] = x + TILE_SIZE/2;
1005     coords[1] = y + TILE_SIZE/2;
1006     rotate(coords+0, rot);
1007     sprintf(str, "%d", tile / 4);
1008     draw_text(dr, coords[0], coords[1],
1009               FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
1010               COL_TEXT, str);
1011
1012     if (rot)
1013         unclip(dr);
1014
1015     draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
1016 }
1017
1018 static int highlight_colour(float angle)
1019 {
1020     int colours[32] = {
1021         COL_LOWLIGHT,
1022         COL_LOWLIGHT_GENTLE,
1023         COL_LOWLIGHT_GENTLE,
1024         COL_LOWLIGHT_GENTLE,
1025         COL_HIGHLIGHT_GENTLE,
1026         COL_HIGHLIGHT_GENTLE,
1027         COL_HIGHLIGHT_GENTLE,
1028         COL_HIGHLIGHT,
1029         COL_HIGHLIGHT,
1030         COL_HIGHLIGHT,
1031         COL_HIGHLIGHT,
1032         COL_HIGHLIGHT,
1033         COL_HIGHLIGHT,
1034         COL_HIGHLIGHT,
1035         COL_HIGHLIGHT,
1036         COL_HIGHLIGHT,
1037         COL_HIGHLIGHT,
1038         COL_HIGHLIGHT_GENTLE,
1039         COL_HIGHLIGHT_GENTLE,
1040         COL_HIGHLIGHT_GENTLE,
1041         COL_LOWLIGHT_GENTLE,
1042         COL_LOWLIGHT_GENTLE,
1043         COL_LOWLIGHT_GENTLE,
1044         COL_LOWLIGHT,
1045         COL_LOWLIGHT,
1046         COL_LOWLIGHT,
1047         COL_LOWLIGHT,
1048         COL_LOWLIGHT,
1049         COL_LOWLIGHT,
1050         COL_LOWLIGHT,
1051         COL_LOWLIGHT,
1052         COL_LOWLIGHT,
1053     };
1054
1055     return colours[(int)((angle + 2*PI) / (PI/16)) & 31];
1056 }
1057
1058 static float game_anim_length_real(const game_state *oldstate,
1059                                    const game_state *newstate, int dir,
1060                                    const game_ui *ui)
1061 {
1062     /*
1063      * Our game_anim_length doesn't need to modify its game_ui, so
1064      * this is the real function which declares ui as const. We must
1065      * wrap this for the backend structure with a version that has ui
1066      * non-const, but we still need this version to call from within
1067      * game_redraw which only has a const ui available.
1068      */
1069     return (float)(ANIM_PER_BLKSIZE_UNIT * sqrt(newstate->n-1));
1070 }
1071
1072 static float game_anim_length(const game_state *oldstate,
1073                               const game_state *newstate, int dir, game_ui *ui)
1074 {
1075     return game_anim_length_real(oldstate, newstate, dir, ui);
1076
1077 }
1078
1079 static float game_flash_length(const game_state *oldstate,
1080                                const game_state *newstate, int dir, game_ui *ui)
1081 {
1082     if (!oldstate->completed && newstate->completed &&
1083         !oldstate->used_solve && !newstate->used_solve)
1084         return 2 * FLASH_FRAME;
1085     else
1086         return 0.0F;
1087 }
1088
1089 static int game_status(const game_state *state)
1090 {
1091     return state->completed ? +1 : 0;
1092 }
1093
1094 static void game_redraw(drawing *dr, game_drawstate *ds,
1095                         const game_state *oldstate, const game_state *state,
1096                         int dir, const game_ui *ui,
1097                         float animtime, float flashtime)
1098 {
1099     int i, bgcolour;
1100     struct rotation srot, *rot;
1101     int lastx = -1, lasty = -1, lastr = -1;
1102     int cx, cy, cmoved = 0, n = state->n;
1103
1104     cx = ui->cur_visible ? ui->cur_x : -state->n;
1105     cy = ui->cur_visible ? ui->cur_y : -state->n;
1106     if (cx != ds->cur_x || cy != ds->cur_y)
1107         cmoved = 1;
1108
1109     if (flashtime > 0) {
1110         int frame = (int)(flashtime / FLASH_FRAME);
1111         bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
1112     } else
1113         bgcolour = COL_BACKGROUND;
1114
1115     if (!ds->started) {
1116         int coords[10];
1117
1118         draw_rect(dr, 0, 0,
1119                   TILE_SIZE * state->w + 2 * BORDER,
1120                   TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
1121         draw_update(dr, 0, 0,
1122                     TILE_SIZE * state->w + 2 * BORDER,
1123                     TILE_SIZE * state->h + 2 * BORDER);
1124
1125         /*
1126          * Recessed area containing the whole puzzle.
1127          */
1128         coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
1129         coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
1130         coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
1131         coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
1132         coords[4] = coords[2] - TILE_SIZE;
1133         coords[5] = coords[3] + TILE_SIZE;
1134         coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
1135         coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
1136         coords[6] = coords[8] + TILE_SIZE;
1137         coords[7] = coords[9] - TILE_SIZE;
1138         draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
1139
1140         coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
1141         coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
1142         draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
1143
1144         ds->started = TRUE;
1145     }
1146
1147     /*
1148      * If we're drawing any rotated tiles, sort out the rotation
1149      * parameters, and also zap the rotation region to the
1150      * background colour before doing anything else.
1151      */
1152     if (oldstate) {
1153         float angle;
1154         float anim_max = game_anim_length_real(oldstate, state, dir, ui);
1155
1156         if (dir > 0) {
1157             lastx = state->lastx;
1158             lasty = state->lasty;
1159             lastr = state->lastr;
1160         } else {
1161             lastx = oldstate->lastx;
1162             lasty = oldstate->lasty;
1163             lastr = -oldstate->lastr;
1164         }
1165
1166         rot = &srot;
1167         rot->cx = COORD(lastx);
1168         rot->cy = COORD(lasty);
1169         rot->cw = rot->ch = TILE_SIZE * state->n;
1170         rot->ox = rot->cx + rot->cw/2;
1171         rot->oy = rot->cy + rot->ch/2;
1172         angle = (float)((-PI/2 * lastr) * (1.0 - animtime / anim_max));
1173         rot->c = (float)cos(angle);
1174         rot->s = (float)sin(angle);
1175
1176         /*
1177          * Sort out the colours of the various sides of the tile.
1178          */
1179         rot->lc = highlight_colour((float)PI + angle);
1180         rot->rc = highlight_colour(angle);
1181         rot->tc = highlight_colour((float)(PI/2.0) + angle);
1182         rot->bc = highlight_colour((float)(-PI/2.0) + angle);
1183
1184         draw_rect(dr, rot->cx, rot->cy, rot->cw, rot->ch, bgcolour);
1185     } else
1186         rot = NULL;
1187
1188     /*
1189      * Now draw each tile.
1190      */
1191     for (i = 0; i < state->w * state->h; i++) {
1192         int t, cc = 0;
1193         int tx = i % state->w, ty = i / state->w;
1194
1195         /*
1196          * Figure out what should be displayed at this location.
1197          * Usually it will be state->grid[i], unless we're in the
1198          * middle of animating an actual rotation and this cell is
1199          * within the rotation region, in which case we set -1
1200          * (always display).
1201          */
1202         if (oldstate && lastx >= 0 && lasty >= 0 &&
1203             tx >= lastx && tx < lastx + state->n &&
1204             ty >= lasty && ty < lasty + state->n)
1205             t = -1;
1206         else
1207             t = state->grid[i];
1208
1209         if (cmoved) {
1210             /* cursor has moved (or changed visibility)... */
1211             if (tx == cx || tx == cx+n-1 || ty == cy || ty == cy+n-1)
1212                 cc = 1; /* ...we're on new cursor, redraw */
1213             if (tx == ds->cur_x || tx == ds->cur_x+n-1 ||
1214                 ty == ds->cur_y || ty == ds->cur_y+n-1)
1215                 cc = 1; /* ...we were on old cursor, redraw */
1216         }
1217
1218         if (ds->bgcolour != bgcolour ||   /* always redraw when flashing */
1219             ds->grid[i] != t || ds->grid[i] == -1 || t == -1 || cc) {
1220             int x = COORD(tx), y = COORD(ty);
1221             unsigned cedges = 0;
1222
1223             if (tx == cx     && ty >= cy && ty <= cy+n-1) cedges |= CUR_LEFT;
1224             if (ty == cy     && tx >= cx && tx <= cx+n-1) cedges |= CUR_TOP;
1225             if (tx == cx+n-1 && ty >= cy && ty <= cy+n-1) cedges |= CUR_RIGHT;
1226             if (ty == cy+n-1 && tx >= cx && tx <= cx+n-1) cedges |= CUR_BOTTOM;
1227
1228             draw_tile(dr, ds, state, x, y, state->grid[i], bgcolour, rot, cedges);
1229             ds->grid[i] = t;
1230         }
1231     }
1232     ds->bgcolour = bgcolour;
1233     ds->cur_x = cx; ds->cur_y = cy;
1234
1235     /*
1236      * Update the status bar.
1237      */
1238     {
1239         char statusbuf[256];
1240
1241         /*
1242          * Don't show the new status until we're also showing the
1243          * new _state_ - after the game animation is complete.
1244          */
1245         if (oldstate)
1246             state = oldstate;
1247
1248         if (state->used_solve)
1249             sprintf(statusbuf, "Moves since auto-solve: %d",
1250                     state->movecount - state->completed);
1251         else {
1252             sprintf(statusbuf, "%sMoves: %d",
1253                     (state->completed ? "COMPLETED! " : ""),
1254                     (state->completed ? state->completed : state->movecount));
1255             if (state->movetarget)
1256                 sprintf(statusbuf+strlen(statusbuf), " (target %d)",
1257                         state->movetarget);
1258         }
1259
1260         status_bar(dr, statusbuf);
1261     }
1262 }
1263
1264 static int game_timing_state(const game_state *state, game_ui *ui)
1265 {
1266     return TRUE;
1267 }
1268
1269 static void game_print_size(const game_params *params, float *x, float *y)
1270 {
1271 }
1272
1273 static void game_print(drawing *dr, const game_state *state, int tilesize)
1274 {
1275 }
1276
1277 #ifdef COMBINED
1278 #define thegame twiddle
1279 #endif
1280
1281 const struct game thegame = {
1282     "Twiddle", "games.twiddle", "twiddle",
1283     default_params,
1284     game_fetch_preset,
1285     decode_params,
1286     encode_params,
1287     free_params,
1288     dup_params,
1289     TRUE, game_configure, custom_params,
1290     validate_params,
1291     new_game_desc,
1292     validate_desc,
1293     new_game,
1294     dup_game,
1295     free_game,
1296     TRUE, solve_game,
1297     TRUE, game_can_format_as_text_now, game_text_format,
1298     new_ui,
1299     free_ui,
1300     encode_ui,
1301     decode_ui,
1302     game_changed_state,
1303     interpret_move,
1304     execute_move,
1305     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1306     game_colours,
1307     game_new_drawstate,
1308     game_free_drawstate,
1309     game_redraw,
1310     game_anim_length,
1311     game_flash_length,
1312     game_status,
1313     FALSE, FALSE, game_print_size, game_print,
1314     TRUE,                              /* wants_statusbar */
1315     FALSE, game_timing_state,
1316     0,                                 /* flags */
1317 };
1318
1319 /* vim: set shiftwidth=4 tabstop=8: */