chiark / gitweb /
Return error messages as 'const char *', not 'char *'.
[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;
402     char *err;
403     int i, area;
404     int *used;
405
406     area = params->w * params->h;
407     p = desc;
408     err = NULL;
409
410     used = snewn(area, int);
411     for (i = 0; i < area; i++)
412         used[i] = FALSE;
413
414     for (i = 0; i < area; i++) {
415         const char *q = p;
416         int n;
417
418         if (*p < '0' || *p > '9') {
419             err = "Not enough numbers in string";
420             goto leave;
421         }
422         while (*p >= '0' && *p <= '9')
423             p++;
424         if (i < area-1 && *p != ',') {
425             err = "Expected comma after number";
426             goto leave;
427         }
428         else if (i == area-1 && *p) {
429             err = "Excess junk at end of string";
430             goto leave;
431         }
432         n = atoi(q);
433         if (n < 1 || n > area) {
434             err = "Number out of range";
435             goto leave;
436         }
437         if (used[n-1]) {
438             err = "Number used twice";
439             goto leave;
440         }
441         used[n-1] = TRUE;
442
443         if (*p) p++;                   /* eat comma */
444     }
445
446     leave:
447     sfree(used);
448     return err;
449 }
450
451 static game_state *new_game(midend *me, const game_params *params,
452                             const char *desc)
453 {
454     game_state *state = snew(game_state);
455     int i;
456     const char *p;
457
458     state->w = params->w;
459     state->h = params->h;
460     state->n = params->w * params->h;
461     state->tiles = snewn(state->n, int);
462
463     p = desc;
464     i = 0;
465     for (i = 0; i < state->n; i++) {
466         assert(*p);
467         state->tiles[i] = atoi(p);
468         while (*p && *p != ',')
469             p++;
470         if (*p) p++;                   /* eat comma */
471     }
472     assert(!*p);
473
474     state->completed = state->movecount = 0;
475     state->movetarget = params->movetarget;
476     state->used_solve = FALSE;
477     state->last_movement_sense = 0;
478
479     return state;
480 }
481
482 static game_state *dup_game(const game_state *state)
483 {
484     game_state *ret = snew(game_state);
485
486     ret->w = state->w;
487     ret->h = state->h;
488     ret->n = state->n;
489     ret->tiles = snewn(state->w * state->h, int);
490     memcpy(ret->tiles, state->tiles, state->w * state->h * sizeof(int));
491     ret->completed = state->completed;
492     ret->movecount = state->movecount;
493     ret->movetarget = state->movetarget;
494     ret->used_solve = state->used_solve;
495     ret->last_movement_sense = state->last_movement_sense;
496
497     return ret;
498 }
499
500 static void free_game(game_state *state)
501 {
502     sfree(state->tiles);
503     sfree(state);
504 }
505
506 static char *solve_game(const game_state *state, const game_state *currstate,
507                         const char *aux, const char **error)
508 {
509     return dupstr("S");
510 }
511
512 static int game_can_format_as_text_now(const game_params *params)
513 {
514     return TRUE;
515 }
516
517 static char *game_text_format(const game_state *state)
518 {
519     char *ret, *p, buf[80];
520     int x, y, col, maxlen;
521
522     /*
523      * First work out how many characters we need to display each
524      * number.
525      */
526     col = sprintf(buf, "%d", state->n);
527
528     /*
529      * Now we know the exact total size of the grid we're going to
530      * produce: it's got h rows, each containing w lots of col, w-1
531      * spaces and a trailing newline.
532      */
533     maxlen = state->h * state->w * (col+1);
534
535     ret = snewn(maxlen+1, char);
536     p = ret;
537
538     for (y = 0; y < state->h; y++) {
539         for (x = 0; x < state->w; x++) {
540             int v = state->tiles[state->w*y+x];
541             sprintf(buf, "%*d", col, v);
542             memcpy(p, buf, col);
543             p += col;
544             if (x+1 == state->w)
545                 *p++ = '\n';
546             else
547                 *p++ = ' ';
548         }
549     }
550
551     assert(p - ret == maxlen);
552     *p = '\0';
553     return ret;
554 }
555
556 enum cursor_mode { unlocked, lock_tile, lock_position };
557
558 struct game_ui {
559     int cur_x, cur_y;
560     int cur_visible;
561     enum cursor_mode cur_mode;
562 };
563
564 static game_ui *new_ui(const game_state *state)
565 {
566     game_ui *ui = snew(game_ui);
567     ui->cur_x = 0;
568     ui->cur_y = 0;
569     ui->cur_visible = FALSE;
570     ui->cur_mode = unlocked;
571
572     return ui;
573 }
574
575 static void free_ui(game_ui *ui)
576 {
577     sfree(ui);
578 }
579
580 static char *encode_ui(const game_ui *ui)
581 {
582     return NULL;
583 }
584
585 static void decode_ui(game_ui *ui, const char *encoding)
586 {
587 }
588
589 static void game_changed_state(game_ui *ui, const game_state *oldstate,
590                                const game_state *newstate)
591 {
592 }
593
594 struct game_drawstate {
595     int started;
596     int w, h, bgcolour;
597     int *tiles;
598     int tilesize;
599     int cur_x, cur_y;
600 };
601
602 static char *interpret_move(const game_state *state, game_ui *ui,
603                             const game_drawstate *ds,
604                             int x, int y, int button)
605 {
606     int cx = -1, cy = -1, dx, dy;
607     char buf[80];
608     int shift = button & MOD_SHFT, control = button & MOD_CTRL,
609         pad = button & MOD_NUM_KEYPAD;
610
611     button &= ~MOD_MASK;
612
613     if (IS_CURSOR_MOVE(button) || pad) {
614         if (!ui->cur_visible) {
615             ui->cur_visible = 1;
616             return UI_UPDATE;
617         }
618
619         if (control || shift || ui->cur_mode) {
620             int x = ui->cur_x, y = ui->cur_y, xwrap = x, ywrap = y;
621             if (x < 0 || x >= state->w || y < 0 || y >= state->h)
622                 return NULL;
623             move_cursor(button | pad, &x, &y,
624                         state->w, state->h, FALSE);
625             move_cursor(button | pad, &xwrap, &ywrap,
626                         state->w, state->h, TRUE);
627
628             if (x != xwrap) {
629                 sprintf(buf, "R%d,%c1", y, x ? '+' : '-');
630             } else if (y != ywrap) {
631                 sprintf(buf, "C%d,%c1", x, y ? '+' : '-');
632             } else if (x == ui->cur_x)
633                 sprintf(buf, "C%d,%d", x, y - ui->cur_y);
634             else
635                 sprintf(buf, "R%d,%d", y, x - ui->cur_x);
636
637             if (control || (!shift && ui->cur_mode == lock_tile)) {
638                 ui->cur_x = xwrap;
639                 ui->cur_y = ywrap;
640             }
641
642             return dupstr(buf);
643         } else {
644             int x = ui->cur_x + 1, y = ui->cur_y + 1;
645
646             move_cursor(button | pad, &x, &y,
647                         state->w + 2, state->h + 2, FALSE);
648
649             if (x == 0 && y == 0) {
650                 int t = ui->cur_x;
651                 ui->cur_x = ui->cur_y;
652                 ui->cur_y = t;
653             } else if (x == 0 && y == state->h + 1) {
654                 int t = ui->cur_x;
655                 ui->cur_x = (state->h - 1) - ui->cur_y;
656                 ui->cur_y = (state->h - 1) - t;
657             } else if (x == state->w + 1 && y == 0) {
658                 int t = ui->cur_x;
659                 ui->cur_x = (state->w - 1) - ui->cur_y;
660                 ui->cur_y = (state->w - 1) - t;
661             } else if (x == state->w + 1 && y == state->h + 1) {
662                 int t = ui->cur_x;
663                 ui->cur_x = state->w - state->h + ui->cur_y;
664                 ui->cur_y = state->h - state->w + t;
665             } else {
666                 ui->cur_x = x - 1;
667                 ui->cur_y = y - 1;
668             }
669
670             ui->cur_visible = 1;
671             return UI_UPDATE;
672         }
673     }
674
675     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
676         cx = FROMCOORD(x);
677         cy = FROMCOORD(y);
678         ui->cur_visible = 0;
679     } else if (IS_CURSOR_SELECT(button)) {
680         if (ui->cur_visible) {
681             if (ui->cur_x == -1 || ui->cur_x == state->w ||
682                 ui->cur_y == -1 || ui->cur_y == state->h) {
683                 cx = ui->cur_x;
684                 cy = ui->cur_y;
685             } else {
686                 const enum cursor_mode m = (button == CURSOR_SELECT2 ?
687                                             lock_position : lock_tile);
688                 ui->cur_mode = (ui->cur_mode == m ? unlocked : m);
689                 return UI_UPDATE;
690             }
691         } else {
692             ui->cur_visible = 1;
693             return UI_UPDATE;
694         }
695     } else {
696         return NULL;
697     }
698
699     if (cx == -1 && cy >= 0 && cy < state->h)
700         dx = -1, dy = 0;
701     else if (cx == state->w && cy >= 0 && cy < state->h)
702         dx = +1, dy = 0;
703     else if (cy == -1 && cx >= 0 && cx < state->w)
704         dy = -1, dx = 0;
705     else if (cy == state->h && cx >= 0 && cx < state->w)
706         dy = +1, dx = 0;
707     else
708         return UI_UPDATE;            /* invalid click location */
709
710     /* reverse direction if right hand button is pressed */
711     if (button == RIGHT_BUTTON || button == CURSOR_SELECT2) {
712         dx = -dx;
713         dy = -dy;
714     }
715
716     if (dx)
717         sprintf(buf, "R%d,%d", cy, dx);
718     else
719         sprintf(buf, "C%d,%d", cx, dy);
720     return dupstr(buf);
721 }
722
723 static game_state *execute_move(const game_state *from, const char *move)
724 {
725     int cx, cy, dx, dy;
726     int tx, ty, n;
727     game_state *ret;
728
729     if (!strcmp(move, "S")) {
730         int i;
731
732         ret = dup_game(from);
733
734         /*
735          * Simply replace the grid with a solved one. For this game,
736          * this isn't a useful operation for actually telling the user
737          * what they should have done, but it is useful for
738          * conveniently being able to get hold of a clean state from
739          * which to practise manoeuvres.
740          */
741         for (i = 0; i < ret->n; i++)
742             ret->tiles[i] = i+1;
743         ret->used_solve = TRUE;
744         ret->completed = ret->movecount = 1;
745
746         return ret;
747     }
748
749     if (move[0] == 'R' && sscanf(move+1, "%d,%d", &cy, &dx) == 2 &&
750         cy >= 0 && cy < from->h) {
751         cx = dy = 0;
752         n = from->w;
753     } else if (move[0] == 'C' && sscanf(move+1, "%d,%d", &cx, &dy) == 2 &&
754                cx >= 0 && cx < from->w) {
755         cy = dx = 0;
756         n = from->h;
757     } else
758         return NULL;
759
760     ret = dup_game(from);
761
762     do {
763         tx = (cx - dx + from->w) % from->w;
764         ty = (cy - dy + from->h) % from->h;
765         ret->tiles[C(ret, cx, cy)] = from->tiles[C(from, tx, ty)];
766         cx = tx;
767         cy = ty;
768     } while (--n > 0);
769
770     ret->movecount++;
771
772     ret->last_movement_sense = dx+dy;
773
774     /*
775      * See if the game has been completed.
776      */
777     if (!ret->completed) {
778         ret->completed = ret->movecount;
779         for (n = 0; n < ret->n; n++)
780             if (ret->tiles[n] != n+1)
781                 ret->completed = FALSE;
782     }
783
784     return ret;
785 }
786
787 /* ----------------------------------------------------------------------
788  * Drawing routines.
789  */
790
791 static void game_compute_size(const game_params *params, int tilesize,
792                               int *x, int *y)
793 {
794     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
795     struct { int tilesize; } ads, *ds = &ads;
796     ads.tilesize = tilesize;
797
798     *x = TILE_SIZE * params->w + 2 * BORDER;
799     *y = TILE_SIZE * params->h + 2 * BORDER;
800 }
801
802 static void game_set_size(drawing *dr, game_drawstate *ds,
803                           const game_params *params, int tilesize)
804 {
805     ds->tilesize = tilesize;
806 }
807
808 static float *game_colours(frontend *fe, int *ncolours)
809 {
810     float *ret = snewn(3 * NCOLOURS, float);
811     int i;
812
813     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
814
815     for (i = 0; i < 3; i++)
816         ret[COL_TEXT * 3 + i] = 0.0;
817
818     *ncolours = NCOLOURS;
819     return ret;
820 }
821
822 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
823 {
824     struct game_drawstate *ds = snew(struct game_drawstate);
825     int i;
826
827     ds->started = FALSE;
828     ds->w = state->w;
829     ds->h = state->h;
830     ds->bgcolour = COL_BACKGROUND;
831     ds->tiles = snewn(ds->w*ds->h, int);
832     ds->tilesize = 0;                  /* haven't decided yet */
833     for (i = 0; i < ds->w*ds->h; i++)
834         ds->tiles[i] = -1;
835     ds->cur_x = ds->cur_y = -1;
836
837     return ds;
838 }
839
840 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
841 {
842     sfree(ds->tiles);
843     sfree(ds);
844 }
845
846 static void draw_tile(drawing *dr, game_drawstate *ds,
847                       const game_state *state, int x, int y,
848                       int tile, int flash_colour)
849 {
850     if (tile == 0) {
851         draw_rect(dr, x, y, TILE_SIZE, TILE_SIZE,
852                   flash_colour);
853     } else {
854         int coords[6];
855         char str[40];
856
857         coords[0] = x + TILE_SIZE - 1;
858         coords[1] = y + TILE_SIZE - 1;
859         coords[2] = x + TILE_SIZE - 1;
860         coords[3] = y;
861         coords[4] = x;
862         coords[5] = y + TILE_SIZE - 1;
863         draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
864
865         coords[0] = x;
866         coords[1] = y;
867         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
868
869         draw_rect(dr, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
870                   TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
871                   flash_colour);
872
873         sprintf(str, "%d", tile);
874         draw_text(dr, x + TILE_SIZE/2, y + TILE_SIZE/2,
875                   FONT_VARIABLE, TILE_SIZE/3, ALIGN_VCENTRE | ALIGN_HCENTRE,
876                   COL_TEXT, str);
877     }
878     draw_update(dr, x, y, TILE_SIZE, TILE_SIZE);
879 }
880
881 static void draw_arrow(drawing *dr, game_drawstate *ds,
882                        int x, int y, int xdx, int xdy, int cur)
883 {
884     int coords[14];
885     int ydy = -xdx, ydx = xdy;
886
887 #define POINT(n, xx, yy) ( \
888     coords[2*(n)+0] = x + (xx)*xdx + (yy)*ydx, \
889     coords[2*(n)+1] = y + (xx)*xdy + (yy)*ydy)
890
891     POINT(0, TILE_SIZE / 2, 3 * TILE_SIZE / 4);   /* top of arrow */
892     POINT(1, 3 * TILE_SIZE / 4, TILE_SIZE / 2);   /* right corner */
893     POINT(2, 5 * TILE_SIZE / 8, TILE_SIZE / 2);   /* right concave */
894     POINT(3, 5 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom right */
895     POINT(4, 3 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom left */
896     POINT(5, 3 * TILE_SIZE / 8, TILE_SIZE / 2);   /* left concave */
897     POINT(6,     TILE_SIZE / 4, TILE_SIZE / 2);   /* left corner */
898
899     draw_polygon(dr, coords, 7, cur ? COL_HIGHLIGHT : COL_LOWLIGHT, COL_TEXT);
900 }
901
902 static void draw_arrow_for_cursor(drawing *dr, game_drawstate *ds,
903                                   int cur_x, int cur_y, int cur)
904 {
905     if (cur_x == -1 && cur_y == -1)
906         return; /* 'no cursur here */
907     else if (cur_x == -1) /* LH column. */
908         draw_arrow(dr, ds, COORD(0), COORD(cur_y+1), 0, -1, cur);
909     else if (cur_x == ds->w) /* RH column */
910         draw_arrow(dr, ds, COORD(ds->w), COORD(cur_y), 0, +1, cur);
911     else if (cur_y == -1) /* Top row */
912         draw_arrow(dr, ds, COORD(cur_x), COORD(0), +1, 0, cur);
913     else if (cur_y == ds->h) /* Bottom row */
914         draw_arrow(dr, ds, COORD(cur_x+1), COORD(ds->h), -1, 0, cur);
915     else
916         return;
917
918     draw_update(dr, COORD(cur_x), COORD(cur_y),
919                 TILE_SIZE, TILE_SIZE);
920 }
921
922 static void game_redraw(drawing *dr, game_drawstate *ds,
923                         const game_state *oldstate, const game_state *state,
924                         int dir, const game_ui *ui,
925                         float animtime, float flashtime)
926 {
927     int i, bgcolour;
928     int cur_x = -1, cur_y = -1;
929
930     if (flashtime > 0) {
931         int frame = (int)(flashtime / FLASH_FRAME);
932         bgcolour = (frame % 2 ? COL_LOWLIGHT : COL_HIGHLIGHT);
933     } else
934         bgcolour = COL_BACKGROUND;
935
936     if (!ds->started) {
937         int coords[10];
938
939         draw_rect(dr, 0, 0,
940                   TILE_SIZE * state->w + 2 * BORDER,
941                   TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
942         draw_update(dr, 0, 0,
943                     TILE_SIZE * state->w + 2 * BORDER,
944                     TILE_SIZE * state->h + 2 * BORDER);
945
946         /*
947          * Recessed area containing the whole puzzle.
948          */
949         coords[0] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
950         coords[1] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
951         coords[2] = COORD(state->w) + HIGHLIGHT_WIDTH - 1;
952         coords[3] = COORD(0) - HIGHLIGHT_WIDTH;
953         coords[4] = coords[2] - TILE_SIZE;
954         coords[5] = coords[3] + TILE_SIZE;
955         coords[8] = COORD(0) - HIGHLIGHT_WIDTH;
956         coords[9] = COORD(state->h) + HIGHLIGHT_WIDTH - 1;
957         coords[6] = coords[8] + TILE_SIZE;
958         coords[7] = coords[9] - TILE_SIZE;
959         draw_polygon(dr, coords, 5, COL_HIGHLIGHT, COL_HIGHLIGHT);
960
961         coords[1] = COORD(0) - HIGHLIGHT_WIDTH;
962         coords[0] = COORD(0) - HIGHLIGHT_WIDTH;
963         draw_polygon(dr, coords, 5, COL_LOWLIGHT, COL_LOWLIGHT);
964
965         /*
966          * Arrows for making moves.
967          */
968         for (i = 0; i < state->w; i++) {
969             draw_arrow(dr, ds, COORD(i), COORD(0), +1, 0, 0);
970             draw_arrow(dr, ds, COORD(i+1), COORD(state->h), -1, 0, 0);
971         }
972         for (i = 0; i < state->h; i++) {
973             draw_arrow(dr, ds, COORD(state->w), COORD(i), 0, +1, 0);
974             draw_arrow(dr, ds, COORD(0), COORD(i+1), 0, -1, 0);
975         }
976
977         ds->started = TRUE;
978     }
979     /*
980      * Cursor (highlighted arrow around edge)
981      */
982     if (ui->cur_visible) {
983         cur_x = ui->cur_x; cur_y = ui->cur_y;
984     }
985
986     if (cur_x != ds->cur_x || cur_y != ds->cur_y) {
987         /* Cursor has changed; redraw two (prev and curr) arrows. */
988         draw_arrow_for_cursor(dr, ds, cur_x, cur_y, 1);
989         draw_arrow_for_cursor(dr, ds, ds->cur_x, ds->cur_y, 0);
990     }
991
992     /*
993      * Now draw each tile.
994      */
995
996     clip(dr, COORD(0), COORD(0), TILE_SIZE*state->w, TILE_SIZE*state->h);
997
998     for (i = 0; i < state->n; i++) {
999         int t, t0;
1000         /*
1001          * Figure out what should be displayed at this
1002          * location. It's either a simple tile, or it's a
1003          * transition between two tiles (in which case we say
1004          * -1 because it must always be drawn).
1005          */
1006
1007         if (oldstate && oldstate->tiles[i] != state->tiles[i])
1008             t = -1;
1009         else
1010             t = state->tiles[i];
1011
1012         t0 = t;
1013
1014         if (ds->bgcolour != bgcolour ||   /* always redraw when flashing */
1015             ds->tiles[i] != t || ds->tiles[i] == -1 || t == -1 ||
1016             ((ds->cur_x != cur_x || ds->cur_y != cur_y) && /* cursor moved */
1017              (TILE_CURSOR(i, state, ds->cur_x, ds->cur_y) ||
1018               TILE_CURSOR(i, state, cur_x, cur_y)))) {
1019             int x, y, x2, y2;
1020
1021             /*
1022              * Figure out what to _actually_ draw, and where to
1023              * draw it.
1024              */
1025             if (t == -1) {
1026                 int x0, y0, x1, y1, dx, dy;
1027                 int j;
1028                 float c;
1029                 int sense;
1030
1031                 if (dir < 0) {
1032                     assert(oldstate);
1033                     sense = -oldstate->last_movement_sense;
1034                 } else {
1035                     sense = state->last_movement_sense;
1036                 }
1037
1038                 t = state->tiles[i];
1039
1040                 /*
1041                  * FIXME: must be prepared to draw a double
1042                  * tile in some situations.
1043                  */
1044
1045                 /*
1046                  * Find the coordinates of this tile in the old and
1047                  * new states.
1048                  */
1049                 x1 = COORD(X(state, i));
1050                 y1 = COORD(Y(state, i));
1051                 for (j = 0; j < oldstate->n; j++)
1052                     if (oldstate->tiles[j] == state->tiles[i])
1053                         break;
1054                 assert(j < oldstate->n);
1055                 x0 = COORD(X(state, j));
1056                 y0 = COORD(Y(state, j));
1057
1058                 dx = (x1 - x0);
1059                 if (dx != 0 &&
1060                     dx != TILE_SIZE * sense) {
1061                     dx = (dx < 0 ? dx + TILE_SIZE * state->w :
1062                           dx - TILE_SIZE * state->w);
1063                     assert(abs(dx) == TILE_SIZE);
1064                 }
1065                 dy = (y1 - y0);
1066                 if (dy != 0 &&
1067                     dy != TILE_SIZE * sense) {
1068                     dy = (dy < 0 ? dy + TILE_SIZE * state->h :
1069                           dy - TILE_SIZE * state->h);
1070                     assert(abs(dy) == TILE_SIZE);
1071                 }
1072
1073                 c = (animtime / ANIM_TIME);
1074                 if (c < 0.0F) c = 0.0F;
1075                 if (c > 1.0F) c = 1.0F;
1076
1077                 x = x0 + (int)(c * dx);
1078                 y = y0 + (int)(c * dy);
1079                 x2 = x1 - dx + (int)(c * dx);
1080                 y2 = y1 - dy + (int)(c * dy);
1081             } else {
1082                 x = COORD(X(state, i));
1083                 y = COORD(Y(state, i));
1084                 x2 = y2 = -1;
1085             }
1086
1087             draw_tile(dr, ds, state, x, y, t,
1088                       (x2 == -1 && TILE_CURSOR(i, state, cur_x, cur_y)) ?
1089                       COL_LOWLIGHT : bgcolour);
1090
1091             if (x2 != -1 || y2 != -1)
1092                 draw_tile(dr, ds, state, x2, y2, t, bgcolour);
1093         }
1094         ds->tiles[i] = t0;
1095     }
1096
1097     ds->cur_x = cur_x;
1098     ds->cur_y = cur_y;
1099
1100     unclip(dr);
1101
1102     ds->bgcolour = bgcolour;
1103
1104     /*
1105      * Update the status bar.
1106      */
1107     {
1108         char statusbuf[256];
1109
1110         /*
1111          * Don't show the new status until we're also showing the
1112          * new _state_ - after the game animation is complete.
1113          */
1114         if (oldstate)
1115             state = oldstate;
1116
1117         if (state->used_solve)
1118             sprintf(statusbuf, "Moves since auto-solve: %d",
1119                     state->movecount - state->completed);
1120         else {
1121             sprintf(statusbuf, "%sMoves: %d",
1122                     (state->completed ? "COMPLETED! " : ""),
1123                     (state->completed ? state->completed : state->movecount));
1124             if (state->movetarget)
1125                 sprintf(statusbuf+strlen(statusbuf), " (target %d)",
1126                         state->movetarget);
1127         }
1128
1129         status_bar(dr, statusbuf);
1130     }
1131 }
1132
1133 static float game_anim_length(const game_state *oldstate,
1134                               const game_state *newstate, int dir, game_ui *ui)
1135 {
1136     return ANIM_TIME;
1137 }
1138
1139 static float game_flash_length(const game_state *oldstate,
1140                                const game_state *newstate, int dir, game_ui *ui)
1141 {
1142     if (!oldstate->completed && newstate->completed &&
1143         !oldstate->used_solve && !newstate->used_solve)
1144         return 2 * FLASH_FRAME;
1145     else
1146         return 0.0F;
1147 }
1148
1149 static int game_status(const game_state *state)
1150 {
1151     return state->completed ? +1 : 0;
1152 }
1153
1154 static int game_timing_state(const game_state *state, game_ui *ui)
1155 {
1156     return TRUE;
1157 }
1158
1159 static void game_print_size(const game_params *params, float *x, float *y)
1160 {
1161 }
1162
1163 static void game_print(drawing *dr, const game_state *state, int tilesize)
1164 {
1165 }
1166
1167 #ifdef COMBINED
1168 #define thegame sixteen
1169 #endif
1170
1171 const struct game thegame = {
1172     "Sixteen", "games.sixteen", "sixteen",
1173     default_params,
1174     game_fetch_preset, NULL,
1175     decode_params,
1176     encode_params,
1177     free_params,
1178     dup_params,
1179     TRUE, game_configure, custom_params,
1180     validate_params,
1181     new_game_desc,
1182     validate_desc,
1183     new_game,
1184     dup_game,
1185     free_game,
1186     TRUE, solve_game,
1187     TRUE, game_can_format_as_text_now, game_text_format,
1188     new_ui,
1189     free_ui,
1190     encode_ui,
1191     decode_ui,
1192     game_changed_state,
1193     interpret_move,
1194     execute_move,
1195     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1196     game_colours,
1197     game_new_drawstate,
1198     game_free_drawstate,
1199     game_redraw,
1200     game_anim_length,
1201     game_flash_length,
1202     game_status,
1203     FALSE, FALSE, game_print_size, game_print,
1204     TRUE,                              /* wants_statusbar */
1205     FALSE, game_timing_state,
1206     0,                                 /* flags */
1207 };
1208
1209 /* vim: set shiftwidth=4 tabstop=8: */