chiark / gitweb /
draw_polygon() and draw_circle() have always had a portability
[sgt-puzzles.git] / netslide.c
1 /*
2  * netslide.c: cross between Net and Sixteen, courtesy of Richard
3  * Boulton.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <math.h>
12
13 #include "puzzles.h"
14 #include "tree234.h"
15
16 #define MATMUL(xr,yr,m,x,y) do { \
17     float rx, ry, xx = (x), yy = (y), *mat = (m); \
18     rx = mat[0] * xx + mat[2] * yy; \
19     ry = mat[1] * xx + mat[3] * yy; \
20     (xr) = rx; (yr) = ry; \
21 } while (0)
22
23 /* Direction and other bitfields */
24 #define R 0x01
25 #define U 0x02
26 #define L 0x04
27 #define D 0x08
28 #define FLASHING 0x10
29 #define ACTIVE 0x20
30 /* Corner flags go in the barriers array */
31 #define RU 0x10
32 #define UL 0x20
33 #define LD 0x40
34 #define DR 0x80
35
36 /* Get tile at given coordinate */
37 #define T(state, x, y) ( (y) * (state)->width + (x) )
38
39 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
40 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
41 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
42 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
43 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
44                     ((n)&3) == 1 ? A(x) : \
45                     ((n)&3) == 2 ? F(x) : C(x) )
46
47 /* X and Y displacements */
48 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
49 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
50
51 /* Bit count */
52 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
53                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
54
55 #define PREFERRED_TILE_SIZE 48
56 #define TILE_SIZE (ds->tilesize)
57 #define BORDER TILE_SIZE
58 #define TILE_BORDER 1
59 #define WINDOW_OFFSET 0
60
61 #define ANIM_TIME 0.13F
62 #define FLASH_FRAME 0.07F
63
64 enum {
65     COL_BACKGROUND,
66     COL_FLASHING,
67     COL_BORDER,
68     COL_WIRE,
69     COL_ENDPOINT,
70     COL_POWERED,
71     COL_BARRIER,
72     COL_LOWLIGHT,
73     COL_TEXT,
74     NCOLOURS
75 };
76
77 struct game_params {
78     int width;
79     int height;
80     int wrapping;
81     float barrier_probability;
82     int movetarget;
83 };
84
85 struct game_state {
86     int width, height, cx, cy, wrapping, completed;
87     int used_solve, just_used_solve;
88     int move_count, movetarget;
89
90     /* position (row or col number, starting at 0) of last move. */
91     int last_move_row, last_move_col;
92
93     /* direction of last move: +1 or -1 */
94     int last_move_dir;
95
96     unsigned char *tiles;
97     unsigned char *barriers;
98 };
99
100 #define OFFSET(x2,y2,x1,y1,dir,state) \
101     ( (x2) = ((x1) + (state)->width + X((dir))) % (state)->width, \
102       (y2) = ((y1) + (state)->height + Y((dir))) % (state)->height)
103
104 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
105 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
106 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
107
108 struct xyd {
109     int x, y, direction;
110 };
111
112 static int xyd_cmp(void *av, void *bv) {
113     struct xyd *a = (struct xyd *)av;
114     struct xyd *b = (struct xyd *)bv;
115     if (a->x < b->x)
116         return -1;
117     if (a->x > b->x)
118         return +1;
119     if (a->y < b->y)
120         return -1;
121     if (a->y > b->y)
122         return +1;
123     if (a->direction < b->direction)
124         return -1;
125     if (a->direction > b->direction)
126         return +1;
127     return 0;
128 }
129
130 static struct xyd *new_xyd(int x, int y, int direction)
131 {
132     struct xyd *xyd = snew(struct xyd);
133     xyd->x = x;
134     xyd->y = y;
135     xyd->direction = direction;
136     return xyd;
137 }
138
139 static void slide_col(game_state *state, int dir, int col);
140 static void slide_col_int(int w, int h, unsigned char *tiles, int dir, int col);
141 static void slide_row(game_state *state, int dir, int row);
142 static void slide_row_int(int w, int h, unsigned char *tiles, int dir, int row);
143
144 /* ----------------------------------------------------------------------
145  * Manage game parameters.
146  */
147 static game_params *default_params(void)
148 {
149     game_params *ret = snew(game_params);
150
151     ret->width = 3;
152     ret->height = 3;
153     ret->wrapping = FALSE;
154     ret->barrier_probability = 1.0;
155     ret->movetarget = 0;
156
157     return ret;
158 }
159
160 static const struct { int x, y, wrap, bprob; const char* desc; }
161 netslide_presets[] = {
162     {3, 3, FALSE, 1.0, " easy"},
163     {3, 3, FALSE, 0.0, " medium"},
164     {3, 3, TRUE,  0.0, " hard"},
165     {4, 4, FALSE, 1.0, " easy"},
166     {4, 4, FALSE, 0.0, " medium"},
167     {4, 4, TRUE,  0.0, " hard"},
168     {5, 5, FALSE, 1.0, " easy"},
169     {5, 5, FALSE, 0.0, " medium"},
170     {5, 5, TRUE,  0.0, " hard"},
171 };
172
173 static int game_fetch_preset(int i, char **name, game_params **params)
174 {
175     game_params *ret;
176     char str[80];
177
178     if (i < 0 || i >= lenof(netslide_presets))
179         return FALSE;
180
181     ret = snew(game_params);
182     ret->width = netslide_presets[i].x;
183     ret->height = netslide_presets[i].y;
184     ret->wrapping = netslide_presets[i].wrap;
185     ret->barrier_probability = netslide_presets[i].bprob;
186     ret->movetarget = 0;
187
188     sprintf(str, "%dx%d%s", ret->width, ret->height, netslide_presets[i].desc);
189
190     *name = dupstr(str);
191     *params = ret;
192     return TRUE;
193 }
194
195 static void free_params(game_params *params)
196 {
197     sfree(params);
198 }
199
200 static game_params *dup_params(game_params *params)
201 {
202     game_params *ret = snew(game_params);
203     *ret = *params;                    /* structure copy */
204     return ret;
205 }
206
207 static void decode_params(game_params *ret, char const *string)
208 {
209     char const *p = string;
210
211     ret->wrapping = FALSE;
212     ret->barrier_probability = 0.0;
213     ret->movetarget = 0;
214
215     ret->width = atoi(p);
216     while (*p && isdigit(*p)) p++;
217     if (*p == 'x') {
218         p++;
219         ret->height = atoi(p);
220         while (*p && isdigit(*p)) p++;
221         if ( (ret->wrapping = (*p == 'w')) != 0 )
222             p++;
223         if (*p == 'b') {
224             ret->barrier_probability = atof(++p);
225             while (*p && (isdigit(*p) || *p == '.')) p++;
226         }
227         if (*p == 'm') {
228             ret->movetarget = atoi(++p);
229         }
230     } else {
231         ret->height = ret->width;
232     }
233 }
234
235 static char *encode_params(game_params *params, int full)
236 {
237     char ret[400];
238     int len;
239
240     len = sprintf(ret, "%dx%d", params->width, params->height);
241     if (params->wrapping)
242         ret[len++] = 'w';
243     if (full && params->barrier_probability)
244         len += sprintf(ret+len, "b%g", params->barrier_probability);
245     /* Shuffle limit is part of the limited parameters, because we have to
246      * provide the target move count. */
247     if (params->movetarget)
248         len += sprintf(ret+len, "m%d", params->movetarget);
249     assert(len < lenof(ret));
250     ret[len] = '\0';
251
252     return dupstr(ret);
253 }
254
255 static config_item *game_configure(game_params *params)
256 {
257     config_item *ret;
258     char buf[80];
259
260     ret = snewn(6, config_item);
261
262     ret[0].name = "Width";
263     ret[0].type = C_STRING;
264     sprintf(buf, "%d", params->width);
265     ret[0].sval = dupstr(buf);
266     ret[0].ival = 0;
267
268     ret[1].name = "Height";
269     ret[1].type = C_STRING;
270     sprintf(buf, "%d", params->height);
271     ret[1].sval = dupstr(buf);
272     ret[1].ival = 0;
273
274     ret[2].name = "Walls wrap around";
275     ret[2].type = C_BOOLEAN;
276     ret[2].sval = NULL;
277     ret[2].ival = params->wrapping;
278
279     ret[3].name = "Barrier probability";
280     ret[3].type = C_STRING;
281     sprintf(buf, "%g", params->barrier_probability);
282     ret[3].sval = dupstr(buf);
283     ret[3].ival = 0;
284
285     ret[4].name = "Number of shuffling moves";
286     ret[4].type = C_STRING;
287     sprintf(buf, "%d", params->movetarget);
288     ret[4].sval = dupstr(buf);
289     ret[4].ival = 0;
290
291     ret[5].name = NULL;
292     ret[5].type = C_END;
293     ret[5].sval = NULL;
294     ret[5].ival = 0;
295
296     return ret;
297 }
298
299 static game_params *custom_params(config_item *cfg)
300 {
301     game_params *ret = snew(game_params);
302
303     ret->width = atoi(cfg[0].sval);
304     ret->height = atoi(cfg[1].sval);
305     ret->wrapping = cfg[2].ival;
306     ret->barrier_probability = (float)atof(cfg[3].sval);
307     ret->movetarget = atoi(cfg[4].sval);
308
309     return ret;
310 }
311
312 static char *validate_params(game_params *params)
313 {
314     if (params->width <= 1 || params->height <= 1)
315         return "Width and height must both be greater than one";
316     if (params->barrier_probability < 0)
317         return "Barrier probability may not be negative";
318     if (params->barrier_probability > 1)
319         return "Barrier probability may not be greater than 1";
320     return NULL;
321 }
322
323 /* ----------------------------------------------------------------------
324  * Randomly select a new game description.
325  */
326
327 static char *new_game_desc(game_params *params, random_state *rs,
328                            char **aux, int interactive)
329 {
330     tree234 *possibilities, *barriertree;
331     int w, h, x, y, cx, cy, nbarriers;
332     unsigned char *tiles, *barriers;
333     char *desc, *p;
334
335     w = params->width;
336     h = params->height;
337
338     tiles = snewn(w * h, unsigned char);
339     memset(tiles, 0, w * h);
340     barriers = snewn(w * h, unsigned char);
341     memset(barriers, 0, w * h);
342
343     cx = w / 2;
344     cy = h / 2;
345
346     /*
347      * Construct the unshuffled grid.
348      * 
349      * To do this, we simply start at the centre point, repeatedly
350      * choose a random possibility out of the available ways to
351      * extend a used square into an unused one, and do it. After
352      * extending the third line out of a square, we remove the
353      * fourth from the possibilities list to avoid any full-cross
354      * squares (which would make the game too easy because they
355      * only have one orientation).
356      * 
357      * The slightly worrying thing is the avoidance of full-cross
358      * squares. Can this cause our unsophisticated construction
359      * algorithm to paint itself into a corner, by getting into a
360      * situation where there are some unreached squares and the
361      * only way to reach any of them is to extend a T-piece into a
362      * full cross?
363      * 
364      * Answer: no it can't, and here's a proof.
365      * 
366      * Any contiguous group of such unreachable squares must be
367      * surrounded on _all_ sides by T-pieces pointing away from the
368      * group. (If not, then there is a square which can be extended
369      * into one of the `unreachable' ones, and so it wasn't
370      * unreachable after all.) In particular, this implies that
371      * each contiguous group of unreachable squares must be
372      * rectangular in shape (any deviation from that yields a
373      * non-T-piece next to an `unreachable' square).
374      * 
375      * So we have a rectangle of unreachable squares, with T-pieces
376      * forming a solid border around the rectangle. The corners of
377      * that border must be connected (since every tile connects all
378      * the lines arriving in it), and therefore the border must
379      * form a closed loop around the rectangle.
380      * 
381      * But this can't have happened in the first place, since we
382      * _know_ we've avoided creating closed loops! Hence, no such
383      * situation can ever arise, and the naive grid construction
384      * algorithm will guaranteeably result in a complete grid
385      * containing no unreached squares, no full crosses _and_ no
386      * closed loops. []
387      */
388     possibilities = newtree234(xyd_cmp);
389
390     if (cx+1 < w)
391         add234(possibilities, new_xyd(cx, cy, R));
392     if (cy-1 >= 0)
393         add234(possibilities, new_xyd(cx, cy, U));
394     if (cx-1 >= 0)
395         add234(possibilities, new_xyd(cx, cy, L));
396     if (cy+1 < h)
397         add234(possibilities, new_xyd(cx, cy, D));
398
399     while (count234(possibilities) > 0) {
400         int i;
401         struct xyd *xyd;
402         int x1, y1, d1, x2, y2, d2, d;
403
404         /*
405          * Extract a randomly chosen possibility from the list.
406          */
407         i = random_upto(rs, count234(possibilities));
408         xyd = delpos234(possibilities, i);
409         x1 = xyd->x;
410         y1 = xyd->y;
411         d1 = xyd->direction;
412         sfree(xyd);
413
414         OFFSET(x2, y2, x1, y1, d1, params);
415         d2 = F(d1);
416 #ifdef GENERATION_DIAGNOSTICS
417         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
418                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
419 #endif
420
421         /*
422          * Make the connection. (We should be moving to an as yet
423          * unused tile.)
424          */
425         index(params, tiles, x1, y1) |= d1;
426         assert(index(params, tiles, x2, y2) == 0);
427         index(params, tiles, x2, y2) |= d2;
428
429         /*
430          * If we have created a T-piece, remove its last
431          * possibility.
432          */
433         if (COUNT(index(params, tiles, x1, y1)) == 3) {
434             struct xyd xyd1, *xydp;
435
436             xyd1.x = x1;
437             xyd1.y = y1;
438             xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
439
440             xydp = find234(possibilities, &xyd1, NULL);
441
442             if (xydp) {
443 #ifdef GENERATION_DIAGNOSTICS
444                 printf("T-piece; removing (%d,%d,%c)\n",
445                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
446 #endif
447                 del234(possibilities, xydp);
448                 sfree(xydp);
449             }
450         }
451
452         /*
453          * Remove all other possibilities that were pointing at the
454          * tile we've just moved into.
455          */
456         for (d = 1; d < 0x10; d <<= 1) {
457             int x3, y3, d3;
458             struct xyd xyd1, *xydp;
459
460             OFFSET(x3, y3, x2, y2, d, params);
461             d3 = F(d);
462
463             xyd1.x = x3;
464             xyd1.y = y3;
465             xyd1.direction = d3;
466
467             xydp = find234(possibilities, &xyd1, NULL);
468
469             if (xydp) {
470 #ifdef GENERATION_DIAGNOSTICS
471                 printf("Loop avoidance; removing (%d,%d,%c)\n",
472                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
473 #endif
474                 del234(possibilities, xydp);
475                 sfree(xydp);
476             }
477         }
478
479         /*
480          * Add new possibilities to the list for moving _out_ of
481          * the tile we have just moved into.
482          */
483         for (d = 1; d < 0x10; d <<= 1) {
484             int x3, y3;
485
486             if (d == d2)
487                 continue;              /* we've got this one already */
488
489             if (!params->wrapping) {
490                 if (d == U && y2 == 0)
491                     continue;
492                 if (d == D && y2 == h-1)
493                     continue;
494                 if (d == L && x2 == 0)
495                     continue;
496                 if (d == R && x2 == w-1)
497                     continue;
498             }
499
500             OFFSET(x3, y3, x2, y2, d, params);
501
502             if (index(params, tiles, x3, y3))
503                 continue;              /* this would create a loop */
504
505 #ifdef GENERATION_DIAGNOSTICS
506             printf("New frontier; adding (%d,%d,%c)\n",
507                    x2, y2, "0RU3L567D9abcdef"[d]);
508 #endif
509             add234(possibilities, new_xyd(x2, y2, d));
510         }
511     }
512     /* Having done that, we should have no possibilities remaining. */
513     assert(count234(possibilities) == 0);
514     freetree234(possibilities);
515
516     /*
517      * Now compute a list of the possible barrier locations.
518      */
519     barriertree = newtree234(xyd_cmp);
520     for (y = 0; y < h; y++) {
521         for (x = 0; x < w; x++) {
522
523             if (!(index(params, tiles, x, y) & R) &&
524                 (params->wrapping || x < w-1))
525                 add234(barriertree, new_xyd(x, y, R));
526             if (!(index(params, tiles, x, y) & D) &&
527                 (params->wrapping || y < h-1))
528                 add234(barriertree, new_xyd(x, y, D));
529         }
530     }
531
532     /*
533      * Save the unshuffled grid in aux.
534      */
535     {
536         char *solution;
537         int i;
538
539         /*
540          * String format is exactly the same as a solve move, so we
541          * can just dupstr this in solve_game().
542          */
543
544         solution = snewn(w * h + 2, char);
545         solution[0] = 'S';
546         for (i = 0; i < w * h; i++)
547             solution[i+1] = "0123456789abcdef"[tiles[i] & 0xF];
548         solution[w*h+1] = '\0';
549
550         *aux = solution;
551     }
552
553     /*
554      * Now shuffle the grid.
555      * FIXME - this simply does a set of random moves to shuffle the pieces,
556      * although we make a token effort to avoid boring cases by avoiding moves
557      * that directly undo the previous one, or that repeat so often as to
558      * turn into fewer moves.
559      *
560      * A better way would be to number all the pieces, generate a placement
561      * for all the numbers as for "sixteen", observing parity constraints if
562      * neccessary, and then place the pieces according to their numbering.
563      * BUT - I'm not sure if this will work, since we disallow movement of
564      * the middle row and column.
565      */
566     {
567         int i;
568         int cols = w - 1;
569         int rows = h - 1;
570         int moves = params->movetarget;
571         int prevdir = -1, prevrowcol = -1, nrepeats = 0;
572         if (!moves) moves = cols * rows * 2;
573         for (i = 0; i < moves; /* incremented conditionally */) {
574             /* Choose a direction: 0,1,2,3 = up, right, down, left. */
575             int dir = random_upto(rs, 4);
576             int rowcol;
577             if (dir % 2 == 0) {
578                 int col = random_upto(rs, cols);
579                 if (col >= cx) col += 1;    /* avoid centre */
580                 if (col == prevrowcol) {
581                     if (dir == 2-prevdir)
582                         continue;   /* undoes last move */
583                     else if (dir == prevdir && (nrepeats+1)*2 > h)
584                         continue;   /* makes fewer moves */
585                 }
586                 slide_col_int(w, h, tiles, 1 - dir, col);
587                 rowcol = col;
588             } else {
589                 int row = random_upto(rs, rows);
590                 if (row >= cy) row += 1;    /* avoid centre */
591                 if (row == prevrowcol) {
592                     if (dir == 4-prevdir)
593                         continue;   /* undoes last move */
594                     else if (dir == prevdir && (nrepeats+1)*2 > w)
595                         continue;   /* makes fewer moves */
596                 }
597                 slide_row_int(w, h, tiles, 2 - dir, row);
598                 rowcol = row;
599             }
600             if (dir == prevdir && rowcol == prevrowcol)
601                 nrepeats++;
602             else
603                 nrepeats = 1;
604             prevdir = dir;
605             prevrowcol = rowcol;
606             i++;    /* if we got here, the move was accepted */
607         }
608     }
609
610     /*
611      * And now choose barrier locations. (We carefully do this
612      * _after_ shuffling, so that changing the barrier rate in the
613      * params while keeping the random seed the same will give the
614      * same shuffled grid and _only_ change the barrier locations.
615      * Also the way we choose barrier locations, by repeatedly
616      * choosing one possibility from the list until we have enough,
617      * is designed to ensure that raising the barrier rate while
618      * keeping the seed the same will provide a superset of the
619      * previous barrier set - i.e. if you ask for 10 barriers, and
620      * then decide that's still too hard and ask for 20, you'll get
621      * the original 10 plus 10 more, rather than getting 20 new
622      * ones and the chance of remembering your first 10.)
623      */
624     nbarriers = (int)(params->barrier_probability * count234(barriertree));
625     assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
626
627     while (nbarriers > 0) {
628         int i;
629         struct xyd *xyd;
630         int x1, y1, d1, x2, y2, d2;
631
632         /*
633          * Extract a randomly chosen barrier from the list.
634          */
635         i = random_upto(rs, count234(barriertree));
636         xyd = delpos234(barriertree, i);
637
638         assert(xyd != NULL);
639
640         x1 = xyd->x;
641         y1 = xyd->y;
642         d1 = xyd->direction;
643         sfree(xyd);
644
645         OFFSET(x2, y2, x1, y1, d1, params);
646         d2 = F(d1);
647
648         index(params, barriers, x1, y1) |= d1;
649         index(params, barriers, x2, y2) |= d2;
650
651         nbarriers--;
652     }
653
654     /*
655      * Clean up the rest of the barrier list.
656      */
657     {
658         struct xyd *xyd;
659
660         while ( (xyd = delpos234(barriertree, 0)) != NULL)
661             sfree(xyd);
662
663         freetree234(barriertree);
664     }
665
666     /*
667      * Finally, encode the grid into a string game description.
668      * 
669      * My syntax is extremely simple: each square is encoded as a
670      * hex digit in which bit 0 means a connection on the right,
671      * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
672      * encoding as used internally). Each digit is followed by
673      * optional barrier indicators: `v' means a vertical barrier to
674      * the right of it, and `h' means a horizontal barrier below
675      * it.
676      */
677     desc = snewn(w * h * 3 + 1, char);
678     p = desc;
679     for (y = 0; y < h; y++) {
680         for (x = 0; x < w; x++) {
681             *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
682             if ((params->wrapping || x < w-1) &&
683                 (index(params, barriers, x, y) & R))
684                 *p++ = 'v';
685             if ((params->wrapping || y < h-1) &&
686                 (index(params, barriers, x, y) & D))
687                 *p++ = 'h';
688         }
689     }
690     assert(p - desc <= w*h*3);
691     *p = '\0';
692
693     sfree(tiles);
694     sfree(barriers);
695
696     return desc;
697 }
698
699 static char *validate_desc(game_params *params, char *desc)
700 {
701     int w = params->width, h = params->height;
702     int i;
703
704     for (i = 0; i < w*h; i++) {
705         if (*desc >= '0' && *desc <= '9')
706             /* OK */;
707         else if (*desc >= 'a' && *desc <= 'f')
708             /* OK */;
709         else if (*desc >= 'A' && *desc <= 'F')
710             /* OK */;
711         else if (!*desc)
712             return "Game description shorter than expected";
713         else
714             return "Game description contained unexpected character";
715         desc++;
716         while (*desc == 'h' || *desc == 'v')
717             desc++;
718     }
719     if (*desc)
720         return "Game description longer than expected";
721
722     return NULL;
723 }
724
725 /* ----------------------------------------------------------------------
726  * Construct an initial game state, given a description and parameters.
727  */
728
729 static game_state *new_game(midend_data *me, game_params *params, char *desc)
730 {
731     game_state *state;
732     int w, h, x, y;
733
734     assert(params->width > 0 && params->height > 0);
735     assert(params->width > 1 || params->height > 1);
736
737     /*
738      * Create a blank game state.
739      */
740     state = snew(game_state);
741     w = state->width = params->width;
742     h = state->height = params->height;
743     state->cx = state->width / 2;
744     state->cy = state->height / 2;
745     state->wrapping = params->wrapping;
746     state->movetarget = params->movetarget;
747     state->completed = 0;
748     state->used_solve = state->just_used_solve = FALSE;
749     state->move_count = 0;
750     state->last_move_row = -1;
751     state->last_move_col = -1;
752     state->last_move_dir = 0;
753     state->tiles = snewn(state->width * state->height, unsigned char);
754     memset(state->tiles, 0, state->width * state->height);
755     state->barriers = snewn(state->width * state->height, unsigned char);
756     memset(state->barriers, 0, state->width * state->height);
757
758
759     /*
760      * Parse the game description into the grid.
761      */
762     for (y = 0; y < h; y++) {
763         for (x = 0; x < w; x++) {
764             if (*desc >= '0' && *desc <= '9')
765                 tile(state, x, y) = *desc - '0';
766             else if (*desc >= 'a' && *desc <= 'f')
767                 tile(state, x, y) = *desc - 'a' + 10;
768             else if (*desc >= 'A' && *desc <= 'F')
769                 tile(state, x, y) = *desc - 'A' + 10;
770             if (*desc)
771                 desc++;
772             while (*desc == 'h' || *desc == 'v') {
773                 int x2, y2, d1, d2;
774                 if (*desc == 'v')
775                     d1 = R;
776                 else
777                     d1 = D;
778
779                 OFFSET(x2, y2, x, y, d1, state);
780                 d2 = F(d1);
781
782                 barrier(state, x, y) |= d1;
783                 barrier(state, x2, y2) |= d2;
784
785                 desc++;
786             }
787         }
788     }
789
790     /*
791      * Set up border barriers if this is a non-wrapping game.
792      */
793     if (!state->wrapping) {
794         for (x = 0; x < state->width; x++) {
795             barrier(state, x, 0) |= U;
796             barrier(state, x, state->height-1) |= D;
797         }
798         for (y = 0; y < state->height; y++) {
799             barrier(state, 0, y) |= L;
800             barrier(state, state->width-1, y) |= R;
801         }
802     }
803
804     /*
805      * Set up the barrier corner flags, for drawing barriers
806      * prettily when they meet.
807      */
808     for (y = 0; y < state->height; y++) {
809         for (x = 0; x < state->width; x++) {
810             int dir;
811
812             for (dir = 1; dir < 0x10; dir <<= 1) {
813                 int dir2 = A(dir);
814                 int x1, y1, x2, y2, x3, y3;
815                 int corner = FALSE;
816
817                 if (!(barrier(state, x, y) & dir))
818                     continue;
819
820                 if (barrier(state, x, y) & dir2)
821                     corner = TRUE;
822
823                 x1 = x + X(dir), y1 = y + Y(dir);
824                 if (x1 >= 0 && x1 < state->width &&
825                     y1 >= 0 && y1 < state->height &&
826                     (barrier(state, x1, y1) & dir2))
827                     corner = TRUE;
828
829                 x2 = x + X(dir2), y2 = y + Y(dir2);
830                 if (x2 >= 0 && x2 < state->width &&
831                     y2 >= 0 && y2 < state->height &&
832                     (barrier(state, x2, y2) & dir))
833                     corner = TRUE;
834
835                 if (corner) {
836                     barrier(state, x, y) |= (dir << 4);
837                     if (x1 >= 0 && x1 < state->width &&
838                         y1 >= 0 && y1 < state->height)
839                         barrier(state, x1, y1) |= (A(dir) << 4);
840                     if (x2 >= 0 && x2 < state->width &&
841                         y2 >= 0 && y2 < state->height)
842                         barrier(state, x2, y2) |= (C(dir) << 4);
843                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
844                     if (x3 >= 0 && x3 < state->width &&
845                         y3 >= 0 && y3 < state->height)
846                         barrier(state, x3, y3) |= (F(dir) << 4);
847                 }
848             }
849         }
850     }
851
852     return state;
853 }
854
855 static game_state *dup_game(game_state *state)
856 {
857     game_state *ret;
858
859     ret = snew(game_state);
860     ret->width = state->width;
861     ret->height = state->height;
862     ret->cx = state->cx;
863     ret->cy = state->cy;
864     ret->wrapping = state->wrapping;
865     ret->movetarget = state->movetarget;
866     ret->completed = state->completed;
867     ret->used_solve = state->used_solve;
868     ret->just_used_solve = state->just_used_solve;
869     ret->move_count = state->move_count;
870     ret->last_move_row = state->last_move_row;
871     ret->last_move_col = state->last_move_col;
872     ret->last_move_dir = state->last_move_dir;
873     ret->tiles = snewn(state->width * state->height, unsigned char);
874     memcpy(ret->tiles, state->tiles, state->width * state->height);
875     ret->barriers = snewn(state->width * state->height, unsigned char);
876     memcpy(ret->barriers, state->barriers, state->width * state->height);
877
878     return ret;
879 }
880
881 static void free_game(game_state *state)
882 {
883     sfree(state->tiles);
884     sfree(state->barriers);
885     sfree(state);
886 }
887
888 static char *solve_game(game_state *state, game_state *currstate,
889                         char *aux, char **error)
890 {
891     if (!aux) {
892         *error = "Solution not known for this puzzle";
893         return NULL;
894     }
895
896     return dupstr(aux);
897 }
898
899 static char *game_text_format(game_state *state)
900 {
901     return NULL;
902 }
903
904 /* ----------------------------------------------------------------------
905  * Utility routine.
906  */
907
908 /*
909  * Compute which squares are reachable from the centre square, as a
910  * quick visual aid to determining how close the game is to
911  * completion. This is also a simple way to tell if the game _is_
912  * completed - just call this function and see whether every square
913  * is marked active.
914  *
915  * squares in the moving_row and moving_col are always inactive - this
916  * is so that "current" doesn't appear to jump across moving lines.
917  */
918 static unsigned char *compute_active(game_state *state,
919                                      int moving_row, int moving_col)
920 {
921     unsigned char *active;
922     tree234 *todo;
923     struct xyd *xyd;
924
925     active = snewn(state->width * state->height, unsigned char);
926     memset(active, 0, state->width * state->height);
927
928     /*
929      * We only store (x,y) pairs in todo, but it's easier to reuse
930      * xyd_cmp and just store direction 0 every time.
931      */
932     todo = newtree234(xyd_cmp);
933     index(state, active, state->cx, state->cy) = ACTIVE;
934     add234(todo, new_xyd(state->cx, state->cy, 0));
935
936     while ( (xyd = delpos234(todo, 0)) != NULL) {
937         int x1, y1, d1, x2, y2, d2;
938
939         x1 = xyd->x;
940         y1 = xyd->y;
941         sfree(xyd);
942
943         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
944             OFFSET(x2, y2, x1, y1, d1, state);
945             d2 = F(d1);
946
947             /*
948              * If the next tile in this direction is connected to
949              * us, and there isn't a barrier in the way, and it
950              * isn't already marked active, then mark it active and
951              * add it to the to-examine list.
952              */
953             if ((x2 != moving_col && y2 != moving_row) &&
954                 (tile(state, x1, y1) & d1) &&
955                 (tile(state, x2, y2) & d2) &&
956                 !(barrier(state, x1, y1) & d1) &&
957                 !index(state, active, x2, y2)) {
958                 index(state, active, x2, y2) = ACTIVE;
959                 add234(todo, new_xyd(x2, y2, 0));
960             }
961         }
962     }
963     /* Now we expect the todo list to have shrunk to zero size. */
964     assert(count234(todo) == 0);
965     freetree234(todo);
966
967     return active;
968 }
969
970 struct game_ui {
971     int cur_x, cur_y;
972     int cur_visible;
973 };
974
975 static game_ui *new_ui(game_state *state)
976 {
977     game_ui *ui = snew(game_ui);
978     ui->cur_x = state->width / 2;
979     ui->cur_y = state->height / 2;
980     ui->cur_visible = FALSE;
981
982     return ui;
983 }
984
985 static void free_ui(game_ui *ui)
986 {
987     sfree(ui);
988 }
989
990 static char *encode_ui(game_ui *ui)
991 {
992     return NULL;
993 }
994
995 static void decode_ui(game_ui *ui, char *encoding)
996 {
997 }
998
999 /* ----------------------------------------------------------------------
1000  * Process a move.
1001  */
1002
1003 static void slide_row_int(int w, int h, unsigned char *tiles, int dir, int row)
1004 {
1005     int x = dir > 0 ? -1 : w;
1006     int tx = x + dir;
1007     int n = w - 1;
1008     unsigned char endtile = tiles[row * w + tx];
1009     do {
1010         x = tx;
1011         tx = (x + dir + w) % w;
1012         tiles[row * w + x] = tiles[row * w + tx];
1013     } while (--n > 0);
1014     tiles[row * w + tx] = endtile;
1015 }
1016
1017 static void slide_col_int(int w, int h, unsigned char *tiles, int dir, int col)
1018 {
1019     int y = dir > 0 ? -1 : h;
1020     int ty = y + dir;
1021     int n = h - 1;
1022     unsigned char endtile = tiles[ty * w + col];
1023     do {
1024         y = ty;
1025         ty = (y + dir + h) % h;
1026         tiles[y * w + col] = tiles[ty * w + col];
1027     } while (--n > 0);
1028     tiles[ty * w + col] = endtile;
1029 }
1030
1031 static void slide_row(game_state *state, int dir, int row)
1032 {
1033     slide_row_int(state->width, state->height, state->tiles, dir, row);
1034 }
1035
1036 static void slide_col(game_state *state, int dir, int col)
1037 {
1038     slide_col_int(state->width, state->height, state->tiles, dir, col);
1039 }
1040
1041 static void game_changed_state(game_ui *ui, game_state *oldstate,
1042                                game_state *newstate)
1043 {
1044 }
1045
1046 struct game_drawstate {
1047     int started;
1048     int width, height;
1049     int tilesize;
1050     unsigned char *visible;
1051 };
1052
1053 static char *interpret_move(game_state *state, game_ui *ui,
1054                             game_drawstate *ds, int x, int y, int button)
1055 {
1056     int cx, cy;
1057     int n, dx, dy;
1058     char buf[80];
1059
1060     button &= ~MOD_MASK;
1061
1062     if (button != LEFT_BUTTON && button != RIGHT_BUTTON)
1063         return NULL;
1064
1065     cx = (x - (BORDER + WINDOW_OFFSET + TILE_BORDER) + 2*TILE_SIZE) / TILE_SIZE - 2;
1066     cy = (y - (BORDER + WINDOW_OFFSET + TILE_BORDER) + 2*TILE_SIZE) / TILE_SIZE - 2;
1067
1068     if (cy >= 0 && cy < state->height && cy != state->cy)
1069     {
1070         if (cx == -1) dx = +1;
1071         else if (cx == state->width) dx = -1;
1072         else return NULL;
1073         n = state->width;
1074         dy = 0;
1075     }
1076     else if (cx >= 0 && cx < state->width && cx != state->cx)
1077     {
1078         if (cy == -1) dy = +1;
1079         else if (cy == state->height) dy = -1;
1080         else return NULL;
1081         n = state->height;
1082         dx = 0;
1083     }
1084     else
1085         return NULL;
1086
1087     /* reverse direction if right hand button is pressed */
1088     if (button == RIGHT_BUTTON)
1089     {
1090         dx = -dx;
1091         dy = -dy;
1092     }
1093
1094     if (dx == 0)
1095         sprintf(buf, "C%d,%d", cx, dy);
1096     else
1097         sprintf(buf, "R%d,%d", cy, dx);
1098     return dupstr(buf);
1099 }
1100
1101 static game_state *execute_move(game_state *from, char *move)
1102 {
1103     game_state *ret;
1104     int c, d, col;
1105
1106     if ((move[0] == 'C' || move[0] == 'R') &&
1107         sscanf(move+1, "%d,%d", &c, &d) == 2 &&
1108         c >= 0 && c < (move[0] == 'C' ? from->width : from->height)) {
1109         col = (move[0] == 'C');
1110     } else if (move[0] == 'S' &&
1111                strlen(move) == from->width * from->height + 1) {
1112         int i;
1113         ret = dup_game(from);
1114         ret->used_solve = ret->just_used_solve = TRUE;
1115         ret->completed = ret->move_count = 1;
1116
1117         for (i = 0; i < from->width * from->height; i++) {
1118             c = move[i+1];
1119             if (c >= '0' && c <= '9')
1120                 c -= '0';
1121             else if (c >= 'A' && c <= 'F')
1122                 c -= 'A' - 10;
1123             else if (c >= 'a' && c <= 'f')
1124                 c -= 'a' - 10;
1125             else {
1126                 free_game(ret);
1127                 return NULL;
1128             }
1129             ret->tiles[i] = c;
1130         }
1131         return ret;
1132     } else
1133         return NULL;                   /* can't parse move string */
1134
1135     ret = dup_game(from);
1136     ret->just_used_solve = FALSE;
1137
1138     if (col)
1139         slide_col(ret, d, c);
1140     else
1141         slide_row(ret, d, c);
1142
1143     ret->move_count++;
1144     ret->last_move_row = col ? -1 : c;
1145     ret->last_move_col = col ? c : -1;
1146     ret->last_move_dir = d;
1147
1148     /*
1149      * See if the game has been completed.
1150      */
1151     if (!ret->completed) {
1152         unsigned char *active = compute_active(ret, -1, -1);
1153         int x1, y1;
1154         int complete = TRUE;
1155
1156         for (x1 = 0; x1 < ret->width; x1++)
1157             for (y1 = 0; y1 < ret->height; y1++)
1158                 if (!index(ret, active, x1, y1)) {
1159                     complete = FALSE;
1160                     goto break_label;  /* break out of two loops at once */
1161                 }
1162         break_label:
1163
1164         sfree(active);
1165
1166         if (complete)
1167             ret->completed = ret->move_count;
1168     }
1169
1170     return ret;
1171 }
1172
1173 /* ----------------------------------------------------------------------
1174  * Routines for drawing the game position on the screen.
1175  */
1176
1177 static game_drawstate *game_new_drawstate(game_state *state)
1178 {
1179     game_drawstate *ds = snew(game_drawstate);
1180
1181     ds->started = FALSE;
1182     ds->width = state->width;
1183     ds->height = state->height;
1184     ds->visible = snewn(state->width * state->height, unsigned char);
1185     ds->tilesize = 0;                  /* not decided yet */
1186     memset(ds->visible, 0xFF, state->width * state->height);
1187
1188     return ds;
1189 }
1190
1191 static void game_free_drawstate(game_drawstate *ds)
1192 {
1193     sfree(ds->visible);
1194     sfree(ds);
1195 }
1196
1197 static void game_size(game_params *params, game_drawstate *ds, int *x, int *y,
1198                       int expand)
1199 {
1200     int tsx, tsy, ts;
1201     /*
1202      * Each window dimension equals the tile size times two more
1203      * than the grid dimension (the border containing the arrows is
1204      * the same width as the tiles), plus TILE_BORDER, plus twice
1205      * WINDOW_OFFSET.
1206      */
1207     tsx = (*x - 2*WINDOW_OFFSET - TILE_BORDER) / (params->width + 2);
1208     tsy = (*y - 2*WINDOW_OFFSET - TILE_BORDER) / (params->height + 2);
1209     ts = min(tsx, tsy);
1210
1211     if (expand)
1212         ds->tilesize = ts;
1213     else
1214         ds->tilesize = min(ts, PREFERRED_TILE_SIZE);
1215
1216     *x = BORDER * 2 + WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
1217     *y = BORDER * 2 + WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
1218 }
1219
1220 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1221 {
1222     float *ret;
1223
1224     ret = snewn(NCOLOURS * 3, float);
1225     *ncolours = NCOLOURS;
1226
1227     /*
1228      * Basic background colour is whatever the front end thinks is
1229      * a sensible default.
1230      */
1231     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1232
1233     /*
1234      * Wires are black.
1235      */
1236     ret[COL_WIRE * 3 + 0] = 0.0F;
1237     ret[COL_WIRE * 3 + 1] = 0.0F;
1238     ret[COL_WIRE * 3 + 2] = 0.0F;
1239
1240     /*
1241      * Powered wires and powered endpoints are cyan.
1242      */
1243     ret[COL_POWERED * 3 + 0] = 0.0F;
1244     ret[COL_POWERED * 3 + 1] = 1.0F;
1245     ret[COL_POWERED * 3 + 2] = 1.0F;
1246
1247     /*
1248      * Barriers are red.
1249      */
1250     ret[COL_BARRIER * 3 + 0] = 1.0F;
1251     ret[COL_BARRIER * 3 + 1] = 0.0F;
1252     ret[COL_BARRIER * 3 + 2] = 0.0F;
1253
1254     /*
1255      * Unpowered endpoints are blue.
1256      */
1257     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
1258     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
1259     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
1260
1261     /*
1262      * Tile borders are a darker grey than the background.
1263      */
1264     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1265     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1266     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1267
1268     /*
1269      * Flashing tiles are a grey in between those two.
1270      */
1271     ret[COL_FLASHING * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
1272     ret[COL_FLASHING * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
1273     ret[COL_FLASHING * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
1274
1275     ret[COL_LOWLIGHT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
1276     ret[COL_LOWLIGHT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.8F;
1277     ret[COL_LOWLIGHT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.8F;
1278     ret[COL_TEXT * 3 + 0] = 0.0;
1279     ret[COL_TEXT * 3 + 1] = 0.0;
1280     ret[COL_TEXT * 3 + 2] = 0.0;
1281
1282     return ret;
1283 }
1284
1285 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
1286                             int colour)
1287 {
1288     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
1289     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
1290     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
1291     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
1292     draw_line(fe, x1, y1, x2, y2, colour);
1293 }
1294
1295 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
1296                              int colour)
1297 {
1298     int mx = (x1 < x2 ? x1 : x2);
1299     int my = (y1 < y2 ? y1 : y2);
1300     int dx = (x2 + x1 - 2*mx + 1);
1301     int dy = (y2 + y1 - 2*my + 1);
1302
1303     draw_rect(fe, mx, my, dx, dy, colour);
1304 }
1305
1306 static void draw_barrier_corner(frontend *fe, game_drawstate *ds,
1307                                 int x, int y, int dir, int phase)
1308 {
1309     int bx = BORDER + WINDOW_OFFSET + TILE_SIZE * x;
1310     int by = BORDER + WINDOW_OFFSET + TILE_SIZE * y;
1311     int x1, y1, dx, dy, dir2;
1312
1313     dir >>= 4;
1314
1315     dir2 = A(dir);
1316     dx = X(dir) + X(dir2);
1317     dy = Y(dir) + Y(dir2);
1318     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
1319     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
1320
1321     if (phase == 0) {
1322         draw_rect_coords(fe, bx+x1, by+y1,
1323                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
1324                          COL_WIRE);
1325         draw_rect_coords(fe, bx+x1, by+y1,
1326                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
1327                          COL_WIRE);
1328     } else {
1329         draw_rect_coords(fe, bx+x1, by+y1,
1330                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
1331                          COL_BARRIER);
1332     }
1333 }
1334
1335 static void draw_barrier(frontend *fe, game_drawstate *ds,
1336                          int x, int y, int dir, int phase)
1337 {
1338     int bx = BORDER + WINDOW_OFFSET + TILE_SIZE * x;
1339     int by = BORDER + WINDOW_OFFSET + TILE_SIZE * y;
1340     int x1, y1, w, h;
1341
1342     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
1343     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
1344     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
1345     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
1346
1347     if (phase == 0) {
1348         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
1349     } else {
1350         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
1351     }
1352 }
1353
1354 static void draw_tile(frontend *fe, game_drawstate *ds, game_state *state,
1355                       int x, int y, int tile, float xshift, float yshift)
1356 {
1357     int bx = BORDER + WINDOW_OFFSET + TILE_SIZE * x + (xshift * TILE_SIZE);
1358     int by = BORDER + WINDOW_OFFSET + TILE_SIZE * y + (yshift * TILE_SIZE);
1359     float cx, cy, ex, ey;
1360     int dir, col;
1361
1362     /*
1363      * When we draw a single tile, we must draw everything up to
1364      * and including the borders around the tile. This means that
1365      * if the neighbouring tiles have connections to those borders,
1366      * we must draw those connections on the borders themselves.
1367      *
1368      * This would be terribly fiddly if we ever had to draw a tile
1369      * while its neighbour was in mid-rotate, because we'd have to
1370      * arrange to _know_ that the neighbour was being rotated and
1371      * hence had an anomalous effect on the redraw of this tile.
1372      * Fortunately, the drawing algorithm avoids ever calling us in
1373      * this circumstance: we're either drawing lots of straight
1374      * tiles at game start or after a move is complete, or we're
1375      * repeatedly drawing only the rotating tile. So no problem.
1376      */
1377
1378     /*
1379      * So. First blank the tile out completely: draw a big
1380      * rectangle in border colour, and a smaller rectangle in
1381      * background colour to fill it in.
1382      */
1383     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
1384               COL_BORDER);
1385     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
1386               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
1387               tile & FLASHING ? COL_FLASHING : COL_BACKGROUND);
1388
1389     /*
1390      * Draw the wires.
1391      */
1392     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
1393     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
1394     for (dir = 1; dir < 0x10; dir <<= 1) {
1395         if (tile & dir) {
1396             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1397             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1398             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
1399                             bx+(int)(cx+ex), by+(int)(cy+ey),
1400                             COL_WIRE);
1401         }
1402     }
1403     for (dir = 1; dir < 0x10; dir <<= 1) {
1404         if (tile & dir) {
1405             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1406             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1407             draw_line(fe, bx+(int)cx, by+(int)cy,
1408                       bx+(int)(cx+ex), by+(int)(cy+ey), col);
1409         }
1410     }
1411
1412     /*
1413      * Draw the box in the middle. We do this in blue if the tile
1414      * is an unpowered endpoint, in cyan if the tile is a powered
1415      * endpoint, in black if the tile is the centrepiece, and
1416      * otherwise not at all.
1417      */
1418     col = -1;
1419     if (x == state->cx && y == state->cy)
1420         col = COL_WIRE;
1421     else if (COUNT(tile) == 1) {
1422         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
1423     }
1424     if (col >= 0) {
1425         int i, points[8];
1426
1427         points[0] = +1; points[1] = +1;
1428         points[2] = +1; points[3] = -1;
1429         points[4] = -1; points[5] = -1;
1430         points[6] = -1; points[7] = +1;
1431
1432         for (i = 0; i < 8; i += 2) {
1433             ex = (TILE_SIZE * 0.24F) * points[i];
1434             ey = (TILE_SIZE * 0.24F) * points[i+1];
1435             points[i] = bx+(int)(cx+ex);
1436             points[i+1] = by+(int)(cy+ey);
1437         }
1438
1439         draw_polygon(fe, points, 4, col, COL_WIRE);
1440     }
1441
1442     /*
1443      * Draw the points on the border if other tiles are connected
1444      * to us.
1445      */
1446     for (dir = 1; dir < 0x10; dir <<= 1) {
1447         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
1448
1449         dx = X(dir);
1450         dy = Y(dir);
1451
1452         ox = x + dx;
1453         oy = y + dy;
1454
1455         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
1456             continue;
1457
1458         if (!(tile(state, ox, oy) & F(dir)))
1459             continue;
1460
1461         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
1462         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
1463         lx = dx * (TILE_BORDER-1);
1464         ly = dy * (TILE_BORDER-1);
1465         vx = (dy ? 1 : 0);
1466         vy = (dx ? 1 : 0);
1467
1468         if (xshift == 0.0 && yshift == 0.0 && (tile & dir)) {
1469             /*
1470              * If we are fully connected to the other tile, we must
1471              * draw right across the tile border. (We can use our
1472              * own ACTIVE state to determine what colour to do this
1473              * in: if we are fully connected to the other tile then
1474              * the two ACTIVE states will be the same.)
1475              */
1476             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
1477             draw_rect_coords(fe, px, py, px+lx, py+ly,
1478                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
1479         } else {
1480             /*
1481              * The other tile extends into our border, but isn't
1482              * actually connected to us. Just draw a single black
1483              * dot.
1484              */
1485             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
1486         }
1487     }
1488
1489     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
1490 }
1491
1492 static void draw_tile_barriers(frontend *fe, game_drawstate *ds,
1493                                game_state *state, int x, int y)
1494 {
1495     int phase;
1496     int dir;
1497     int bx = BORDER + WINDOW_OFFSET + TILE_SIZE * x;
1498     int by = BORDER + WINDOW_OFFSET + TILE_SIZE * y;
1499     /*
1500      * Draw barrier corners, and then barriers.
1501      */
1502     for (phase = 0; phase < 2; phase++) {
1503         for (dir = 1; dir < 0x10; dir <<= 1)
1504             if (barrier(state, x, y) & (dir << 4))
1505                 draw_barrier_corner(fe, ds, x, y, dir << 4, phase);
1506         for (dir = 1; dir < 0x10; dir <<= 1)
1507             if (barrier(state, x, y) & dir)
1508                 draw_barrier(fe, ds, x, y, dir, phase);
1509     }
1510
1511     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
1512 }
1513
1514 static void draw_arrow(frontend *fe, game_drawstate *ds,
1515                        int x, int y, int xdx, int xdy)
1516 {
1517     int coords[14];
1518     int ydy = -xdx, ydx = xdy;
1519
1520     x = x * TILE_SIZE + BORDER + WINDOW_OFFSET;
1521     y = y * TILE_SIZE + BORDER + WINDOW_OFFSET;
1522
1523 #define POINT(n, xx, yy) ( \
1524     coords[2*(n)+0] = x + (xx)*xdx + (yy)*ydx, \
1525     coords[2*(n)+1] = y + (xx)*xdy + (yy)*ydy)
1526
1527     POINT(0, TILE_SIZE / 2, 3 * TILE_SIZE / 4);   /* top of arrow */
1528     POINT(1, 3 * TILE_SIZE / 4, TILE_SIZE / 2);   /* right corner */
1529     POINT(2, 5 * TILE_SIZE / 8, TILE_SIZE / 2);   /* right concave */
1530     POINT(3, 5 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom right */
1531     POINT(4, 3 * TILE_SIZE / 8, TILE_SIZE / 4);   /* bottom left */
1532     POINT(5, 3 * TILE_SIZE / 8, TILE_SIZE / 2);   /* left concave */
1533     POINT(6,     TILE_SIZE / 4, TILE_SIZE / 2);   /* left corner */
1534
1535     draw_polygon(fe, coords, 7, COL_LOWLIGHT, COL_TEXT);
1536 }
1537
1538 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1539                  game_state *state, int dir, game_ui *ui, float t, float ft)
1540 {
1541     int x, y, tx, ty, frame;
1542     unsigned char *active;
1543     float xshift = 0.0;
1544     float yshift = 0.0;
1545
1546     /*
1547      * Clear the screen and draw the exterior barrier lines if this
1548      * is our first call.
1549      */
1550     if (!ds->started) {
1551         int phase;
1552
1553         ds->started = TRUE;
1554
1555         draw_rect(fe, 0, 0, 
1556                   BORDER * 2 + WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
1557                   BORDER * 2 + WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
1558                   COL_BACKGROUND);
1559         draw_update(fe, 0, 0, 
1560                     BORDER * 2 + WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
1561                     BORDER * 2 + WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
1562
1563         for (phase = 0; phase < 2; phase++) {
1564
1565             for (x = 0; x < ds->width; x++) {
1566                 if (barrier(state, x, 0) & UL)
1567                     draw_barrier_corner(fe, ds, x, -1, LD, phase);
1568                 if (barrier(state, x, 0) & RU)
1569                     draw_barrier_corner(fe, ds, x, -1, DR, phase);
1570                 if (barrier(state, x, 0) & U)
1571                     draw_barrier(fe, ds, x, -1, D, phase);
1572                 if (barrier(state, x, ds->height-1) & DR)
1573                     draw_barrier_corner(fe, ds, x, ds->height, RU, phase);
1574                 if (barrier(state, x, ds->height-1) & LD)
1575                     draw_barrier_corner(fe, ds, x, ds->height, UL, phase);
1576                 if (barrier(state, x, ds->height-1) & D)
1577                     draw_barrier(fe, ds, x, ds->height, U, phase);
1578             }
1579
1580             for (y = 0; y < ds->height; y++) {
1581                 if (barrier(state, 0, y) & UL)
1582                     draw_barrier_corner(fe, ds, -1, y, RU, phase);
1583                 if (barrier(state, 0, y) & LD)
1584                     draw_barrier_corner(fe, ds, -1, y, DR, phase);
1585                 if (barrier(state, 0, y) & L)
1586                     draw_barrier(fe, ds, -1, y, R, phase);
1587                 if (barrier(state, ds->width-1, y) & RU)
1588                     draw_barrier_corner(fe, ds, ds->width, y, UL, phase);
1589                 if (barrier(state, ds->width-1, y) & DR)
1590                     draw_barrier_corner(fe, ds, ds->width, y, LD, phase);
1591                 if (barrier(state, ds->width-1, y) & R)
1592                     draw_barrier(fe, ds, ds->width, y, L, phase);
1593             }
1594         }
1595
1596         /*
1597          * Arrows for making moves.
1598          */
1599         for (x = 0; x < ds->width; x++) {
1600             if (x == state->cx) continue;
1601             draw_arrow(fe, ds, x, 0, +1, 0);
1602             draw_arrow(fe, ds, x+1, ds->height, -1, 0);
1603         }
1604         for (y = 0; y < ds->height; y++) {
1605             if (y == state->cy) continue;
1606             draw_arrow(fe, ds, ds->width, y, 0, +1);
1607             draw_arrow(fe, ds, 0, y+1, 0, -1);
1608         }
1609     }
1610
1611     /* Check if this is an undo.  If so, we will need to run any animation
1612      * backwards.
1613      */
1614     if (oldstate && oldstate->move_count > state->move_count) {
1615         game_state * tmpstate = state;
1616         state = oldstate;
1617         oldstate = tmpstate;
1618         t = ANIM_TIME - t;
1619     }
1620
1621     tx = ty = -1;
1622     if (oldstate && (t < ANIM_TIME)) {
1623         /*
1624          * We're animating a slide, of row/column number
1625          * state->last_move_pos, in direction
1626          * state->last_move_dir
1627          */
1628         xshift = state->last_move_row == -1 ? 0.0 :
1629                 (1 - t / ANIM_TIME) * state->last_move_dir;
1630         yshift = state->last_move_col == -1 ? 0.0 :
1631                 (1 - t / ANIM_TIME) * state->last_move_dir;
1632     }
1633     
1634     frame = -1;
1635     if (ft > 0) {
1636         /*
1637          * We're animating a completion flash. Find which frame
1638          * we're at.
1639          */
1640         frame = (int)(ft / FLASH_FRAME);
1641     }
1642
1643     /*
1644      * Draw any tile which differs from the way it was last drawn.
1645      */
1646     if (xshift != 0.0 || yshift != 0.0) {
1647         active = compute_active(state,
1648                                 state->last_move_row, state->last_move_col);
1649     } else {
1650         active = compute_active(state, -1, -1);
1651     }
1652
1653     clip(fe,
1654          BORDER + WINDOW_OFFSET, BORDER + WINDOW_OFFSET,
1655          TILE_SIZE * state->width + TILE_BORDER,
1656          TILE_SIZE * state->height + TILE_BORDER);
1657     
1658     for (x = 0; x < ds->width; x++)
1659         for (y = 0; y < ds->height; y++) {
1660             unsigned char c = tile(state, x, y) | index(state, active, x, y);
1661
1662             /*
1663              * In a completion flash, we adjust the FLASHING bit
1664              * depending on our distance from the centre point and
1665              * the frame number.
1666              */
1667             if (frame >= 0) {
1668                 int xdist, ydist, dist;
1669                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
1670                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
1671                 dist = (xdist > ydist ? xdist : ydist);
1672
1673                 if (frame >= dist && frame < dist+4) {
1674                     int flash = (frame - dist) & 1;
1675                     flash = flash ? FLASHING : 0;
1676                     c = (c &~ FLASHING) | flash;
1677                 }
1678             }
1679
1680             if (index(state, ds->visible, x, y) != c ||
1681                 index(state, ds->visible, x, y) == 0xFF ||
1682                 (x == state->last_move_col || y == state->last_move_row))
1683             {
1684                 float xs = (y == state->last_move_row ? xshift : 0.0);
1685                 float ys = (x == state->last_move_col ? yshift : 0.0);
1686
1687                 draw_tile(fe, ds, state, x, y, c, xs, ys);
1688                 if (xs < 0 && x == 0)
1689                     draw_tile(fe, ds, state, state->width, y, c, xs, ys);
1690                 else if (xs > 0 && x == state->width - 1)
1691                     draw_tile(fe, ds, state, -1, y, c, xs, ys);
1692                 else if (ys < 0 && y == 0)
1693                     draw_tile(fe, ds, state, x, state->height, c, xs, ys);
1694                 else if (ys > 0 && y == state->height - 1)
1695                     draw_tile(fe, ds, state, x, -1, c, xs, ys);
1696
1697                 if (x == state->last_move_col || y == state->last_move_row)
1698                     index(state, ds->visible, x, y) = 0xFF;
1699                 else
1700                     index(state, ds->visible, x, y) = c;
1701             }
1702         }
1703
1704     for (x = 0; x < ds->width; x++)
1705         for (y = 0; y < ds->height; y++)
1706             draw_tile_barriers(fe, ds, state, x, y);
1707
1708     unclip(fe);
1709
1710     /*
1711      * Update the status bar.
1712      */
1713     {
1714         char statusbuf[256];
1715         int i, n, a;
1716
1717         n = state->width * state->height;
1718         for (i = a = 0; i < n; i++)
1719             if (active[i])
1720                 a++;
1721
1722         if (state->used_solve)
1723             sprintf(statusbuf, "Moves since auto-solve: %d",
1724                     state->move_count - state->completed);
1725         else
1726             sprintf(statusbuf, "%sMoves: %d",
1727                     (state->completed ? "COMPLETED! " : ""),
1728                     (state->completed ? state->completed : state->move_count));
1729
1730         if (state->movetarget)
1731             sprintf(statusbuf + strlen(statusbuf), " (target %d)",
1732                     state->movetarget);
1733
1734         sprintf(statusbuf + strlen(statusbuf), " Active: %d/%d", a, n);
1735
1736         status_bar(fe, statusbuf);
1737     }
1738
1739     sfree(active);
1740 }
1741
1742 static float game_anim_length(game_state *oldstate,
1743                               game_state *newstate, int dir, game_ui *ui)
1744 {
1745     /*
1746      * Don't animate an auto-solve move.
1747      */
1748     if ((dir > 0 && newstate->just_used_solve) ||
1749         (dir < 0 && oldstate->just_used_solve))
1750         return 0.0F;
1751
1752     return ANIM_TIME;
1753 }
1754
1755 static float game_flash_length(game_state *oldstate,
1756                                game_state *newstate, int dir, game_ui *ui)
1757 {
1758     /*
1759      * If the game has just been completed, we display a completion
1760      * flash.
1761      */
1762     if (!oldstate->completed && newstate->completed &&
1763         !oldstate->used_solve && !newstate->used_solve) {
1764         int size;
1765         size = 0;
1766         if (size < newstate->cx+1)
1767             size = newstate->cx+1;
1768         if (size < newstate->cy+1)
1769             size = newstate->cy+1;
1770         if (size < newstate->width - newstate->cx)
1771             size = newstate->width - newstate->cx;
1772         if (size < newstate->height - newstate->cy)
1773             size = newstate->height - newstate->cy;
1774         return FLASH_FRAME * (size+4);
1775     }
1776
1777     return 0.0F;
1778 }
1779
1780 static int game_wants_statusbar(void)
1781 {
1782     return TRUE;
1783 }
1784
1785 static int game_timing_state(game_state *state)
1786 {
1787     return FALSE;
1788 }
1789
1790 #ifdef COMBINED
1791 #define thegame netslide
1792 #endif
1793
1794 const struct game thegame = {
1795     "Netslide", "games.netslide",
1796     default_params,
1797     game_fetch_preset,
1798     decode_params,
1799     encode_params,
1800     free_params,
1801     dup_params,
1802     TRUE, game_configure, custom_params,
1803     validate_params,
1804     new_game_desc,
1805     validate_desc,
1806     new_game,
1807     dup_game,
1808     free_game,
1809     TRUE, solve_game,
1810     FALSE, game_text_format,
1811     new_ui,
1812     free_ui,
1813     encode_ui,
1814     decode_ui,
1815     game_changed_state,
1816     interpret_move,
1817     execute_move,
1818     game_size,
1819     game_colours,
1820     game_new_drawstate,
1821     game_free_drawstate,
1822     game_redraw,
1823     game_anim_length,
1824     game_flash_length,
1825     game_wants_statusbar,
1826     FALSE, game_timing_state,
1827     0,                                 /* mouse_priorities */
1828 };