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