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