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