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