chiark / gitweb /
Introduce routines in each game module to encode a set of game
[sgt-puzzles.git] / net.c
1 /*
2  * net.c: Net game.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13 #include "tree234.h"
14
15 const char *const game_name = "Net";
16 const int game_can_configure = TRUE;
17
18 #define PI 3.141592653589793238462643383279502884197169399
19
20 #define MATMUL(xr,yr,m,x,y) do { \
21     float rx, ry, xx = (x), yy = (y), *mat = (m); \
22     rx = mat[0] * xx + mat[2] * yy; \
23     ry = mat[1] * xx + mat[3] * yy; \
24     (xr) = rx; (yr) = ry; \
25 } while (0)
26
27 /* Direction and other bitfields */
28 #define R 0x01
29 #define U 0x02
30 #define L 0x04
31 #define D 0x08
32 #define LOCKED 0x10
33 #define ACTIVE 0x20
34 /* Corner flags go in the barriers array */
35 #define RU 0x10
36 #define UL 0x20
37 #define LD 0x40
38 #define DR 0x80
39
40 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
41 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
42 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
43 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
44 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
45                     ((n)&3) == 1 ? A(x) : \
46                     ((n)&3) == 2 ? F(x) : C(x) )
47
48 /* X and Y displacements */
49 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
50 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
51
52 /* Bit count */
53 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
54                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
55
56 #define TILE_SIZE 32
57 #define TILE_BORDER 1
58 #define WINDOW_OFFSET 16
59
60 #define ROTATE_TIME 0.13F
61 #define FLASH_FRAME 0.07F
62
63 enum {
64     COL_BACKGROUND,
65     COL_LOCKED,
66     COL_BORDER,
67     COL_WIRE,
68     COL_ENDPOINT,
69     COL_POWERED,
70     COL_BARRIER,
71     NCOLOURS
72 };
73
74 struct game_params {
75     int width;
76     int height;
77     int wrapping;
78     float barrier_probability;
79 };
80
81 struct game_state {
82     int width, height, cx, cy, wrapping, completed, last_rotate_dir;
83     unsigned char *tiles;
84     unsigned char *barriers;
85 };
86
87 #define OFFSET(x2,y2,x1,y1,dir,state) \
88     ( (x2) = ((x1) + (state)->width + X((dir))) % (state)->width, \
89       (y2) = ((y1) + (state)->height + Y((dir))) % (state)->height)
90
91 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
92 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
93 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
94
95 struct xyd {
96     int x, y, direction;
97 };
98
99 static int xyd_cmp(void *av, void *bv) {
100     struct xyd *a = (struct xyd *)av;
101     struct xyd *b = (struct xyd *)bv;
102     if (a->x < b->x)
103         return -1;
104     if (a->x > b->x)
105         return +1;
106     if (a->y < b->y)
107         return -1;
108     if (a->y > b->y)
109         return +1;
110     if (a->direction < b->direction)
111         return -1;
112     if (a->direction > b->direction)
113         return +1;
114     return 0;
115 };
116
117 static struct xyd *new_xyd(int x, int y, int direction)
118 {
119     struct xyd *xyd = snew(struct xyd);
120     xyd->x = x;
121     xyd->y = y;
122     xyd->direction = direction;
123     return xyd;
124 }
125
126 /* ----------------------------------------------------------------------
127  * Manage game parameters.
128  */
129 game_params *default_params(void)
130 {
131     game_params *ret = snew(game_params);
132
133     ret->width = 5;
134     ret->height = 5;
135     ret->wrapping = FALSE;
136     ret->barrier_probability = 0.0;
137
138     return ret;
139 }
140
141 int game_fetch_preset(int i, char **name, game_params **params)
142 {
143     game_params *ret;
144     char str[80];
145     static const struct { int x, y, wrap; } values[] = {
146         {5, 5, FALSE},
147         {7, 7, FALSE},
148         {9, 9, FALSE},
149         {11, 11, FALSE},
150         {13, 11, FALSE},
151         {5, 5, TRUE},
152         {7, 7, TRUE},
153         {9, 9, TRUE},
154         {11, 11, TRUE},
155         {13, 11, TRUE},
156     };
157
158     if (i < 0 || i >= lenof(values))
159         return FALSE;
160
161     ret = snew(game_params);
162     ret->width = values[i].x;
163     ret->height = values[i].y;
164     ret->wrapping = values[i].wrap;
165     ret->barrier_probability = 0.0;
166
167     sprintf(str, "%dx%d%s", ret->width, ret->height,
168             ret->wrapping ? " wrapping" : "");
169
170     *name = dupstr(str);
171     *params = ret;
172     return TRUE;
173 }
174
175 void free_params(game_params *params)
176 {
177     sfree(params);
178 }
179
180 game_params *dup_params(game_params *params)
181 {
182     game_params *ret = snew(game_params);
183     *ret = *params;                    /* structure copy */
184     return ret;
185 }
186
187 game_params *decode_params(char const *string)
188 {
189     game_params *ret = default_params();
190     char const *p = string;
191
192     ret->width = atoi(p);
193     while (*p && isdigit(*p)) p++;
194     if (*p == 'x') {
195         p++;
196         ret->height = atoi(p);
197         while (*p && isdigit(*p)) p++;
198         if ( (ret->wrapping = (*p == 'w')) != 0 )
199             p++;
200         if (*p == 'b')
201             ret->barrier_probability = atof(p+1);
202     } else {
203         ret->height = ret->width;
204     }
205
206     return ret;
207 }
208
209 char *encode_params(game_params *params)
210 {
211     char ret[400];
212     int len;
213
214     len = sprintf(ret, "%dx%d", params->width, params->height);
215     if (params->wrapping)
216         ret[len++] = 'w';
217     if (params->barrier_probability)
218         len += sprintf(ret+len, "b%g", params->barrier_probability);
219     assert(len < lenof(ret));
220     ret[len] = '\0';
221
222     return dupstr(ret);
223 }
224
225 config_item *game_configure(game_params *params)
226 {
227     config_item *ret;
228     char buf[80];
229
230     ret = snewn(5, config_item);
231
232     ret[0].name = "Width";
233     ret[0].type = C_STRING;
234     sprintf(buf, "%d", params->width);
235     ret[0].sval = dupstr(buf);
236     ret[0].ival = 0;
237
238     ret[1].name = "Height";
239     ret[1].type = C_STRING;
240     sprintf(buf, "%d", params->height);
241     ret[1].sval = dupstr(buf);
242     ret[1].ival = 0;
243
244     ret[2].name = "Walls wrap around";
245     ret[2].type = C_BOOLEAN;
246     ret[2].sval = NULL;
247     ret[2].ival = params->wrapping;
248
249     ret[3].name = "Barrier probability";
250     ret[3].type = C_STRING;
251     sprintf(buf, "%g", params->barrier_probability);
252     ret[3].sval = dupstr(buf);
253     ret[3].ival = 0;
254
255     ret[4].name = NULL;
256     ret[4].type = C_END;
257     ret[4].sval = NULL;
258     ret[4].ival = 0;
259
260     return ret;
261 }
262
263 game_params *custom_params(config_item *cfg)
264 {
265     game_params *ret = snew(game_params);
266
267     ret->width = atoi(cfg[0].sval);
268     ret->height = atoi(cfg[1].sval);
269     ret->wrapping = cfg[2].ival;
270     ret->barrier_probability = (float)atof(cfg[3].sval);
271
272     return ret;
273 }
274
275 char *validate_params(game_params *params)
276 {
277     if (params->width <= 0 && params->height <= 0)
278         return "Width and height must both be greater than zero";
279     if (params->width <= 0)
280         return "Width must be greater than zero";
281     if (params->height <= 0)
282         return "Height must be greater than zero";
283     if (params->width <= 1 && params->height <= 1)
284         return "At least one of width and height must be greater than one";
285     if (params->barrier_probability < 0)
286         return "Barrier probability may not be negative";
287     if (params->barrier_probability > 1)
288         return "Barrier probability may not be greater than 1";
289     return NULL;
290 }
291
292 /* ----------------------------------------------------------------------
293  * Randomly select a new game seed.
294  */
295
296 char *new_game_seed(game_params *params, random_state *rs)
297 {
298     /*
299      * The full description of a Net game is far too large to
300      * encode directly in the seed, so by default we'll have to go
301      * for the simple approach of providing a random-number seed.
302      * 
303      * (This does not restrict me from _later on_ inventing a seed
304      * string syntax which can never be generated by this code -
305      * for example, strings beginning with a letter - allowing me
306      * to type in a precise game, and have new_game detect it and
307      * understand it and do something completely different.)
308      */
309     char buf[40];
310     sprintf(buf, "%lu", random_bits(rs, 32));
311     return dupstr(buf);
312 }
313
314 char *validate_seed(game_params *params, char *seed)
315 {
316     /*
317      * Since any string at all will suffice to seed the RNG, there
318      * is no validation required.
319      */
320     return NULL;
321 }
322
323 /* ----------------------------------------------------------------------
324  * Construct an initial game state, given a seed and parameters.
325  */
326
327 game_state *new_game(game_params *params, char *seed)
328 {
329     random_state *rs;
330     game_state *state;
331     tree234 *possibilities, *barriers;
332     int w, h, x, y, nbarriers;
333
334     assert(params->width > 0 && params->height > 0);
335     assert(params->width > 1 || params->height > 1);
336
337     /*
338      * Create a blank game state.
339      */
340     state = snew(game_state);
341     w = state->width = params->width;
342     h = state->height = params->height;
343     state->cx = state->width / 2;
344     state->cy = state->height / 2;
345     state->wrapping = params->wrapping;
346     state->last_rotate_dir = +1;       /* *shrug* */
347     state->completed = FALSE;
348     state->tiles = snewn(state->width * state->height, unsigned char);
349     memset(state->tiles, 0, state->width * state->height);
350     state->barriers = snewn(state->width * state->height, unsigned char);
351     memset(state->barriers, 0, state->width * state->height);
352
353     /*
354      * Set up border barriers if this is a non-wrapping game.
355      */
356     if (!state->wrapping) {
357         for (x = 0; x < state->width; x++) {
358             barrier(state, x, 0) |= U;
359             barrier(state, x, state->height-1) |= D;
360         }
361         for (y = 0; y < state->height; y++) {
362             barrier(state, 0, y) |= L;
363             barrier(state, state->width-1, y) |= R;
364         }
365     }
366
367     /*
368      * Seed the internal random number generator.
369      */
370     rs = random_init(seed, strlen(seed));
371
372     /*
373      * Construct the unshuffled grid.
374      * 
375      * To do this, we simply start at the centre point, repeatedly
376      * choose a random possibility out of the available ways to
377      * extend a used square into an unused one, and do it. After
378      * extending the third line out of a square, we remove the
379      * fourth from the possibilities list to avoid any full-cross
380      * squares (which would make the game too easy because they
381      * only have one orientation).
382      * 
383      * The slightly worrying thing is the avoidance of full-cross
384      * squares. Can this cause our unsophisticated construction
385      * algorithm to paint itself into a corner, by getting into a
386      * situation where there are some unreached squares and the
387      * only way to reach any of them is to extend a T-piece into a
388      * full cross?
389      * 
390      * Answer: no it can't, and here's a proof.
391      * 
392      * Any contiguous group of such unreachable squares must be
393      * surrounded on _all_ sides by T-pieces pointing away from the
394      * group. (If not, then there is a square which can be extended
395      * into one of the `unreachable' ones, and so it wasn't
396      * unreachable after all.) In particular, this implies that
397      * each contiguous group of unreachable squares must be
398      * rectangular in shape (any deviation from that yields a
399      * non-T-piece next to an `unreachable' square).
400      * 
401      * So we have a rectangle of unreachable squares, with T-pieces
402      * forming a solid border around the rectangle. The corners of
403      * that border must be connected (since every tile connects all
404      * the lines arriving in it), and therefore the border must
405      * form a closed loop around the rectangle.
406      * 
407      * But this can't have happened in the first place, since we
408      * _know_ we've avoided creating closed loops! Hence, no such
409      * situation can ever arise, and the naive grid construction
410      * algorithm will guaranteeably result in a complete grid
411      * containing no unreached squares, no full crosses _and_ no
412      * closed loops. []
413      */
414     possibilities = newtree234(xyd_cmp);
415
416     if (state->cx+1 < state->width)
417         add234(possibilities, new_xyd(state->cx, state->cy, R));
418     if (state->cy-1 >= 0)
419         add234(possibilities, new_xyd(state->cx, state->cy, U));
420     if (state->cx-1 >= 0)
421         add234(possibilities, new_xyd(state->cx, state->cy, L));
422     if (state->cy+1 < state->height)
423         add234(possibilities, new_xyd(state->cx, state->cy, D));
424
425     while (count234(possibilities) > 0) {
426         int i;
427         struct xyd *xyd;
428         int x1, y1, d1, x2, y2, d2, d;
429
430         /*
431          * Extract a randomly chosen possibility from the list.
432          */
433         i = random_upto(rs, count234(possibilities));
434         xyd = delpos234(possibilities, i);
435         x1 = xyd->x;
436         y1 = xyd->y;
437         d1 = xyd->direction;
438         sfree(xyd);
439
440         OFFSET(x2, y2, x1, y1, d1, state);
441         d2 = F(d1);
442 #ifdef DEBUG
443         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
444                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
445 #endif
446
447         /*
448          * Make the connection. (We should be moving to an as yet
449          * unused tile.)
450          */
451         tile(state, x1, y1) |= d1;
452         assert(tile(state, x2, y2) == 0);
453         tile(state, x2, y2) |= d2;
454
455         /*
456          * If we have created a T-piece, remove its last
457          * possibility.
458          */
459         if (COUNT(tile(state, x1, y1)) == 3) {
460             struct xyd xyd1, *xydp;
461
462             xyd1.x = x1;
463             xyd1.y = y1;
464             xyd1.direction = 0x0F ^ tile(state, x1, y1);
465
466             xydp = find234(possibilities, &xyd1, NULL);
467
468             if (xydp) {
469 #ifdef DEBUG
470                 printf("T-piece; removing (%d,%d,%c)\n",
471                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
472 #endif
473                 del234(possibilities, xydp);
474                 sfree(xydp);
475             }
476         }
477
478         /*
479          * Remove all other possibilities that were pointing at the
480          * tile we've just moved into.
481          */
482         for (d = 1; d < 0x10; d <<= 1) {
483             int x3, y3, d3;
484             struct xyd xyd1, *xydp;
485
486             OFFSET(x3, y3, x2, y2, d, state);
487             d3 = F(d);
488
489             xyd1.x = x3;
490             xyd1.y = y3;
491             xyd1.direction = d3;
492
493             xydp = find234(possibilities, &xyd1, NULL);
494
495             if (xydp) {
496 #ifdef DEBUG
497                 printf("Loop avoidance; removing (%d,%d,%c)\n",
498                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
499 #endif
500                 del234(possibilities, xydp);
501                 sfree(xydp);
502             }
503         }
504
505         /*
506          * Add new possibilities to the list for moving _out_ of
507          * the tile we have just moved into.
508          */
509         for (d = 1; d < 0x10; d <<= 1) {
510             int x3, y3;
511
512             if (d == d2)
513                 continue;              /* we've got this one already */
514
515             if (!state->wrapping) {
516                 if (d == U && y2 == 0)
517                     continue;
518                 if (d == D && y2 == state->height-1)
519                     continue;
520                 if (d == L && x2 == 0)
521                     continue;
522                 if (d == R && x2 == state->width-1)
523                     continue;
524             }
525
526             OFFSET(x3, y3, x2, y2, d, state);
527
528             if (tile(state, x3, y3))
529                 continue;              /* this would create a loop */
530
531 #ifdef DEBUG
532             printf("New frontier; adding (%d,%d,%c)\n",
533                    x2, y2, "0RU3L567D9abcdef"[d]);
534 #endif
535             add234(possibilities, new_xyd(x2, y2, d));
536         }
537     }
538     /* Having done that, we should have no possibilities remaining. */
539     assert(count234(possibilities) == 0);
540     freetree234(possibilities);
541
542     /*
543      * Now compute a list of the possible barrier locations.
544      */
545     barriers = newtree234(xyd_cmp);
546     for (y = 0; y < state->height; y++) {
547         for (x = 0; x < state->width; x++) {
548
549             if (!(tile(state, x, y) & R) &&
550                 (state->wrapping || x < state->width-1))
551                 add234(barriers, new_xyd(x, y, R));
552             if (!(tile(state, x, y) & D) &&
553                 (state->wrapping || y < state->height-1))
554                 add234(barriers, new_xyd(x, y, D));
555         }
556     }
557
558     /*
559      * Now shuffle the grid.
560      */
561     for (y = 0; y < state->height; y++) {
562         for (x = 0; x < state->width; x++) {
563             int orig = tile(state, x, y);
564             int rot = random_upto(rs, 4);
565             tile(state, x, y) = ROT(orig, rot);
566         }
567     }
568
569     /*
570      * And now choose barrier locations. (We carefully do this
571      * _after_ shuffling, so that changing the barrier rate in the
572      * params while keeping the game seed the same will give the
573      * same shuffled grid and _only_ change the barrier locations.
574      * Also the way we choose barrier locations, by repeatedly
575      * choosing one possibility from the list until we have enough,
576      * is designed to ensure that raising the barrier rate while
577      * keeping the seed the same will provide a superset of the
578      * previous barrier set - i.e. if you ask for 10 barriers, and
579      * then decide that's still too hard and ask for 20, you'll get
580      * the original 10 plus 10 more, rather than getting 20 new
581      * ones and the chance of remembering your first 10.)
582      */
583     nbarriers = (int)(params->barrier_probability * count234(barriers));
584     assert(nbarriers >= 0 && nbarriers <= count234(barriers));
585
586     while (nbarriers > 0) {
587         int i;
588         struct xyd *xyd;
589         int x1, y1, d1, x2, y2, d2;
590
591         /*
592          * Extract a randomly chosen barrier from the list.
593          */
594         i = random_upto(rs, count234(barriers));
595         xyd = delpos234(barriers, i);
596
597         assert(xyd != NULL);
598
599         x1 = xyd->x;
600         y1 = xyd->y;
601         d1 = xyd->direction;
602         sfree(xyd);
603
604         OFFSET(x2, y2, x1, y1, d1, state);
605         d2 = F(d1);
606
607         barrier(state, x1, y1) |= d1;
608         barrier(state, x2, y2) |= d2;
609
610         nbarriers--;
611     }
612
613     /*
614      * Clean up the rest of the barrier list.
615      */
616     {
617         struct xyd *xyd;
618
619         while ( (xyd = delpos234(barriers, 0)) != NULL)
620             sfree(xyd);
621
622         freetree234(barriers);
623     }
624
625     /*
626      * Set up the barrier corner flags, for drawing barriers
627      * prettily when they meet.
628      */
629     for (y = 0; y < state->height; y++) {
630         for (x = 0; x < state->width; x++) {
631             int dir;
632
633             for (dir = 1; dir < 0x10; dir <<= 1) {
634                 int dir2 = A(dir);
635                 int x1, y1, x2, y2, x3, y3;
636                 int corner = FALSE;
637
638                 if (!(barrier(state, x, y) & dir))
639                     continue;
640
641                 if (barrier(state, x, y) & dir2)
642                     corner = TRUE;
643
644                 x1 = x + X(dir), y1 = y + Y(dir);
645                 if (x1 >= 0 && x1 < state->width &&
646                     y1 >= 0 && y1 < state->height &&
647                     (barrier(state, x1, y1) & dir2))
648                     corner = TRUE;
649
650                 x2 = x + X(dir2), y2 = y + Y(dir2);
651                 if (x2 >= 0 && x2 < state->width &&
652                     y2 >= 0 && y2 < state->height &&
653                     (barrier(state, x2, y2) & dir))
654                     corner = TRUE;
655
656                 if (corner) {
657                     barrier(state, x, y) |= (dir << 4);
658                     if (x1 >= 0 && x1 < state->width &&
659                         y1 >= 0 && y1 < state->height)
660                         barrier(state, x1, y1) |= (A(dir) << 4);
661                     if (x2 >= 0 && x2 < state->width &&
662                         y2 >= 0 && y2 < state->height)
663                         barrier(state, x2, y2) |= (C(dir) << 4);
664                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
665                     if (x3 >= 0 && x3 < state->width &&
666                         y3 >= 0 && y3 < state->height)
667                         barrier(state, x3, y3) |= (F(dir) << 4);
668                 }
669             }
670         }
671     }
672
673     random_free(rs);
674
675     return state;
676 }
677
678 game_state *dup_game(game_state *state)
679 {
680     game_state *ret;
681
682     ret = snew(game_state);
683     ret->width = state->width;
684     ret->height = state->height;
685     ret->cx = state->cx;
686     ret->cy = state->cy;
687     ret->wrapping = state->wrapping;
688     ret->completed = state->completed;
689     ret->last_rotate_dir = state->last_rotate_dir;
690     ret->tiles = snewn(state->width * state->height, unsigned char);
691     memcpy(ret->tiles, state->tiles, state->width * state->height);
692     ret->barriers = snewn(state->width * state->height, unsigned char);
693     memcpy(ret->barriers, state->barriers, state->width * state->height);
694
695     return ret;
696 }
697
698 void free_game(game_state *state)
699 {
700     sfree(state->tiles);
701     sfree(state->barriers);
702     sfree(state);
703 }
704
705 /* ----------------------------------------------------------------------
706  * Utility routine.
707  */
708
709 /*
710  * Compute which squares are reachable from the centre square, as a
711  * quick visual aid to determining how close the game is to
712  * completion. This is also a simple way to tell if the game _is_
713  * completed - just call this function and see whether every square
714  * is marked active.
715  */
716 static unsigned char *compute_active(game_state *state)
717 {
718     unsigned char *active;
719     tree234 *todo;
720     struct xyd *xyd;
721
722     active = snewn(state->width * state->height, unsigned char);
723     memset(active, 0, state->width * state->height);
724
725     /*
726      * We only store (x,y) pairs in todo, but it's easier to reuse
727      * xyd_cmp and just store direction 0 every time.
728      */
729     todo = newtree234(xyd_cmp);
730     index(state, active, state->cx, state->cy) = ACTIVE;
731     add234(todo, new_xyd(state->cx, state->cy, 0));
732
733     while ( (xyd = delpos234(todo, 0)) != NULL) {
734         int x1, y1, d1, x2, y2, d2;
735
736         x1 = xyd->x;
737         y1 = xyd->y;
738         sfree(xyd);
739
740         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
741             OFFSET(x2, y2, x1, y1, d1, state);
742             d2 = F(d1);
743
744             /*
745              * If the next tile in this direction is connected to
746              * us, and there isn't a barrier in the way, and it
747              * isn't already marked active, then mark it active and
748              * add it to the to-examine list.
749              */
750             if ((tile(state, x1, y1) & d1) &&
751                 (tile(state, x2, y2) & d2) &&
752                 !(barrier(state, x1, y1) & d1) &&
753                 !index(state, active, x2, y2)) {
754                 index(state, active, x2, y2) = ACTIVE;
755                 add234(todo, new_xyd(x2, y2, 0));
756             }
757         }
758     }
759     /* Now we expect the todo list to have shrunk to zero size. */
760     assert(count234(todo) == 0);
761     freetree234(todo);
762
763     return active;
764 }
765
766 struct game_ui {
767     int cur_x, cur_y;
768     int cur_visible;
769 };
770
771 game_ui *new_ui(game_state *state)
772 {
773     game_ui *ui = snew(game_ui);
774     ui->cur_x = state->width / 2;
775     ui->cur_y = state->height / 2;
776     ui->cur_visible = FALSE;
777
778     return ui;
779 }
780
781 void free_ui(game_ui *ui)
782 {
783     sfree(ui);
784 }
785
786 /* ----------------------------------------------------------------------
787  * Process a move.
788  */
789 game_state *make_move(game_state *state, game_ui *ui, int x, int y, int button)
790 {
791     game_state *ret, *nullret;
792     int tx, ty, orig;
793
794     nullret = NULL;
795
796     if (button == LEFT_BUTTON ||
797         button == MIDDLE_BUTTON ||
798         button == RIGHT_BUTTON) {
799
800         if (ui->cur_visible) {
801             ui->cur_visible = FALSE;
802             nullret = state;
803         }
804
805         /*
806          * The button must have been clicked on a valid tile.
807          */
808         x -= WINDOW_OFFSET + TILE_BORDER;
809         y -= WINDOW_OFFSET + TILE_BORDER;
810         if (x < 0 || y < 0)
811             return nullret;
812         tx = x / TILE_SIZE;
813         ty = y / TILE_SIZE;
814         if (tx >= state->width || ty >= state->height)
815             return nullret;
816         if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
817             y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
818             return nullret;
819     } else if (button == CURSOR_UP || button == CURSOR_DOWN ||
820                button == CURSOR_RIGHT || button == CURSOR_LEFT) {
821         if (button == CURSOR_UP && ui->cur_y > 0)
822             ui->cur_y--;
823         else if (button == CURSOR_DOWN && ui->cur_y < state->height-1)
824             ui->cur_y++;
825         else if (button == CURSOR_LEFT && ui->cur_x > 0)
826             ui->cur_x--;
827         else if (button == CURSOR_RIGHT && ui->cur_x < state->width-1)
828             ui->cur_x++;
829         else
830             return nullret;            /* no cursor movement */
831         ui->cur_visible = TRUE;
832         return state;                  /* UI activity has occurred */
833     } else if (button == 'a' || button == 's' || button == 'd' ||
834                button == 'A' || button == 'S' || button == 'D') {
835         tx = ui->cur_x;
836         ty = ui->cur_y;
837         if (button == 'a' || button == 'A')
838             button = LEFT_BUTTON;
839         else if (button == 's' || button == 'S')
840             button = MIDDLE_BUTTON;
841         else if (button == 'd' || button == 'D')
842             button = RIGHT_BUTTON;
843     } else
844         return nullret;
845
846     /*
847      * The middle button locks or unlocks a tile. (A locked tile
848      * cannot be turned, and is visually marked as being locked.
849      * This is a convenience for the player, so that once they are
850      * sure which way round a tile goes, they can lock it and thus
851      * avoid forgetting later on that they'd already done that one;
852      * and the locking also prevents them turning the tile by
853      * accident. If they change their mind, another middle click
854      * unlocks it.)
855      */
856     if (button == MIDDLE_BUTTON) {
857         ret = dup_game(state);
858         tile(ret, tx, ty) ^= LOCKED;
859         return ret;
860     }
861
862     /*
863      * The left and right buttons have no effect if clicked on a
864      * locked tile.
865      */
866     if (tile(state, tx, ty) & LOCKED)
867         return nullret;
868
869     /*
870      * Otherwise, turn the tile one way or the other. Left button
871      * turns anticlockwise; right button turns clockwise.
872      */
873     ret = dup_game(state);
874     orig = tile(ret, tx, ty);
875     if (button == LEFT_BUTTON) {
876         tile(ret, tx, ty) = A(orig);
877         ret->last_rotate_dir = +1;
878     } else {
879         tile(ret, tx, ty) = C(orig);
880         ret->last_rotate_dir = -1;
881     }
882
883     /*
884      * Check whether the game has been completed.
885      */
886     {
887         unsigned char *active = compute_active(ret);
888         int x1, y1;
889         int complete = TRUE;
890
891         for (x1 = 0; x1 < ret->width; x1++)
892             for (y1 = 0; y1 < ret->height; y1++)
893                 if (!index(ret, active, x1, y1)) {
894                     complete = FALSE;
895                     goto break_label;  /* break out of two loops at once */
896                 }
897         break_label:
898
899         sfree(active);
900
901         if (complete)
902             ret->completed = TRUE;
903     }
904
905     return ret;
906 }
907
908 /* ----------------------------------------------------------------------
909  * Routines for drawing the game position on the screen.
910  */
911
912 struct game_drawstate {
913     int started;
914     int width, height;
915     unsigned char *visible;
916 };
917
918 game_drawstate *game_new_drawstate(game_state *state)
919 {
920     game_drawstate *ds = snew(game_drawstate);
921
922     ds->started = FALSE;
923     ds->width = state->width;
924     ds->height = state->height;
925     ds->visible = snewn(state->width * state->height, unsigned char);
926     memset(ds->visible, 0xFF, state->width * state->height);
927
928     return ds;
929 }
930
931 void game_free_drawstate(game_drawstate *ds)
932 {
933     sfree(ds->visible);
934     sfree(ds);
935 }
936
937 void game_size(game_params *params, int *x, int *y)
938 {
939     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
940     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
941 }
942
943 float *game_colours(frontend *fe, game_state *state, int *ncolours)
944 {
945     float *ret;
946
947     ret = snewn(NCOLOURS * 3, float);
948     *ncolours = NCOLOURS;
949
950     /*
951      * Basic background colour is whatever the front end thinks is
952      * a sensible default.
953      */
954     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
955
956     /*
957      * Wires are black.
958      */
959     ret[COL_WIRE * 3 + 0] = 0.0F;
960     ret[COL_WIRE * 3 + 1] = 0.0F;
961     ret[COL_WIRE * 3 + 2] = 0.0F;
962
963     /*
964      * Powered wires and powered endpoints are cyan.
965      */
966     ret[COL_POWERED * 3 + 0] = 0.0F;
967     ret[COL_POWERED * 3 + 1] = 1.0F;
968     ret[COL_POWERED * 3 + 2] = 1.0F;
969
970     /*
971      * Barriers are red.
972      */
973     ret[COL_BARRIER * 3 + 0] = 1.0F;
974     ret[COL_BARRIER * 3 + 1] = 0.0F;
975     ret[COL_BARRIER * 3 + 2] = 0.0F;
976
977     /*
978      * Unpowered endpoints are blue.
979      */
980     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
981     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
982     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
983
984     /*
985      * Tile borders are a darker grey than the background.
986      */
987     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
988     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
989     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
990
991     /*
992      * Locked tiles are a grey in between those two.
993      */
994     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
995     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
996     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
997
998     return ret;
999 }
1000
1001 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
1002                             int colour)
1003 {
1004     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
1005     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
1006     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
1007     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
1008     draw_line(fe, x1, y1, x2, y2, colour);
1009 }
1010
1011 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
1012                              int colour)
1013 {
1014     int mx = (x1 < x2 ? x1 : x2);
1015     int my = (y1 < y2 ? y1 : y2);
1016     int dx = (x2 + x1 - 2*mx + 1);
1017     int dy = (y2 + y1 - 2*my + 1);
1018
1019     draw_rect(fe, mx, my, dx, dy, colour);
1020 }
1021
1022 static void draw_barrier_corner(frontend *fe, int x, int y, int dir, int phase)
1023 {
1024     int bx = WINDOW_OFFSET + TILE_SIZE * x;
1025     int by = WINDOW_OFFSET + TILE_SIZE * y;
1026     int x1, y1, dx, dy, dir2;
1027
1028     dir >>= 4;
1029
1030     dir2 = A(dir);
1031     dx = X(dir) + X(dir2);
1032     dy = Y(dir) + Y(dir2);
1033     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
1034     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
1035
1036     if (phase == 0) {
1037         draw_rect_coords(fe, bx+x1, by+y1,
1038                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
1039                          COL_WIRE);
1040         draw_rect_coords(fe, bx+x1, by+y1,
1041                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
1042                          COL_WIRE);
1043     } else {
1044         draw_rect_coords(fe, bx+x1, by+y1,
1045                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
1046                          COL_BARRIER);
1047     }
1048 }
1049
1050 static void draw_barrier(frontend *fe, int x, int y, int dir, int phase)
1051 {
1052     int bx = WINDOW_OFFSET + TILE_SIZE * x;
1053     int by = WINDOW_OFFSET + TILE_SIZE * y;
1054     int x1, y1, w, h;
1055
1056     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
1057     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
1058     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
1059     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
1060
1061     if (phase == 0) {
1062         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
1063     } else {
1064         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
1065     }
1066 }
1067
1068 static void draw_tile(frontend *fe, game_state *state, int x, int y, int tile,
1069                       float angle, int cursor)
1070 {
1071     int bx = WINDOW_OFFSET + TILE_SIZE * x;
1072     int by = WINDOW_OFFSET + TILE_SIZE * y;
1073     float matrix[4];
1074     float cx, cy, ex, ey, tx, ty;
1075     int dir, col, phase;
1076
1077     /*
1078      * When we draw a single tile, we must draw everything up to
1079      * and including the borders around the tile. This means that
1080      * if the neighbouring tiles have connections to those borders,
1081      * we must draw those connections on the borders themselves.
1082      *
1083      * This would be terribly fiddly if we ever had to draw a tile
1084      * while its neighbour was in mid-rotate, because we'd have to
1085      * arrange to _know_ that the neighbour was being rotated and
1086      * hence had an anomalous effect on the redraw of this tile.
1087      * Fortunately, the drawing algorithm avoids ever calling us in
1088      * this circumstance: we're either drawing lots of straight
1089      * tiles at game start or after a move is complete, or we're
1090      * repeatedly drawing only the rotating tile. So no problem.
1091      */
1092
1093     /*
1094      * So. First blank the tile out completely: draw a big
1095      * rectangle in border colour, and a smaller rectangle in
1096      * background colour to fill it in.
1097      */
1098     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
1099               COL_BORDER);
1100     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
1101               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
1102               tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
1103
1104     /*
1105      * Draw an inset outline rectangle as a cursor, in whichever of
1106      * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
1107      * in.
1108      */
1109     if (cursor) {
1110         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
1111                   bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
1112                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
1113         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
1114                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
1115                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
1116         draw_line(fe, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
1117                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
1118                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
1119         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
1120                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
1121                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
1122     }
1123
1124     /*
1125      * Set up the rotation matrix.
1126      */
1127     matrix[0] = (float)cos(angle * PI / 180.0);
1128     matrix[1] = (float)-sin(angle * PI / 180.0);
1129     matrix[2] = (float)sin(angle * PI / 180.0);
1130     matrix[3] = (float)cos(angle * PI / 180.0);
1131
1132     /*
1133      * Draw the wires.
1134      */
1135     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
1136     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
1137     for (dir = 1; dir < 0x10; dir <<= 1) {
1138         if (tile & dir) {
1139             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1140             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1141             MATMUL(tx, ty, matrix, ex, ey);
1142             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
1143                             bx+(int)(cx+tx), by+(int)(cy+ty),
1144                             COL_WIRE);
1145         }
1146     }
1147     for (dir = 1; dir < 0x10; dir <<= 1) {
1148         if (tile & dir) {
1149             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1150             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1151             MATMUL(tx, ty, matrix, ex, ey);
1152             draw_line(fe, bx+(int)cx, by+(int)cy,
1153                       bx+(int)(cx+tx), by+(int)(cy+ty), col);
1154         }
1155     }
1156
1157     /*
1158      * Draw the box in the middle. We do this in blue if the tile
1159      * is an unpowered endpoint, in cyan if the tile is a powered
1160      * endpoint, in black if the tile is the centrepiece, and
1161      * otherwise not at all.
1162      */
1163     col = -1;
1164     if (x == state->cx && y == state->cy)
1165         col = COL_WIRE;
1166     else if (COUNT(tile) == 1) {
1167         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
1168     }
1169     if (col >= 0) {
1170         int i, points[8];
1171
1172         points[0] = +1; points[1] = +1;
1173         points[2] = +1; points[3] = -1;
1174         points[4] = -1; points[5] = -1;
1175         points[6] = -1; points[7] = +1;
1176
1177         for (i = 0; i < 8; i += 2) {
1178             ex = (TILE_SIZE * 0.24F) * points[i];
1179             ey = (TILE_SIZE * 0.24F) * points[i+1];
1180             MATMUL(tx, ty, matrix, ex, ey);
1181             points[i] = bx+(int)(cx+tx);
1182             points[i+1] = by+(int)(cy+ty);
1183         }
1184
1185         draw_polygon(fe, points, 4, TRUE, col);
1186         draw_polygon(fe, points, 4, FALSE, COL_WIRE);
1187     }
1188
1189     /*
1190      * Draw the points on the border if other tiles are connected
1191      * to us.
1192      */
1193     for (dir = 1; dir < 0x10; dir <<= 1) {
1194         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
1195
1196         dx = X(dir);
1197         dy = Y(dir);
1198
1199         ox = x + dx;
1200         oy = y + dy;
1201
1202         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
1203             continue;
1204
1205         if (!(tile(state, ox, oy) & F(dir)))
1206             continue;
1207
1208         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
1209         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
1210         lx = dx * (TILE_BORDER-1);
1211         ly = dy * (TILE_BORDER-1);
1212         vx = (dy ? 1 : 0);
1213         vy = (dx ? 1 : 0);
1214
1215         if (angle == 0.0 && (tile & dir)) {
1216             /*
1217              * If we are fully connected to the other tile, we must
1218              * draw right across the tile border. (We can use our
1219              * own ACTIVE state to determine what colour to do this
1220              * in: if we are fully connected to the other tile then
1221              * the two ACTIVE states will be the same.)
1222              */
1223             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
1224             draw_rect_coords(fe, px, py, px+lx, py+ly,
1225                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
1226         } else {
1227             /*
1228              * The other tile extends into our border, but isn't
1229              * actually connected to us. Just draw a single black
1230              * dot.
1231              */
1232             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
1233         }
1234     }
1235
1236     /*
1237      * Draw barrier corners, and then barriers.
1238      */
1239     for (phase = 0; phase < 2; phase++) {
1240         for (dir = 1; dir < 0x10; dir <<= 1)
1241             if (barrier(state, x, y) & (dir << 4))
1242                 draw_barrier_corner(fe, x, y, dir << 4, phase);
1243         for (dir = 1; dir < 0x10; dir <<= 1)
1244             if (barrier(state, x, y) & dir)
1245                 draw_barrier(fe, x, y, dir, phase);
1246     }
1247
1248     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
1249 }
1250
1251 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1252                  game_state *state, game_ui *ui, float t, float ft)
1253 {
1254     int x, y, tx, ty, frame;
1255     unsigned char *active;
1256     float angle = 0.0;
1257
1258     /*
1259      * Clear the screen and draw the exterior barrier lines if this
1260      * is our first call.
1261      */
1262     if (!ds->started) {
1263         int phase;
1264
1265         ds->started = TRUE;
1266
1267         draw_rect(fe, 0, 0, 
1268                   WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
1269                   WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
1270                   COL_BACKGROUND);
1271         draw_update(fe, 0, 0, 
1272                     WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
1273                     WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
1274
1275         for (phase = 0; phase < 2; phase++) {
1276
1277             for (x = 0; x < ds->width; x++) {
1278                 if (barrier(state, x, 0) & UL)
1279                     draw_barrier_corner(fe, x, -1, LD, phase);
1280                 if (barrier(state, x, 0) & RU)
1281                     draw_barrier_corner(fe, x, -1, DR, phase);
1282                 if (barrier(state, x, 0) & U)
1283                     draw_barrier(fe, x, -1, D, phase);
1284                 if (barrier(state, x, ds->height-1) & DR)
1285                     draw_barrier_corner(fe, x, ds->height, RU, phase);
1286                 if (barrier(state, x, ds->height-1) & LD)
1287                     draw_barrier_corner(fe, x, ds->height, UL, phase);
1288                 if (barrier(state, x, ds->height-1) & D)
1289                     draw_barrier(fe, x, ds->height, U, phase);
1290             }
1291
1292             for (y = 0; y < ds->height; y++) {
1293                 if (barrier(state, 0, y) & UL)
1294                     draw_barrier_corner(fe, -1, y, RU, phase);
1295                 if (barrier(state, 0, y) & LD)
1296                     draw_barrier_corner(fe, -1, y, DR, phase);
1297                 if (barrier(state, 0, y) & L)
1298                     draw_barrier(fe, -1, y, R, phase);
1299                 if (barrier(state, ds->width-1, y) & RU)
1300                     draw_barrier_corner(fe, ds->width, y, UL, phase);
1301                 if (barrier(state, ds->width-1, y) & DR)
1302                     draw_barrier_corner(fe, ds->width, y, LD, phase);
1303                 if (barrier(state, ds->width-1, y) & R)
1304                     draw_barrier(fe, ds->width, y, L, phase);
1305             }
1306         }
1307     }
1308
1309     tx = ty = -1;
1310     if (oldstate && (t < ROTATE_TIME)) {
1311         /*
1312          * We're animating a tile rotation. Find the turning tile,
1313          * if any.
1314          */
1315         for (x = 0; x < oldstate->width; x++)
1316             for (y = 0; y < oldstate->height; y++)
1317                 if ((tile(oldstate, x, y) ^ tile(state, x, y)) & 0xF) {
1318                     tx = x, ty = y;
1319                     goto break_label;  /* leave both loops at once */
1320                 }
1321         break_label:
1322
1323         if (tx >= 0) {
1324             if (tile(state, tx, ty) == ROT(tile(oldstate, tx, ty),
1325                                            state->last_rotate_dir))
1326                 angle = state->last_rotate_dir * 90.0F * (t / ROTATE_TIME);
1327             else
1328                 angle = state->last_rotate_dir * -90.0F * (t / ROTATE_TIME);
1329             state = oldstate;
1330         }
1331     }
1332     
1333     frame = -1;
1334     if (ft > 0) {
1335         /*
1336          * We're animating a completion flash. Find which frame
1337          * we're at.
1338          */
1339         frame = (int)(ft / FLASH_FRAME);
1340     }
1341
1342     /*
1343      * Draw any tile which differs from the way it was last drawn.
1344      */
1345     active = compute_active(state);
1346
1347     for (x = 0; x < ds->width; x++)
1348         for (y = 0; y < ds->height; y++) {
1349             unsigned char c = tile(state, x, y) | index(state, active, x, y);
1350
1351             /*
1352              * In a completion flash, we adjust the LOCKED bit
1353              * depending on our distance from the centre point and
1354              * the frame number.
1355              */
1356             if (frame >= 0) {
1357                 int xdist, ydist, dist;
1358                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
1359                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
1360                 dist = (xdist > ydist ? xdist : ydist);
1361
1362                 if (frame >= dist && frame < dist+4) {
1363                     int lock = (frame - dist) & 1;
1364                     lock = lock ? LOCKED : 0;
1365                     c = (c &~ LOCKED) | lock;
1366                 }
1367             }
1368
1369             if (index(state, ds->visible, x, y) != c ||
1370                 index(state, ds->visible, x, y) == 0xFF ||
1371                 (x == tx && y == ty) ||
1372                 (ui->cur_visible && x == ui->cur_x && y == ui->cur_y)) {
1373                 draw_tile(fe, state, x, y, c,
1374                           (x == tx && y == ty ? angle : 0.0F),
1375                           (ui->cur_visible && x == ui->cur_x && y == ui->cur_y));
1376                 if ((x == tx && y == ty) ||
1377                     (ui->cur_visible && x == ui->cur_x && y == ui->cur_y))
1378                     index(state, ds->visible, x, y) = 0xFF;
1379                 else
1380                     index(state, ds->visible, x, y) = c;
1381             }
1382         }
1383
1384     /*
1385      * Update the status bar.
1386      */
1387     {
1388         char statusbuf[256];
1389         int i, n, a;
1390
1391         n = state->width * state->height;
1392         for (i = a = 0; i < n; i++)
1393             if (active[i])
1394                 a++;
1395
1396         sprintf(statusbuf, "%sActive: %d/%d",
1397                 (state->completed ? "COMPLETED! " : ""), a, n);
1398
1399         status_bar(fe, statusbuf);
1400     }
1401
1402     sfree(active);
1403 }
1404
1405 float game_anim_length(game_state *oldstate, game_state *newstate)
1406 {
1407     int x, y;
1408
1409     /*
1410      * If there's a tile which has been rotated, allow time to
1411      * animate its rotation.
1412      */
1413     for (x = 0; x < oldstate->width; x++)
1414         for (y = 0; y < oldstate->height; y++)
1415             if ((tile(oldstate, x, y) ^ tile(newstate, x, y)) & 0xF) {
1416                 return ROTATE_TIME;
1417             }
1418
1419     return 0.0F;
1420 }
1421
1422 float game_flash_length(game_state *oldstate, game_state *newstate)
1423 {
1424     /*
1425      * If the game has just been completed, we display a completion
1426      * flash.
1427      */
1428     if (!oldstate->completed && newstate->completed) {
1429         int size;
1430         size = 0;
1431         if (size < newstate->cx+1)
1432             size = newstate->cx+1;
1433         if (size < newstate->cy+1)
1434             size = newstate->cy+1;
1435         if (size < newstate->width - newstate->cx)
1436             size = newstate->width - newstate->cx;
1437         if (size < newstate->height - newstate->cy)
1438             size = newstate->height - newstate->cy;
1439         return FLASH_FRAME * (size+4);
1440     }
1441
1442     return 0.0F;
1443 }
1444
1445 int game_wants_statusbar(void)
1446 {
1447     return TRUE;
1448 }