chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[sgt-puzzles.git] / sixteen.c
1 /*
2  * sixteen.c: `16-puzzle', a sliding-tiles jigsaw which differs
3  * from the 15-puzzle in that you toroidally rotate a row or column
4  * at a time.
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <assert.h>
11 #include <ctype.h>
12 #include <math.h>
13
14 #include "puzzles.h"
15
16 #define PREFERRED_TILE_SIZE 48
17 #define TILE_SIZE (ds->tilesize)
18 #define BORDER TILE_SIZE
19 #define HIGHLIGHT_WIDTH (TILE_SIZE / 20)
20 #define COORD(x)  ( (x) * TILE_SIZE + BORDER )
21 #define FROMCOORD(x)  ( ((x) - BORDER + 2*TILE_SIZE) / TILE_SIZE - 2 )
22
23 #define ANIM_TIME 0.13F
24 #define FLASH_FRAME 0.13F
25
26 #define X(state, i) ( (i) % (state)->w )
27 #define Y(state, i) ( (i) / (state)->w )
28 #define C(state, x, y) ( (y) * (state)->w + (x) )
29
30 #define TILE_CURSOR(i, state, x, y) ((i) == C((state), (x), (y)) &&     \
31                                      0 <= (x) && (x) < (state)->w &&    \
32                                      0 <= (y) && (y) < (state)->h)
33 enum {
34     COL_BACKGROUND,
35     COL_TEXT,
36     COL_HIGHLIGHT,
37     COL_LOWLIGHT,
38     NCOLOURS
39 };
40
41 struct game_params {
42     int w, h;
43     int movetarget;
44 };
45
46 struct game_state {
47     int w, h, n;
48     int *tiles;
49     int completed;
50     int used_solve;                    /* used to suppress completion flash */
51     int movecount, movetarget;
52     int last_movement_sense;
53 };
54
55 static game_params *default_params(void)
56 {
57     game_params *ret = snew(game_params);
58
59     ret->w = ret->h = 4;
60     ret->movetarget = 0;
61
62     return ret;
63 }
64
65 static int game_fetch_preset(int i, char **name, game_params **params)
66 {
67     game_params *ret;
68     int w, h;
69     char buf[80];
70
71     switch (i) {
72       case 0: w = 3, h = 3; break;
73       case 1: w = 4, h = 3; break;
74       case 2: w = 4, h = 4; break;
75       case 3: w = 5, h = 4; break;
76       case 4: w = 5, h = 5; break;
77       default: return FALSE;
78     }
79
80     sprintf(buf, "%dx%d", w, h);
81     *name = dupstr(buf);
82     *params = ret = snew(game_params);
83     ret->w = w;
84     ret->h = h;
85     ret->movetarget = 0;
86     return TRUE;
87 }
88
89 static void free_params(game_params *params)
90 {
91     sfree(params);
92 }
93
94 static game_params *dup_params(const game_params *params)
95 {
96     game_params *ret = snew(game_params);
97     *ret = *params;                    /* structure copy */
98     return ret;
99 }
100
101 static void decode_params(game_params *ret, char const *string)
102 {
103     ret->w = ret->h = atoi(string);
104     ret->movetarget = 0;
105     while (*string && isdigit((unsigned char)*string)) string++;
106     if (*string == 'x') {
107         string++;
108         ret->h = atoi(string);
109         while (*string && isdigit((unsigned char)*string))
110             string++;
111     }
112     if (*string == 'm') {
113         string++;
114         ret->movetarget = atoi(string);
115         while (*string && isdigit((unsigned char)*string))
116             string++;
117     }
118 }
119
120 static char *encode_params(const game_params *params, int full)
121 {
122     char data[256];
123
124     sprintf(data, "%dx%d", params->w, params->h);
125     /* Shuffle limit is part of the limited parameters, because we have to
126      * supply the target move count. */
127     if (params->movetarget)
128         sprintf(data + strlen(data), "m%d", params->movetarget);
129
130     return dupstr(data);
131 }
132
133 static config_item *game_configure(const game_params *params)
134 {
135     config_item *ret;
136     char buf[80];
137
138     ret = snewn(4, config_item);
139
140     ret[0].name = "Width";
141     ret[0].type = C_STRING;
142     sprintf(buf, "%d", params->w);
143     ret[0].u.string.sval = dupstr(buf);
144
145     ret[1].name = "Height";
146     ret[1].type = C_STRING;
147     sprintf(buf, "%d", params->h);
148     ret[1].u.string.sval = dupstr(buf);
149
150     ret[2].name = "Number of shuffling moves";
151     ret[2].type = C_STRING;
152     sprintf(buf, "%d", params->movetarget);
153     ret[2].u.string.sval = dupstr(buf);
154
155     ret[3].name = NULL;
156     ret[3].type = C_END;
157
158     return ret;
159 }
160
161 static game_params *custom_params(const config_item *cfg)
162 {
163     game_params *ret = snew(game_params);
164
165     ret->w = atoi(cfg[0].u.string.sval);
166     ret->h = atoi(cfg[1].u.string.sval);
167     ret->movetarget = atoi(cfg[2].u.string.sval);
168
169     return ret;
170 }
171
172 static const char *validate_params(const game_params *params, int full)
173 {
174     if (params->w < 2 || params->h < 2)
175         return "Width and height must both be at least two";
176
177     return NULL;
178 }
179
180 static int perm_parity(int *perm, int n)
181 {
182     int i, j, ret;
183
184     ret = 0;
185
186     for (i = 0; i < n-1; i++)
187         for (j = i+1; j < n; j++)
188             if (perm[i] > perm[j])
189                 ret = !ret;
190
191     return ret;
192 }
193
194 static char *new_game_desc(const game_params *params, random_state *rs,
195                            char **aux, int interactive)
196 {
197     int stop, n, i, x;
198     int x1, x2, p1, p2;
199     int *tiles, *used;
200     char *ret;
201     int retlen;
202
203     n = params->w * params->h;
204
205     tiles = snewn(n, int);
206
207     if (params->movetarget) {
208         int prevoffset = -1;
209         int max = (params->w > params->h ? params->w : params->h);
210         int *prevmoves = snewn(max, int);
211
212         /*
213          * Shuffle the old-fashioned way, by making a series of
214          * single moves on the grid.
215          */
216
217         for (i = 0; i < n; i++)
218             tiles[i] = i;
219
220         for (i = 0; i < params->movetarget; i++) {
221             int start, offset, len, direction, index;
222             int j, tmp;
223
224             /*
225              * Choose a move to make. We can choose from any row
226              * or any column.
227              */
228             while (1) {
229                 j = random_upto(rs, params->w + params->h);
230
231                 if (j < params->w) {
232                     /* Column. */
233                     index = j;
234                     start = j;
235                     offset = params->w;
236                     len = params->h;
237                 } else {
238                     /* Row. */
239                     index = j - params->w;
240                     start = index * params->w;
241                     offset = 1;
242                     len = params->w;
243                 }
244
245                 direction = -1 + 2 * random_upto(rs, 2);
246
247                 /*
248                  * To at least _try_ to avoid boring cases, check
249                  * that this move doesn't directly undo a previous
250                  * one, or repeat it so many times as to turn it
251                  * into fewer moves in the opposite direction. (For
252                  * example, in a row of length 4, we're allowed to
253                  * move it the same way twice, but not three
254                  * times.)
255                  * 
256                  * We track this for each individual row/column,
257                  * and clear all the counters as soon as a
258                  * perpendicular move is made. This isn't perfect
259                  * (it _can't_ guaranteeably be perfect - there
260                  * will always come a move count beyond which a
261                  * shorter solution will be possible than the one
262                  * which constructed the position) but it should
263                  * sort out all the obvious cases.
264                  */
265                 if (offset == prevoffset) {
266                     tmp = prevmoves[index] + direction;
267                     if (abs(2*tmp) > len || abs(tmp) < abs(prevmoves[index]))
268                         continue;
269                 }
270
271                 /* If we didn't `continue', we've found an OK move to make. */
272                 if (offset != prevoffset) {
273                     int i;
274                     for (i = 0; i < max; i++)
275                         prevmoves[i] = 0;
276                     prevoffset = offset;
277                 }
278                 prevmoves[index] += direction;
279                 break;
280             }
281
282             /*
283              * Make the move.
284              */
285             if (direction < 0) {
286                 start += (len-1) * offset;
287                 offset = -offset;
288             }
289             tmp = tiles[start];
290             for (j = 0; j+1 < len; j++)
291                 tiles[start + j*offset] = tiles[start + (j+1)*offset];
292             tiles[start + (len-1) * offset] = tmp;
293         }
294
295         sfree(prevmoves);
296
297     } else {
298
299         used = snewn(n, int);
300
301         for (i = 0; i < n; i++) {
302             tiles[i] = -1;
303             used[i] = FALSE;
304         }
305
306         /*
307          * If both dimensions are odd, there is a parity
308          * constraint.
309          */
310         if (params->w & params->h & 1)
311             stop = 2;
312         else
313             stop = 0;
314
315         /*
316          * Place everything except (possibly) the last two tiles.
317          */
318         for (x = 0, i = n; i > stop; i--) {
319             int k = i > 1 ? random_upto(rs, i) : 0;
320             int j;
321
322             for (j = 0; j < n; j++)
323                 if (!used[j] && (k-- == 0))
324                     break;
325
326             assert(j < n && !used[j]);
327             used[j] = TRUE;
328
329             while (tiles[x] >= 0)
330                 x++;
331             assert(x < n);
332             tiles[x] = j;
333         }
334
335         if (stop) {
336             /*
337              * Find the last two locations, and the last two
338              * pieces.
339              */
340             while (tiles[x] >= 0)
341                 x++;
342             assert(x < n);
343             x1 = x;
344             x++;
345             while (tiles[x] >= 0)
346                 x++;
347             assert(x < n);
348             x2 = x;
349
350             for (i = 0; i < n; i++)
351                 if (!used[i])
352                     break;
353             p1 = i;
354             for (i = p1+1; i < n; i++)
355                 if (!used[i])
356                     break;
357             p2 = i;
358
359             /*
360              * Try the last two tiles one way round. If that fails,
361              * swap them.
362              */
363             tiles[x1] = p1;
364             tiles[x2] = p2;
365             if (perm_parity(tiles, n) != 0) {
366                 tiles[x1] = p2;
367                 tiles[x2] = p1;
368                 assert(perm_parity(tiles, n) == 0);
369             }
370         }
371
372         sfree(used);
373     }
374
375     /*
376      * Now construct the game description, by describing the tile
377      * array as a simple sequence of comma-separated integers.
378      */
379     ret = NULL;
380     retlen = 0;
381     for (i = 0; i < n; i++) {
382         char buf[80];
383         int k;
384
385         k = sprintf(buf, "%d,", tiles[i]+1);
386
387         ret = sresize(ret, retlen + k + 1, char);
388         strcpy(ret + retlen, buf);
389         retlen += k;
390     }
391     ret[retlen-1] = '\0';              /* delete last comma */
392
393     sfree(tiles);
394
395     return ret;
396 }
397
398
399 static const char *validate_desc(const game_params *params, const char *desc)
400 {
401     const char *p, *err;
402     int i, area;
403     int *used;
404
405     area = params->w * params->h;
406     p = desc;
407     err = NULL;
408
409     used = snewn(area, int);
410     for (i = 0; i < area; i++)
411         used[i] = FALSE;
412
413     for (i = 0; i < area; i++) {
414         const char *q = p;
415         int n;
416
417         if (*p < '0' || *p > '9') {
418             err = "Not enough numbers in string";
419             goto leave;
420         }
421         while (*p >= '0' && *p <= '9')
422             p++;
423         if (i < area-1 && *p != ',') {
424             err = "Expected comma after number";
425             goto leave;
426         }
427         else if (i == area-1 && *p) {
428             err = "Excess junk at end of string";
429             goto leave;
430         }
431         n = atoi(q);
432         if (n < 1 || n > area) {
433             err = "Number out of range";
434             goto leave;
435         }
436         if (used[n-1]) {
437             err = "Number used twice";
438             goto leave;
439         }
440         used[n-1] = TRUE;
441
442         if (*p) p++;                   /* eat comma */
443     }
444
445     leave:
446     sfree(used);
447     return err;
448 }
449
450 static game_state *new_game(midend *me, const game_params *params,
451                             const char *desc)
452 {
453     game_state *state = snew(game_state);
454     int i;
455     const char *p;
456
457     state->w = params->w;
458     state->h = params->h;
459     state->n = params->w * params->h;
460     state->tiles = snewn(state->n, int);
461
462     p = desc;
463     i = 0;
464     for (i = 0; i < state->n; i++) {
465         assert(*p);
466         state->tiles[i] = atoi(p);
467         while (*p && *p != ',')
468             p++;
469         if (*p) p++;                   /* eat comma */
470     }
471     assert(!*p);
472
473     state->completed = state->movecount = 0;
474     state->movetarget = params->movetarget;
475     state->used_solve = FALSE;
476     state->last_movement_sense = 0;
477
478     return state;
479 }
480
481 static game_state *dup_game(const game_state *state)
482 {
483     game_state *ret = snew(game_state);
484
485     ret->w = state->w;
486     ret->h = state->h;
487     ret->n = state->n;
488     ret->tiles = snewn(state->w * state->h, int);
489     memcpy(ret->tiles, state->tiles, state->w * state->h * sizeof(int));
490     ret->completed = state->completed;
491     ret->movecount = state->movecount;
492     ret->movetarget = state->movetarget;
493     ret->used_solve = state->used_solve;
494     ret->last_movement_sense = state->last_movement_sense;
495
496     return ret;
497 }
498
499 static void free_game(game_state *state)
500 {
501     sfree(state->tiles);
502     sfree(state);
503 }
504
505 static char *solve_game(const game_state *state, const game_state *currstate,
506                         const char *aux, const char **error)
507 {
508     return dupstr("S");
509 }
510
511 static int game_can_format_as_text_now(const game_params *params)
512 {
513     return TRUE;
514 }
515
516 static char *game_text_format(const game_state *state)
517 {
518     char *ret, *p, buf[80];
519     int x, y, col, maxlen;
520
521     /*
522      * First work out how many characters we need to display each
523      * number.
524      */
525     col = sprintf(buf, "%d", state->n);
526
527     /*
528      * Now we know the exact total size of the grid we're going to
529      * produce: it's got h rows, each containing w lots of col, w-1
530      * spaces and a trailing newline.
531      */
532     maxlen = state->h * state->w * (col+1);
533
534     ret = snewn(maxlen+1, char);
535     p = ret;
536
537     for (y = 0; y < state->h; y++) {
538         for (x = 0; x < state->w; x++) {
539             int v = state->tiles[state->w*y+x];
540             sprintf(buf, "%*d", col, v);
541             memcpy(p, buf, col);
542             p += col;
543             if (x+1 == state->w)
544                 *p++ = '\n';
545             else
546                 *p++ = ' ';
547         }
548     }
549
550     assert(p - ret == maxlen);
551     *p = '\0';
552     return ret;
553 }
554
555 enum cursor_mode { unlocked, lock_tile, lock_position };
556
557 struct game_ui {
558     int cur_x, cur_y;
559     int cur_visible;
560     enum cursor_mode cur_mode;
561 };
562
563 static game_ui *new_ui(const game_state *state)
564 {
565     game_ui *ui = snew(game_ui);
566     ui->cur_x = 0;
567     ui->cur_y = 0;
568     ui->cur_visible = FALSE;
569     ui->cur_mode = unlocked;
570
571     return ui;
572 }
573
574 static void free_ui(game_ui *ui)
575 {
576     sfree(ui);
577 }
578
579 static char *encode_ui(const game_ui *ui)
580 {
581     return NULL;
582 }
583
584 static void decode_ui(game_ui *ui, const char *encoding)
585 {
586 }
587
588 static void game_changed_state(game_ui *ui, const game_state *oldstate,
589                                const game_state *newstate)
590 {
591 }
592
593 struct game_drawstate {
594     int started;
595     int w, h, bgcolour;
596     int *tiles;
597     int tilesize;
598     int cur_x, cur_y;
599 };
600
601 static char *interpret_move(const game_state *state, game_ui *ui,
602                             const game_drawstate *ds,
603                             int x, int y, int button)
604 {
605     int cx = -1, cy = -1, dx, dy;
606     char buf[80];
607     int shift = button & MOD_SHFT, control = button & MOD_CTRL,
608         pad = button & MOD_NUM_KEYPAD;
609
610     button &= ~MOD_MASK;
611
612     if (IS_CURSOR_MOVE(button) || pad) {
613         if (!ui->cur_visible) {
614             ui->cur_visible = 1;
615             return UI_UPDATE;
616         }
617
618         if (control || shift || ui->cur_mode) {
619             int x = ui->cur_x, y = ui->cur_y, xwrap = x, ywrap = y;
620             if (x < 0 || x >= state->w || y < 0 || y >= state->h)
621                 return NULL;
622             move_cursor(button | pad, &x, &y,
623                         state->w, state->h, FALSE);
624             move_cursor(button | pad, &xwrap, &ywrap,
625                         state->w, state->h, TRUE);
626
627             if (x != xwrap) {
628                 sprintf(buf, "R%d,%c1", y, x ? '+' : '-');
629             } else if (y != ywrap) {
630                 sprintf(buf, "C%d,%c1", x, y ? '+' : '-');
631             } else if (x == ui->cur_x)
632                 sprintf(buf, "C%d,%d", x, y - ui->cur_y);
633             else
634                 sprintf(buf, "R%d,%d", y, x - ui->cur_x);
635
636             if (control || (!shift && ui->cur_mode == lock_tile)) {
637                 ui->cur_x = xwrap;
638                 ui->cur_y = ywrap;
639             }
640
641             return dupstr(buf);
642         } else {
643             int x = ui->cur_x + 1, y = ui->cur_y + 1;
644
645             move_cursor(button | pad, &x, &y,
646                         state->w + 2, state->h + 2, FALSE);
647
648             if (x == 0 && y == 0) {
649                 int t = ui->cur_x;
650                 ui->cur_x = ui->cur_y;
651                 ui->cur_y = t;
652             } else if (x == 0 && y == state->h + 1) {
653                 int t = ui->cur_x;
654                 ui->cur_x = (state->h - 1) - ui->cur_y;
655                 ui->cur_y = (state->h - 1) - t;
656             } else if (x == state->w + 1 && y == 0) {
657                 int t = ui->cur_x;
658                 ui->cur_x = (state->w - 1) - ui->cur_y;
659                 ui->cur_y = (state->w - 1) - t;
660             } else if (x == state->w + 1 && y == state->h + 1) {
661                 int t = ui->cur_x;
662                 ui->cur_x = state->w - state->h + ui->cur_y;
663                 ui->cur_y = state->h - state->w + t;
664             } else {
665                 ui->cur_x = x - 1;
666                 ui->cur_y = y - 1;
667             }
668
669             ui->cur_visible = 1;
670             return UI_UPDATE;
671         }
672     }
673
674     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
675         cx = FROMCOORD(x);
676         cy = FROMCOORD(y);
677         ui->cur_visible = 0;
678     } else if (IS_CURSOR_SELECT(button)) {
679         if (ui->cur_visible) {
680             if (ui->cur_x == -1 || ui->cur_x == state->w ||
681                 ui->cur_y == -1 || ui->cur_y == state->h) {
682                 cx = ui->cur_x;
683                 cy = ui->cur_y;
684             } else {
685                 const enum cursor_mode m = (button == CURSOR_SELECT2 ?
686                                             lock_position : lock_tile);
687                 ui->cur_mode = (ui->cur_mode == m ? unlocked : m);
688                 return UI_UPDATE;
689             }
690         } else {
691             ui->cur_visible = 1;
692             return UI_UPDATE;
693         }
694     } else {
695         return NULL;
696     }
697
698     if (cx == -1 && cy >= 0 && cy < state->h)
699         dx = -1, dy = 0;
700     else if (cx == state->w && cy >= 0 && cy < state->h)
701         dx = +1, dy = 0;
702     else if (cy == -1 && cx >= 0 && cx < state->w)
703         dy = -1, dx = 0;
704     else if (cy == state->h && cx >= 0 && cx < state->w)
705         dy = +1, dx = 0;
706     else
707         return UI_UPDATE;            /* invalid click location */
708
709     /* reverse direction if right hand button is pressed */
710     if (button == RIGHT_BUTTON || button == CURSOR_SELECT2) {
711         dx = -dx;
712         dy = -dy;
713     }
714
715     if (dx)
716         sprintf(buf, "R%d,%d", cy, dx);
717     else
718         sprintf(buf, "C%d,%d", cx, dy);
719     return dupstr(buf);
720 }
721
722 static game_state *execute_move(const game_state *from, const char *move)
723 {
724     int cx, cy, dx, dy;
725     int tx, ty, n;
726     game_state *ret;
727
728     if (!strcmp(move, "S")) {
729         int i;
730
731         ret = dup_game(from);
732
733         /*
734          * Simply replace the grid with a solved one. For this game,
735          * this isn't a useful operation for actually telling the user
736          * what they should have done, but it is useful for
737          * conveniently being able to get hold of a clean state from
738          * which to practise manoeuvres.
739          */
740         for (i = 0; i < ret->n; i++)
741             ret->tiles[i] = i+1;
742         ret->used_solve = TRUE;
743         ret->completed = ret->movecount = 1;
744
745         return ret;
746     }
747
748     if (move[0] == 'R' && sscanf(move+1, "%d,%d", &cy, &dx) == 2 &&
749         cy >= 0 && cy < from->h) {
750         cx = dy = 0;
751         n = from->w;
752     } else if (move[0] == 'C' && sscanf(move+1, "%d,%d", &cx, &dy) == 2 &&
753                cx >= 0 && cx < from->w) {
754         cy = dx = 0;
755         n = from->h;
756     } else
757         return NULL;
758
759     ret = dup_game(from);
760
761     do {
762         tx = (cx - dx + from->w) % from->w;
763         ty = (cy - dy + from->h) % from->h;
764         ret->tiles[C(ret, cx, cy)] = from->tiles[C(from, tx, ty)];
765         cx = tx;
766         cy = ty;
767     } while (--n > 0);
768
769     ret->movecount++;
770
771     ret->last_movement_sense = dx+dy;
772
773     /*
774      * See if the game has been completed.
775      */
776     if (!ret->completed) {
777         ret->completed = ret->movecount;
778         for (n = 0; n < ret->n; n++)
779             if (ret->tiles[n] != n+1)
780                 ret->completed = FALSE;
781     }
782
783     return ret;
784 }
785
786 /* ----------------------------------------------------------------------
787  * Drawing routines.
788  */
789
790 static void game_compute_size(const game_params *params, int tilesize,
791                               int *x, int *y)
792 {
793     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
794     struct { int tilesize; } ads, *ds = &ads;
795     ads.tilesize = tilesize;
796
797     *x = TILE_SIZE * params->w + 2 * BORDER;
798     *y = TILE_SIZE * params->h + 2 * BORDER;
799 }
800
801 static void game_set_size(drawing *dr, game_drawstate *ds,
802                           const game_params *params, int tilesize)
803 {
804     ds->tilesize = tilesize;
805 }
806
807 static float *game_colours(frontend *fe, int *ncolours)
808 {
809     float *ret = snewn(3 * NCOLOURS, float);
810     int i;
811
812     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
813
814     for (i = 0; i < 3; i++)
815         ret[COL_TEXT * 3 + i] = 0.0;
816
817     *ncolours = NCOLOURS;
818     return ret;
819 }
820
821 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
822 {
823     struct game_drawstate *ds = snew(struct game_drawstate);
824     int i;
825
826     ds->started = FALSE;
827     ds->w = state->w;
828     ds->h = state->h;
829     ds->bgcolour = COL_BACKGROUND;
830     ds->tiles = snewn(ds->w*ds->h, int);
831     ds->tilesize = 0;                  /* haven't decided yet */
832     for (i = 0; i < ds->w*ds->h; i++)
833         ds->tiles[i] = -1;
834     ds->cur_x = ds->cur_y = -1;
835
836     return ds;
837 }
838
839 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
840 {
841     sfree(ds->tiles);
842     sfree(ds);
843 }
844
845 static void draw_tile(drawing *dr, game_drawstate *ds,
846                       const game_state *state, int x, int y,
847                       int tile, int flash_colour)
848 {
849     if (tile == 0) {
850         draw_rect(dr, x, y, TILE_SIZE, TILE_SIZE,
851                   flash_colour);
852     } else {
853         int coords[6];
854         char str[40];
855
856         coords[0] = x + TILE_SIZE - 1;
857         coords[1] = y + TILE_SIZE - 1;
858         coords[2] = x + TILE_SIZE - 1;
859         coords[3] = y;
860         coords[4] = x;
861         coords[5] = y + TILE_SIZE - 1;
862         draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
863
864         coords[0] = x;
865         coords[1] = y;
866         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
867
868         draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
869                   TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
870                   flash_colour);
871
872         sprintf(str, "%d", tile);
873         draw_text(dr, x + TILE_SIZE/2, y + TILE_SIZE/2,
874                   FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
875                   COL_TEXT, str);
876     }
877     draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
878 }
879
880 static void draw_arrow(drawing *dr, game_drawstate *ds,
881                        int x, int y, int xdx, int xdy, int cur)
882 {
883     int coords[14];
884     int ydy = -xdx, ydx = xdy;
885
886 #define POINT(n, xx, yy) ( \
887     coords[2*(n)+0] = x + (xx)*xdx + (yy)*ydx, \
888     coords[2*(n)+1] = y + (xx)*xdy + (yy)*ydy)
889
890     POINT(0, TILE_SIZE / 2, 3 * TILE_SIZE / 4);   /* top of arrow */
891     POINT(1, 3 * TILE_SIZE / 4, TILE_SIZE / 2);   /* right corner */
892     POINT(2, 5 * TILE_SIZE / 8, TILE_SIZE / 2);   /* right concave */
893     POINT(3, 5 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom right */
894     POINT(4, 3 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom left */
895     POINT(5, 3 * TILE_SIZE / 8, TILE_SIZE / 2);   /* left concave */
896     POINT(6,     TILE_SIZE / 4, TILE_SIZE / 2);   /* left corner */
897
898     draw_polygon(dr, coords, 7, cur ? COL_HIGHLIGHT : COL_LOWLIGHT, COL_TEXT);
899 }
900
901 static void draw_arrow_for_cursor(drawing *dr, game_drawstate *ds,
902                                   int cur_x, int cur_y, int cur)
903 {
904     if (cur_x == -1 && cur_y == -1)
905         return; /* 'no cursur here */
906     else if (cur_x == -1) /* LH column. */
907         draw_arrow(dr, ds, COORD(0), COORD(cur_y+1), 0, -1, cur);
908     else if (cur_x == ds->w) /* RH column */
909         draw_arrow(dr, ds, COORD(ds->w), COORD(cur_y), 0, +1, cur);
910     else if (cur_y == -1) /* Top row */
911         draw_arrow(dr, ds, COORD(cur_x), COORD(0), +1, 0, cur);
912     else if (cur_y == ds->h) /* Bottom row */
913         draw_arrow(dr, ds, COORD(cur_x+1), COORD(ds->h), -1, 0, cur);
914     else
915         return;
916
917     draw_update(dr, COORD(cur_x), COORD(cur_y),
918                 TILE_SIZE, TILE_SIZE);
919 }
920
921 static void game_redraw(drawing *dr, game_drawstate *ds,
922                         const game_state *oldstate, const game_state *state,
923                         int dir, const game_ui *ui,
924                         float animtime, float flashtime)
925 {
926     int i, bgcolour;
927     int cur_x = -1, cur_y = -1;
928
929     if (flashtime > 0) {
930         int frame = (int)(flashtime / FLASH_FRAME);
931         bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
932     } else
933         bgcolour = COL_BACKGROUND;
934
935     if (!ds->started) {
936         int coords[10];
937
938         draw_rect(dr, 0, 0,
939                   TILE_SIZE * state->w + 2 * BORDER,
940                   TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
941         draw_update(dr, 0, 0,
942                     TILE_SIZE * state->w + 2 * BORDER,
943                     TILE_SIZE * state->h + 2 * BORDER);
944
945         /*
946          * Recessed area containing the whole puzzle.
947          */
948         coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
949         coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
950         coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
951         coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
952         coords[4] = coords[2] - TILE_SIZE;
953         coords[5] = coords[3] + TILE_SIZE;
954         coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
955         coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
956         coords[6] = coords[8] + TILE_SIZE;
957         coords[7] = coords[9] - TILE_SIZE;
958         draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
959
960         coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
961         coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
962         draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
963
964         /*
965          * Arrows for making moves.
966          */
967         for (i = 0; i < state->w; i++) {
968             draw_arrow(dr, ds, COORD(i), COORD(0), +1, 0, 0);
969             draw_arrow(dr, ds, COORD(i+1), COORD(state->h), -1, 0, 0);
970         }
971         for (i = 0; i < state->h; i++) {
972             draw_arrow(dr, ds, COORD(state->w), COORD(i), 0, +1, 0);
973             draw_arrow(dr, ds, COORD(0), COORD(i+1), 0, -1, 0);
974         }
975
976         ds->started = TRUE;
977     }
978     /*
979      * Cursor (highlighted arrow around edge)
980      */
981     if (ui->cur_visible) {
982         cur_x = ui->cur_x; cur_y = ui->cur_y;
983     }
984
985     if (cur_x != ds->cur_x || cur_y != ds->cur_y) {
986         /* Cursor has changed; redraw two (prev and curr) arrows. */
987         draw_arrow_for_cursor(dr, ds, cur_x, cur_y, 1);
988         draw_arrow_for_cursor(dr, ds, ds->cur_x, ds->cur_y, 0);
989     }
990
991     /*
992      * Now draw each tile.
993      */
994
995     clip(dr, COORD(0), COORD(0), TILE_SIZE*state->w, TILE_SIZE*state->h);
996
997     for (i = 0; i < state->n; i++) {
998         int t, t0;
999         /*
1000          * Figure out what should be displayed at this
1001          * location. It's either a simple tile, or it's a
1002          * transition between two tiles (in which case we say
1003          * -1 because it must always be drawn).
1004          */
1005
1006         if (oldstate && oldstate->tiles[i] != state->tiles[i])
1007             t = -1;
1008         else
1009             t = state->tiles[i];
1010
1011         t0 = t;
1012
1013         if (ds->bgcolour != bgcolour ||   /* always redraw when flashing */
1014             ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1 ||
1015             ((ds->cur_x != cur_x || ds->cur_y != cur_y) && /* cursor moved */
1016              (TILE_CURSOR(i, state, ds->cur_x, ds->cur_y) ||
1017               TILE_CURSOR(i, state, cur_x, cur_y)))) {
1018             int x, y, x2, y2;
1019
1020             /*
1021              * Figure out what to _actually_ draw, and where to
1022              * draw it.
1023              */
1024             if (t == -1) {
1025                 int x0, y0, x1, y1, dx, dy;
1026                 int j;
1027                 float c;
1028                 int sense;
1029
1030                 if (dir < 0) {
1031                     assert(oldstate);
1032                     sense = -oldstate->last_movement_sense;
1033                 } else {
1034                     sense = state->last_movement_sense;
1035                 }
1036
1037                 t = state->tiles[i];
1038
1039                 /*
1040                  * FIXME: must be prepared to draw a double
1041                  * tile in some situations.
1042                  */
1043
1044                 /*
1045                  * Find the coordinates of this tile in the old and
1046                  * new states.
1047                  */
1048                 x1 = COORD(X(state, i));
1049                 y1 = COORD(Y(state, i));
1050                 for (j = 0; j < oldstate->n; j++)
1051                     if (oldstate->tiles[j] == state->tiles[i])
1052                         break;
1053                 assert(j < oldstate->n);
1054                 x0 = COORD(X(state, j));
1055                 y0 = COORD(Y(state, j));
1056
1057                 dx = (x1 - x0);
1058                 if (dx != 0 &&
1059                     dx != TILE_SIZE * sense) {
1060                     dx = (dx < 0 ? dx + TILE_SIZE * state->w :
1061                           dx - TILE_SIZE * state->w);
1062                     assert(abs(dx) == TILE_SIZE);
1063                 }
1064                 dy = (y1 - y0);
1065                 if (dy != 0 &&
1066                     dy != TILE_SIZE * sense) {
1067                     dy = (dy < 0 ? dy + TILE_SIZE * state->h :
1068                           dy - TILE_SIZE * state->h);
1069                     assert(abs(dy) == TILE_SIZE);
1070                 }
1071
1072                 c = (animtime / ANIM_TIME);
1073                 if (c < 0.0F) c = 0.0F;
1074                 if (c > 1.0F) c = 1.0F;
1075
1076                 x = x0 + (int)(c * dx);
1077                 y = y0 + (int)(c * dy);
1078                 x2 = x1 - dx + (int)(c * dx);
1079                 y2 = y1 - dy + (int)(c * dy);
1080             } else {
1081                 x = COORD(X(state, i));
1082                 y = COORD(Y(state, i));
1083                 x2 = y2 = -1;
1084             }
1085
1086             draw_tile(dr, ds, state, x, y, t,
1087                       (x2 == -1 && TILE_CURSOR(i, state, cur_x, cur_y)) ?
1088                       COL_LOWLIGHT : bgcolour);
1089
1090             if (x2 != -1 || y2 != -1)
1091                 draw_tile(dr, ds, state, x2, y2, t, bgcolour);
1092         }
1093         ds->tiles[i] = t0;
1094     }
1095
1096     ds->cur_x = cur_x;
1097     ds->cur_y = cur_y;
1098
1099     unclip(dr);
1100
1101     ds->bgcolour = bgcolour;
1102
1103     /*
1104      * Update the status bar.
1105      */
1106     {
1107         char statusbuf[256];
1108
1109         /*
1110          * Don't show the new status until we're also showing the
1111          * new _state_ - after the game animation is complete.
1112          */
1113         if (oldstate)
1114             state = oldstate;
1115
1116         if (state->used_solve)
1117             sprintf(statusbuf, "Moves since auto-solve: %d",
1118                     state->movecount - state->completed);
1119         else {
1120             sprintf(statusbuf, "%sMoves: %d",
1121                     (state->completed ? "COMPLETED! " : ""),
1122                     (state->completed ? state->completed : state->movecount));
1123             if (state->movetarget)
1124                 sprintf(statusbuf+strlen(statusbuf), " (target %d)",
1125                         state->movetarget);
1126         }
1127
1128         status_bar(dr, statusbuf);
1129     }
1130 }
1131
1132 static float game_anim_length(const game_state *oldstate,
1133                               const game_state *newstate, int dir, game_ui *ui)
1134 {
1135     return ANIM_TIME;
1136 }
1137
1138 static float game_flash_length(const game_state *oldstate,
1139                                const game_state *newstate, int dir, game_ui *ui)
1140 {
1141     if (!oldstate->completed && newstate->completed &&
1142         !oldstate->used_solve && !newstate->used_solve)
1143         return 2 * FLASH_FRAME;
1144     else
1145         return 0.0F;
1146 }
1147
1148 static int game_status(const game_state *state)
1149 {
1150     return state->completed ? +1 : 0;
1151 }
1152
1153 static int game_timing_state(const game_state *state, game_ui *ui)
1154 {
1155     return TRUE;
1156 }
1157
1158 static void game_print_size(const game_params *params, float *x, float *y)
1159 {
1160 }
1161
1162 static void game_print(drawing *dr, const game_state *state, int tilesize)
1163 {
1164 }
1165
1166 #ifdef COMBINED
1167 #define thegame sixteen
1168 #endif
1169
1170 const struct game thegame = {
1171     "Sixteen", "games.sixteen", "sixteen",
1172     default_params,
1173     game_fetch_preset, NULL,
1174     decode_params,
1175     encode_params,
1176     free_params,
1177     dup_params,
1178     TRUE, game_configure, custom_params,
1179     validate_params,
1180     new_game_desc,
1181     validate_desc,
1182     new_game,
1183     dup_game,
1184     free_game,
1185     TRUE, solve_game,
1186     TRUE, game_can_format_as_text_now, game_text_format,
1187     new_ui,
1188     free_ui,
1189     encode_ui,
1190     decode_ui,
1191     game_changed_state,
1192     interpret_move,
1193     execute_move,
1194     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1195     game_colours,
1196     game_new_drawstate,
1197     game_free_drawstate,
1198     game_redraw,
1199     game_anim_length,
1200     game_flash_length,
1201     game_status,
1202     FALSE, FALSE, game_print_size, game_print,
1203     TRUE,                              /* wants_statusbar */
1204     FALSE, game_timing_state,
1205     0,                                 /* flags */
1206 };
1207
1208 /* vim: set shiftwidth=4 tabstop=8: */