chiark / gitweb /
Slight solver speedup by tracking more carefully which block merges
[sgt-puzzles.git] / unfinished / slide.c
1 /*
2  * slide.c: Implementation of the block-sliding puzzle `Klotski'.
3  */
4
5 /*
6  * TODO:
7  * 
8  *  - Solve function:
9  *     * try to generate a solution when Solve is pressed
10  *        + from the start, or from here? From here, I fear.
11  *        + hence, not much point saving the solution in an aux
12  *          string
13  *     * Inertia-like method for telling the user the solution
14  *     * standalone solver which draws diagrams
15  * 
16  *  - The dragging semantics are still subtly wrong in complex
17  *    cases.
18  * 
19  *  - Improve the generator.
20  *     * actually, we seem to be mostly sensible already now. I
21  *       want more choice over the type of main block and location
22  *       of the exit/target, and I think I probably ought to give
23  *       up on compactness and just bite the bullet and have the
24  *       target area right outside the main wall, but mostly I
25  *       think it's OK.
26  *     * but adjust the presets, because 8x6 is _slow_ to
27  *       generate.
28  *     * also, introduce a difficulty scheme, in the form of
29  *       limiting the minimum move count. This is obviously
30  *       sensible, because it also speeds up generation since the
31  *       solver can bomb out once it hits that ceiling!
32  *        + I was going to say I'd need to work out a minimum move
33  *          count for each grid size, but actually I think not: if
34  *          you ask for too few moves, it just has to remove still
35  *          more singletons, until at move count 1 you end up with
36  *          nothing in your way at all and it SERVES YOU RIGHT!
37  * 
38  *  - Improve the graphics.
39  *     * All the colours are a bit wishy-washy. _Some_ dark
40  *       colours would surely not be excessive? Probably darken
41  *       the tiles, the walls and the main block, and leave the
42  *       target marker pale.
43  *     * The cattle grid effect is still disgusting. Think of
44  *       something completely different.
45  */
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <assert.h>
51 #include <ctype.h>
52 #include <math.h>
53
54 #include "puzzles.h"
55 #include "tree234.h"
56
57 /*
58  * The implementation of this game revolves around the insight
59  * which makes an exhaustive-search solver feasible: although
60  * there are many blocks which can be rearranged in many ways, any
61  * two blocks of the same shape are _indistinguishable_ and hence
62  * the number of _distinct_ board layouts is generally much
63  * smaller. So we adopt a representation for board layouts which
64  * is inherently canonical, i.e. there are no two distinct
65  * representations which encode indistinguishable layouts.
66  *
67  * The way we do this is to encode each square of the board, in
68  * the normal left-to-right top-to-bottom order, as being one of
69  * the following things:
70  *  - the first square (in the given order) of a block (`anchor')
71  *  - special case of the above: the anchor for the _main_ block
72  *    (i.e. the one which the aim of the game is to get to the
73  *    target position)
74  *  - a subsequent square of a block whose previous square was N
75  *    squares ago
76  *  - an impassable wall
77  * 
78  * (We also separately store data about which board positions are
79  * forcefields only passable by the main block. We can't encode
80  * that in the main board data, because then the main block would
81  * destroy forcefields as it went over them.)
82  *
83  * Hence, for example, a 2x2 square block would be encoded as
84  * ANCHOR, followed by DIST(1), and w-2 squares later on there
85  * would be DIST(w-1) followed by DIST(1). So if you start at the
86  * last of those squares, the DIST numbers give you a linked list
87  * pointing back through all the other squares in the same block.
88  *
89  * So the solver simply does a bfs over all reachable positions,
90  * encoding them in this format and storing them in a tree234 to
91  * ensure it doesn't ever revisit an already-analysed position.
92  */
93
94 enum {
95     /*
96      * The colours are arranged here so that every base colour is
97      * directly followed by its highlight colour and then its
98      * lowlight colour. Do not break this, or draw_tile() will get
99      * confused.
100      */
101     COL_BACKGROUND,
102     COL_HIGHLIGHT,
103     COL_LOWLIGHT,
104     COL_DRAGGING,
105     COL_DRAGGING_HIGHLIGHT,
106     COL_DRAGGING_LOWLIGHT,
107     COL_MAIN,
108     COL_MAIN_HIGHLIGHT,
109     COL_MAIN_LOWLIGHT,
110     COL_MAIN_DRAGGING,
111     COL_MAIN_DRAGGING_HIGHLIGHT,
112     COL_MAIN_DRAGGING_LOWLIGHT,
113     COL_TARGET,
114     COL_TARGET_HIGHLIGHT,
115     COL_TARGET_LOWLIGHT,
116     NCOLOURS
117 };
118
119 /*
120  * Board layout is a simple array of bytes. Each byte holds:
121  */
122 #define ANCHOR      255                /* top-left-most square of some piece */
123 #define MAINANCHOR  254                /* anchor of _main_ piece */
124 #define EMPTY       253                /* empty square */
125 #define WALL        252                /* immovable wall */
126 #define MAXDIST     251
127 /* all other values indicate distance back to previous square of same block */
128 #define ISDIST(x) ( (unsigned char)((x)-1) <= MAXDIST-1 )
129 #define DIST(x) (x)
130 #define ISANCHOR(x) ( (x)==ANCHOR || (x)==MAINANCHOR )
131 #define ISBLOCK(x) ( ISANCHOR(x) || ISDIST(x) )
132
133 /*
134  * MAXDIST is the largest DIST value we can encode. This must
135  * therefore also be the maximum puzzle width in theory (although
136  * solver running time will dictate a much smaller limit in
137  * practice).
138  */
139 #define MAXWID MAXDIST
140
141 struct game_params {
142     int w, h;
143 };
144
145 struct game_immutable_state {
146     int refcount;
147     unsigned char *forcefield;
148 };
149
150 struct game_state {
151     int w, h;
152     unsigned char *board;
153     int tx, ty;                        /* target coords for MAINANCHOR */
154     int minmoves;                      /* for display only */
155     int lastmoved, lastmoved_pos;      /* for move counting */
156     int movecount;
157     int completed;
158     struct game_immutable_state *imm;
159 };
160
161 static game_params *default_params(void)
162 {
163     game_params *ret = snew(game_params);
164
165     ret->w = 8;
166     ret->h = 6;
167
168     return ret;
169 }
170
171 static const struct game_params slide_presets[] = {
172     {6, 5},
173     {7, 5},
174     {7, 6},
175     {8, 6},
176 };
177
178 static int game_fetch_preset(int i, char **name, game_params **params)
179 {
180     game_params *ret;
181     char str[80];
182
183     if (i < 0 || i >= lenof(slide_presets))
184         return FALSE;
185
186     ret = snew(game_params);
187     *ret = slide_presets[i];
188
189     sprintf(str, "%dx%d", ret->w, ret->h);
190
191     *name = dupstr(str);
192     *params = ret;
193     return TRUE;
194 }
195
196 static void free_params(game_params *params)
197 {
198     sfree(params);
199 }
200
201 static game_params *dup_params(game_params *params)
202 {
203     game_params *ret = snew(game_params);
204     *ret = *params;                    /* structure copy */
205     return ret;
206 }
207
208 static void decode_params(game_params *params, char const *string)
209 {
210     params->w = params->h = atoi(string);
211     while (*string && isdigit((unsigned char)*string)) string++;
212     if (*string == 'x') {
213         string++;
214         params->h = atoi(string);
215     }
216 }
217
218 static char *encode_params(game_params *params, int full)
219 {
220     char data[256];
221
222     sprintf(data, "%dx%d", params->w, params->h);
223
224     return dupstr(data);
225 }
226
227 static config_item *game_configure(game_params *params)
228 {
229     config_item *ret;
230     char buf[80];
231
232     ret = snewn(3, config_item);
233
234     ret[0].name = "Width";
235     ret[0].type = C_STRING;
236     sprintf(buf, "%d", params->w);
237     ret[0].sval = dupstr(buf);
238     ret[0].ival = 0;
239
240     ret[1].name = "Height";
241     ret[1].type = C_STRING;
242     sprintf(buf, "%d", params->h);
243     ret[1].sval = dupstr(buf);
244     ret[1].ival = 0;
245
246     ret[2].name = NULL;
247     ret[2].type = C_END;
248     ret[2].sval = NULL;
249     ret[2].ival = 0;
250
251     return ret;
252 }
253
254 static game_params *custom_params(config_item *cfg)
255 {
256     game_params *ret = snew(game_params);
257
258     ret->w = atoi(cfg[0].sval);
259     ret->h = atoi(cfg[1].sval);
260
261     return ret;
262 }
263
264 static char *validate_params(game_params *params, int full)
265 {
266     if (params->w > MAXWID)
267         return "Width must be at most " STR(MAXWID);
268
269     if (params->w < 5)
270         return "Width must be at least 5";
271     if (params->h < 4)
272         return "Height must be at least 4";
273
274     return NULL;
275 }
276
277 static char *board_text_format(int w, int h, unsigned char *data,
278                                unsigned char *forcefield)
279 {
280     int wh = w*h;
281     int *dsf = snew_dsf(wh);
282     int i, x, y;
283     int retpos, retlen = (w*2+2)*(h*2+1)+1;
284     char *ret = snewn(retlen, char);
285
286     for (i = 0; i < wh; i++)
287         if (ISDIST(data[i]))
288             dsf_merge(dsf, i - data[i], i);
289     retpos = 0;
290     for (y = 0; y < 2*h+1; y++) {
291         for (x = 0; x < 2*w+1; x++) {
292             int v;
293             int i = (y/2)*w+(x/2);
294
295 #define dtype(i) (ISBLOCK(data[i]) ? \
296                   dsf_canonify(dsf, i) : data[i])
297 #define dchar(t) ((t)==EMPTY ? ' ' : (t)==WALL ? '#' : \
298                   data[t] == MAINANCHOR ? '*' : '%')
299
300             if (y % 2 && x % 2) {
301                 int j = dtype(i);
302                 v = dchar(j);
303             } else if (y % 2 && !(x % 2)) {
304                 int j1 = (x > 0 ? dtype(i-1) : -1);
305                 int j2 = (x < 2*w ? dtype(i) : -1);
306                 if (j1 != j2)
307                     v = '|';
308                 else
309                     v = dchar(j1);
310             } else if (!(y % 2) && (x % 2)) {
311                 int j1 = (y > 0 ? dtype(i-w) : -1);
312                 int j2 = (y < 2*h ? dtype(i) : -1);
313                 if (j1 != j2)
314                     v = '-';
315                 else
316                     v = dchar(j1);
317             } else {
318                 int j1 = (x > 0 && y > 0 ? dtype(i-w-1) : -1);
319                 int j2 = (x > 0 && y < 2*h ? dtype(i-1) : -1);
320                 int j3 = (x < 2*w && y > 0 ? dtype(i-w) : -1);
321                 int j4 = (x < 2*w && y < 2*h ? dtype(i) : -1);
322                 if (j1 == j2 && j2 == j3 && j3 == j4)
323                     v = dchar(j1);
324                 else if (j1 == j2 && j3 == j4)
325                     v = '|';
326                 else if (j1 == j3 && j2 == j4)
327                     v = '-';
328                 else
329                     v = '+';
330             }
331
332             assert(retpos < retlen);
333             ret[retpos++] = v;
334         }
335         assert(retpos < retlen);
336         ret[retpos++] = '\n';
337     }
338     assert(retpos < retlen);
339     ret[retpos++] = '\0';
340     assert(retpos == retlen);
341
342     return ret;
343 }
344
345 /* ----------------------------------------------------------------------
346  * Solver.
347  */
348
349 /*
350  * During solver execution, the set of visited board positions is
351  * stored as a tree234 of the following structures. `w', `h' and
352  * `data' are obvious in meaning; `dist' represents the minimum
353  * distance to reach this position from the starting point.
354  * 
355  * `prev' links each board to the board position from which it was
356  * most efficiently derived.
357  */
358 struct board {
359     int w, h;
360     int dist;
361     struct board *prev;
362     unsigned char *data;
363 };
364
365 static int boardcmp(void *av, void *bv)
366 {
367     struct board *a = (struct board *)av;
368     struct board *b = (struct board *)bv;
369     return memcmp(a->data, b->data, a->w * a->h);
370 }
371
372 static struct board *newboard(int w, int h, unsigned char *data)
373 {
374     struct board *b = malloc(sizeof(struct board) + w*h);
375     b->data = (unsigned char *)b + sizeof(struct board);
376     memcpy(b->data, data, w*h);
377     b->w = w;
378     b->h = h;
379     b->dist = -1;
380     b->prev = NULL;
381     return b;
382 }
383
384 /*
385  * The actual solver. Given a board, attempt to find the minimum
386  * length of move sequence which moves MAINANCHOR to (tx,ty), or
387  * -1 if no solution exists. Returns that minimum length, and
388  * (FIXME) optionally also writes out the actual moves into an
389  * as-yet-unprovided parameter.
390  */
391 static int solve_board(int w, int h, unsigned char *board,
392                        unsigned char *forcefield, int tx, int ty)
393 {
394     int wh = w*h;
395     struct board *b, *b2, *b3;
396     int *next, *anchors, *which;
397     int *movereached, *movequeue, mqhead, mqtail;
398     tree234 *sorted, *queue;
399     int i, j, dir;
400     int qlen, lastdist;
401     int ret;
402
403 #ifdef SOLVER_DIAGNOSTICS
404     {
405         char *t = board_text_format(w, h, board);
406         for (i = 0; i < h; i++) {
407             for (j = 0; j < w; j++) {
408                 int c = board[i*w+j];
409                 if (ISDIST(c))
410                     printf("D%-3d", c);
411                 else if (c == MAINANCHOR)
412                     printf("M   ");
413                 else if (c == ANCHOR)
414                     printf("A   ");
415                 else if (c == WALL)
416                     printf("W   ");
417                 else if (c == EMPTY)
418                     printf("E   ");
419             }
420             printf("\n");
421         }
422         
423         printf("Starting solver for:\n%s\n", t);
424         sfree(t);
425     }
426 #endif
427
428     sorted = newtree234(boardcmp);
429     queue = newtree234(NULL);
430
431     b = newboard(w, h, board);
432     b->dist = 0;
433     add234(sorted, b);
434     addpos234(queue, b, 0);
435     qlen = 1;
436
437     next = snewn(wh, int);
438     anchors = snewn(wh, int);
439     which = snewn(wh, int);
440     movereached = snewn(wh, int);
441     movequeue = snewn(wh, int);
442     lastdist = -1;
443
444     while ((b = delpos234(queue, 0)) != NULL) {
445         qlen--;
446         if (b->dist != lastdist) {
447 #ifdef SOLVER_DIAGNOSTICS
448             printf("dist %d (%d)\n", b->dist, count234(sorted));
449 #endif
450             lastdist = b->dist;
451         }
452         /*
453          * Find all the anchors and form a linked list of the
454          * squares within each block.
455          */
456         for (i = 0; i < wh; i++) {
457             next[i] = -1;
458             anchors[i] = FALSE;
459             which[i] = -1;
460             if (ISANCHOR(b->data[i])) {
461                 anchors[i] = TRUE;
462                 which[i] = i;
463             } else if (ISDIST(b->data[i])) {
464                 j = i - b->data[i];
465                 next[j] = i;
466                 which[i] = which[j];
467             }
468         }
469
470         /*
471          * For each anchor, do an array-based BFS to find all the
472          * places we can slide it to.
473          */
474         for (i = 0; i < wh; i++) {
475             if (!anchors[i])
476                 continue;
477
478             mqhead = mqtail = 0;
479             for (j = 0; j < wh; j++)
480                 movereached[j] = FALSE;
481             movequeue[mqtail++] = i;
482             while (mqhead < mqtail) {
483                 int pos = movequeue[mqhead++];
484
485                 /*
486                  * Try to move in each direction from here.
487                  */
488                 for (dir = 0; dir < 4; dir++) {
489                     int dx = (dir == 0 ? -1 : dir == 1 ? +1 : 0);
490                     int dy = (dir == 2 ? -1 : dir == 3 ? +1 : 0);
491                     int offset = dy*w + dx;
492                     int newpos = pos + offset;
493                     int d = newpos - i;
494
495                     /*
496                      * For each square involved in this block,
497                      * check to see if the square d spaces away
498                      * from it is either empty or part of the same
499                      * block.
500                      */
501                     for (j = i; j >= 0; j = next[j]) {
502                         int jy = (pos+j-i) / w + dy, jx = (pos+j-i) % w + dx;
503                         if (jy >= 0 && jy < h && jx >= 0 && jx < w &&
504                             ((b->data[j+d] == EMPTY || which[j+d] == i) &&
505                              (b->data[i] == MAINANCHOR || !forcefield[j+d])))
506                             /* ok */;
507                         else
508                             break;
509                     }
510                     if (j >= 0)
511                         continue;              /* this direction wasn't feasible */
512
513                     /*
514                      * If we've already tried moving this piece
515                      * here, leave it.
516                      */
517                     if (movereached[newpos])
518                         continue;
519                     movereached[newpos] = TRUE;
520                     movequeue[mqtail++] = newpos;
521
522                     /*
523                      * We have a viable move. Make it.
524                      */
525                     b2 = newboard(w, h, b->data);
526                     for (j = i; j >= 0; j = next[j])
527                         b2->data[j] = EMPTY;
528                     for (j = i; j >= 0; j = next[j])
529                         b2->data[j+d] = b->data[j];
530
531                     b3 = add234(sorted, b2);
532                     if (b3 != b2) {
533                         sfree(b2);             /* we already got one */
534                     } else {
535                         b2->dist = b->dist + 1;
536                         b2->prev = b;
537                         addpos234(queue, b2, qlen++);
538                         if (b2->data[ty*w+tx] == MAINANCHOR)
539                             goto done;     /* search completed! */
540                     }
541                 }
542             }
543         }
544     }
545     b2 = NULL;
546
547     done:
548
549     if (b2)
550         ret = b2->dist;
551     else
552         ret = -1;                      /* no solution */
553
554     freetree234(queue);
555
556     while ((b = delpos234(sorted, 0)) != NULL)
557         sfree(b);
558     freetree234(sorted);
559
560     sfree(next);
561     sfree(anchors);
562     sfree(movereached);
563     sfree(movequeue);
564     sfree(which);
565
566     return ret;
567 }
568
569 /* ----------------------------------------------------------------------
570  * Random board generation.
571  */
572
573 static void generate_board(int w, int h, int *rtx, int *rty, int *minmoves,
574                            random_state *rs, unsigned char **rboard,
575                            unsigned char **rforcefield)
576 {
577     int wh = w*h;
578     unsigned char *board, *board2, *forcefield;
579     unsigned char *tried_merge;
580     int *dsf;
581     int *list, nlist, pos;
582     int tx, ty;
583     int i, j;
584     int moves;
585
586     /*
587      * Set up a board and fill it with singletons, except for a
588      * border of walls.
589      */
590     board = snewn(wh, unsigned char);
591     forcefield = snewn(wh, unsigned char);
592     board2 = snewn(wh, unsigned char);
593     memset(board, ANCHOR, wh);
594     memset(forcefield, FALSE, wh);
595     for (i = 0; i < w; i++)
596         board[i] = board[i+w*(h-1)] = WALL;
597     for (i = 0; i < h; i++)
598         board[i*w] = board[i*w+(w-1)] = WALL;
599
600     tried_merge = snewn(wh * wh, unsigned char);
601     memset(tried_merge, 0, wh*wh);
602     dsf = snew_dsf(wh);
603
604     /*
605      * Invent a main piece at one extreme. (FIXME: vary the
606      * extreme, and the piece.)
607      */
608     board[w+1] = MAINANCHOR;
609     board[w+2] = DIST(1);
610     board[w*2+1] = DIST(w-1);
611     board[w*2+2] = DIST(1);
612
613     /*
614      * Invent a target position. (FIXME: vary this too.)
615      */
616     tx = w-2;
617     ty = h-3;
618     forcefield[ty*w+tx+1] = forcefield[(ty+1)*w+tx+1] = TRUE;
619     board[ty*w+tx+1] = board[(ty+1)*w+tx+1] = EMPTY;
620
621     /*
622      * Gradually remove singletons until the game becomes soluble.
623      */
624     for (j = w; j-- > 0 ;)
625         for (i = h; i-- > 0 ;)
626             if (board[i*w+j] == ANCHOR) {
627                 /*
628                  * See if the board is already soluble.
629                  */
630                 if ((moves = solve_board(w, h, board, forcefield,
631                                          tx, ty)) >= 0)
632                     goto soluble;
633
634                 /*
635                  * Otherwise, remove this piece.
636                  */
637                 board[i*w+j] = EMPTY;
638             }
639     assert(!"We shouldn't get here");
640     soluble:
641
642     /*
643      * Make a list of all the inter-block edges on the board.
644      */
645     list = snewn(wh*2, int);
646     nlist = 0;
647     for (i = 0; i+1 < w; i++)
648         for (j = 0; j < h; j++)
649             list[nlist++] = (j*w+i) * 2 + 0;   /* edge to the right of j*w+i */
650     for (j = 0; j+1 < h; j++)
651         for (i = 0; i < w; i++)
652             list[nlist++] = (j*w+i) * 2 + 1;   /* edge below j*w+i */
653
654     /*
655      * Now go through that list in random order, trying to merge
656      * the blocks on each side of each edge.
657      */
658     shuffle(list, nlist, sizeof(*list), rs);
659     while (nlist > 0) {
660         int x1, y1, p1, c1;
661         int x2, y2, p2, c2;
662
663         pos = list[--nlist];
664         y1 = y2 = pos / (w*2);
665         x1 = x2 = (pos / 2) % w;
666         if (pos % 2)
667             y2++;
668         else
669             x2++;
670         p1 = y1*w+x1;
671         p2 = y2*w+x2;
672
673         /*
674          * Immediately abandon the attempt if we've already tried
675          * to merge the same pair of blocks along a different
676          * edge.
677          */
678         c1 = dsf_canonify(dsf, p1);
679         c2 = dsf_canonify(dsf, p2);
680         if (tried_merge[c1 * wh + c2])
681 {printf("aha\n");
682             continue;
683 }
684
685         /*
686          * In order to be mergeable, these two squares must each
687          * either be, or belong to, a non-main anchor, and their
688          * anchors must also be distinct.
689          */
690         if (!ISBLOCK(board[p1]) || !ISBLOCK(board[p2]))
691             continue;
692         while (ISDIST(board[p1]))
693             p1 -= board[p1];
694         while (ISDIST(board[p2]))
695             p2 -= board[p2];
696         if (board[p1] == MAINANCHOR || board[p2] == MAINANCHOR || p1 == p2)
697             continue;
698
699         /*
700          * We can merge these blocks. Try it, and see if the
701          * puzzle remains soluble.
702          */
703         memcpy(board2, board, wh);
704         j = -1;
705         while (p1 < wh || p2 < wh) {
706             /*
707              * p1 and p2 are the squares at the head of each block
708              * list. Pick the smaller one and put it on the output
709              * block list.
710              */
711             i = min(p1, p2);
712             if (j < 0) {
713                 board[i] = ANCHOR;
714             } else {
715                 assert(i - j <= MAXDIST);
716                 board[i] = DIST(i - j);
717             }
718             j = i;
719
720             /*
721              * Now advance whichever list that came from.
722              */
723             if (i == p1) {
724                 do {
725                     p1++;
726                 } while (p1 < wh && board[p1] != DIST(p1-i));
727             } else {
728                 do {
729                     p2++;
730                 } while (p2 < wh && board[p2] != DIST(p2-i));
731             }
732         }
733         j = solve_board(w, h, board, forcefield, tx, ty);
734         if (j < 0) {
735             /*
736              * Didn't work. Revert the merge.
737              */
738             memcpy(board, board2, wh);
739             tried_merge[c1 * wh + c2] = tried_merge[c2 * wh + c1] = TRUE;
740         } else {
741             int c;
742
743             moves = j;
744
745             dsf_merge(dsf, c1, c2);
746             c = dsf_canonify(dsf, c1);
747             for (i = 0; i < wh; i++)
748                 tried_merge[c*wh+i] = (tried_merge[c1*wh+i] |
749                                        tried_merge[c2*wh+i]);
750             for (i = 0; i < wh; i++)
751                 tried_merge[i*wh+c] = (tried_merge[i*wh+c1] |
752                                        tried_merge[i*wh+c2]);
753         }
754     }
755
756     sfree(board2);
757
758     *rtx = tx;
759     *rty = ty;
760     *rboard = board;
761     *rforcefield = forcefield;
762     *minmoves = moves;
763 }
764
765 /* ----------------------------------------------------------------------
766  * End of solver/generator code.
767  */
768
769 static char *new_game_desc(game_params *params, random_state *rs,
770                            char **aux, int interactive)
771 {
772     int w = params->w, h = params->h, wh = w*h;
773     int tx, ty, minmoves;
774     unsigned char *board, *forcefield;
775     char *ret, *p;
776     int i;
777
778     generate_board(params->w, params->h, &tx, &ty, &minmoves, rs,
779                    &board, &forcefield);
780 #ifdef GENERATOR_DIAGNOSTICS
781     {
782         char *t = board_text_format(params->w, params->h, board);
783         printf("%s\n", t);
784         sfree(t);
785     }
786 #endif
787
788     /*
789      * Encode as a game ID.
790      */
791     ret = snewn(wh * 6 + 40, char);
792     p = ret;
793     i = 0;
794     while (i < wh) {
795         if (ISDIST(board[i])) {
796             p += sprintf(p, "d%d", board[i]);
797             i++;
798         } else {
799             int count = 1;
800             int b = board[i], f = forcefield[i];
801             int c = (b == ANCHOR ? 'a' :
802                      b == MAINANCHOR ? 'm' :
803                      b == EMPTY ? 'e' :
804                      /* b == WALL ? */ 'w');
805             if (f) *p++ = 'f';
806             *p++ = c;
807             i++;
808             while (i < wh && board[i] == b && forcefield[i] == f)
809                 i++, count++;
810             if (count > 1)
811                 p += sprintf(p, "%d", count);
812         }
813     }
814     p += sprintf(p, ",%d,%d,%d", tx, ty, minmoves);
815     ret = sresize(ret, p+1 - ret, char);
816
817     /*
818      * FIXME: generate an aux string
819      */
820
821     sfree(board);
822     sfree(forcefield);
823
824     return ret;
825 }
826
827 static char *validate_desc(game_params *params, char *desc)
828 {
829     int w = params->w, h = params->h, wh = w*h;
830     int *active, *link;
831     int mains = 0, mpos = -1;
832     int i, j, tx, ty, minmoves;
833     char *ret;
834
835     active = snewn(wh, int);
836     link = snewn(wh, int);
837     i = 0;
838
839     while (*desc && *desc != ',') {
840         if (i >= wh) {
841             ret = "Too much data in game description";
842             goto done;
843         }
844         link[i] = -1;
845         active[i] = FALSE;
846         if (*desc == 'f' || *desc == 'F') {
847             desc++;
848             if (!*desc) {
849                 ret = "Expected another character after 'f' in game "
850                     "description";
851                 goto done;
852             }
853         }
854
855         if (*desc == 'd' || *desc == 'D') {
856             int dist;
857
858             desc++;
859             if (!isdigit((unsigned char)*desc)) {
860                 ret = "Expected a number after 'd' in game description";
861                 goto done;
862             }
863             dist = atoi(desc);
864             while (*desc && isdigit((unsigned char)*desc)) desc++;
865
866             if (dist <= 0 || dist > i) {
867                 ret = "Out-of-range number after 'd' in game description";
868                 goto done;
869             }
870
871             if (!active[i - dist]) {
872                 ret = "Invalid back-reference in game description";
873                 goto done;
874             }
875
876             link[i] = i - dist;
877             for (j = i; j > 0; j = link[j])
878                 if (j == i-1 || j == i-w)
879                     break;
880             if (j < 0) {
881                 ret = "Disconnected piece in game description";
882                 goto done;
883             }
884
885             active[i] = TRUE;
886             active[link[i]] = FALSE;
887             i++;
888         } else {
889             int c = *desc++;
890             int count = 1;
891
892             if (!strchr("aAmMeEwW", c)) {
893                 ret = "Invalid character in game description";
894                 goto done;
895             }
896             if (isdigit((unsigned char)*desc)) {
897                 count = atoi(desc);
898                 while (*desc && isdigit((unsigned char)*desc)) desc++;
899             }
900             if (i + count > wh) {
901                 ret = "Too much data in game description";
902                 goto done;
903             }
904             while (count-- > 0) {
905                 active[i] = (strchr("aAmM", c) != NULL);
906                 link[i] = -1;
907                 if (strchr("mM", c) != NULL) {
908                     mains++;
909                     mpos = i;
910                 }
911                 i++;
912             }
913         }
914     }
915     if (mains != 1) {
916         ret = (mains == 0 ? "No main piece specified in game description" :
917                "More than one main piece specified in game description");
918         goto done;
919     }
920     if (i < wh) {
921         ret = "Not enough data in game description";
922         goto done;
923     }
924
925     /*
926      * Now read the target coordinates.
927      */
928     i = sscanf(desc, ",%d,%d,%d", &tx, &ty, &minmoves);
929     if (i < 2) {
930         ret = "No target coordinates specified";
931         goto done;
932         /*
933          * (but minmoves is optional)
934          */
935     }
936
937     ret = NULL;
938
939     done:
940     sfree(active);
941     sfree(link);
942     return ret;
943 }
944
945 static game_state *new_game(midend *me, game_params *params, char *desc)
946 {
947     int w = params->w, h = params->h, wh = w*h;
948     game_state *state;
949     int i;
950
951     state = snew(game_state);
952     state->w = w;
953     state->h = h;
954     state->board = snewn(wh, unsigned char);
955     state->lastmoved = state->lastmoved_pos = -1;
956     state->movecount = 0;
957     state->imm = snew(struct game_immutable_state);
958     state->imm->refcount = 1;
959     state->imm->forcefield = snewn(wh, unsigned char);
960
961     i = 0;
962
963     while (*desc && *desc != ',') {
964         int f = FALSE;
965
966         assert(i < wh);
967
968         if (*desc == 'f') {
969             f = TRUE;
970             desc++;
971             assert(*desc);
972         }
973
974         if (*desc == 'd' || *desc == 'D') {
975             int dist;
976
977             desc++;
978             dist = atoi(desc);
979             while (*desc && isdigit((unsigned char)*desc)) desc++;
980
981             state->board[i] = DIST(dist);
982             state->imm->forcefield[i] = f;
983
984             i++;
985         } else {
986             int c = *desc++;
987             int count = 1;
988
989             if (isdigit((unsigned char)*desc)) {
990                 count = atoi(desc);
991                 while (*desc && isdigit((unsigned char)*desc)) desc++;
992             }
993             assert(i + count <= wh);
994
995             c = (c == 'a' || c == 'A' ? ANCHOR :
996                  c == 'm' || c == 'M' ? MAINANCHOR :
997                  c == 'e' || c == 'E' ? EMPTY :
998                  /* c == 'w' || c == 'W' ? */ WALL);             
999
1000             while (count-- > 0) {
1001                 state->board[i] = c;
1002                 state->imm->forcefield[i] = f;
1003                 i++;
1004             }
1005         }
1006     }
1007
1008     /*
1009      * Now read the target coordinates.
1010      */
1011     state->tx = state->ty = 0;
1012     state->minmoves = -1;
1013     i = sscanf(desc, ",%d,%d,%d", &state->tx, &state->ty, &state->minmoves);
1014
1015     if (state->board[state->ty*w+state->tx] == MAINANCHOR)
1016         state->completed = 0;          /* already complete! */
1017     else
1018         state->completed = -1;
1019
1020     return state;
1021 }
1022
1023 static game_state *dup_game(game_state *state)
1024 {
1025     int w = state->w, h = state->h, wh = w*h;
1026     game_state *ret = snew(game_state);
1027
1028     ret->w = state->w;
1029     ret->h = state->h;
1030     ret->board = snewn(wh, unsigned char);
1031     memcpy(ret->board, state->board, wh);
1032     ret->tx = state->tx;
1033     ret->ty = state->ty;
1034     ret->minmoves = state->minmoves;
1035     ret->lastmoved = state->lastmoved;
1036     ret->lastmoved_pos = state->lastmoved_pos;
1037     ret->movecount = state->movecount;
1038     ret->completed = state->completed;
1039     ret->imm = state->imm;
1040     ret->imm->refcount++;
1041
1042     return ret;
1043 }
1044
1045 static void free_game(game_state *state)
1046 {
1047     if (--state->imm->refcount <= 0) {
1048         sfree(state->imm->forcefield);
1049         sfree(state->imm);
1050     }
1051     sfree(state->board);
1052     sfree(state);
1053 }
1054
1055 static char *solve_game(game_state *state, game_state *currstate,
1056                         char *aux, char **error)
1057 {
1058     /*
1059      * FIXME: we have a solver, so use it
1060      * 
1061      * FIXME: we should have generated an aux string, so use that
1062      */
1063     return NULL;
1064 }
1065
1066 static char *game_text_format(game_state *state)
1067 {
1068     return board_text_format(state->w, state->h, state->board,
1069                              state->imm->forcefield);
1070 }
1071
1072 struct game_ui {
1073     int dragging;
1074     int drag_anchor;
1075     int drag_offset_x, drag_offset_y;
1076     int drag_currpos;
1077     unsigned char *reachable;
1078     int *bfs_queue;                    /* used as scratch in interpret_move */
1079 };
1080
1081 static game_ui *new_ui(game_state *state)
1082 {
1083     int w = state->w, h = state->h, wh = w*h;
1084     game_ui *ui = snew(game_ui);
1085
1086     ui->dragging = FALSE;
1087     ui->drag_anchor = ui->drag_currpos = -1;
1088     ui->drag_offset_x = ui->drag_offset_y = -1;
1089     ui->reachable = snewn(wh, unsigned char);
1090     memset(ui->reachable, 0, wh);
1091     ui->bfs_queue = snewn(wh, int);
1092
1093     return ui;
1094 }
1095
1096 static void free_ui(game_ui *ui)
1097 {
1098     sfree(ui->bfs_queue);
1099     sfree(ui->reachable);
1100     sfree(ui);
1101 }
1102
1103 static char *encode_ui(game_ui *ui)
1104 {
1105     return NULL;
1106 }
1107
1108 static void decode_ui(game_ui *ui, char *encoding)
1109 {
1110 }
1111
1112 static void game_changed_state(game_ui *ui, game_state *oldstate,
1113                                game_state *newstate)
1114 {
1115 }
1116
1117 #define PREFERRED_TILESIZE 32
1118 #define TILESIZE (ds->tilesize)
1119 #define BORDER (TILESIZE/2)
1120 #define COORD(x)  ( (x) * TILESIZE + BORDER )
1121 #define FROMCOORD(x)  ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
1122 #define BORDER_WIDTH (1 + TILESIZE/20)
1123 #define HIGHLIGHT_WIDTH (1 + TILESIZE/16)
1124
1125 #define FLASH_INTERVAL 0.10F
1126 #define FLASH_TIME 3*FLASH_INTERVAL
1127
1128 struct game_drawstate {
1129     int tilesize;
1130     int w, h;
1131     unsigned long *grid;               /* what's currently displayed */
1132     int started;
1133 };
1134
1135 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1136                             int x, int y, int button)
1137 {
1138     int w = state->w, h = state->h, wh = w*h;
1139     int tx, ty, i, j;
1140     int qhead, qtail;
1141
1142     if (button == LEFT_BUTTON) {
1143         tx = FROMCOORD(x);
1144         ty = FROMCOORD(y);
1145
1146         if (tx < 0 || tx >= w || ty < 0 || ty >= h ||
1147             !ISBLOCK(state->board[ty*w+tx]))
1148             return NULL;               /* this click has no effect */
1149
1150         /*
1151          * User has clicked on a block. Find the block's anchor
1152          * and register that we've started dragging it.
1153          */
1154         i = ty*w+tx;
1155         while (ISDIST(state->board[i]))
1156             i -= state->board[i];
1157         assert(i >= 0 && i < wh);
1158
1159         ui->dragging = TRUE;
1160         ui->drag_anchor = i;
1161         ui->drag_offset_x = tx - (i % w);
1162         ui->drag_offset_y = ty - (i / w);
1163         ui->drag_currpos = i;
1164
1165         /*
1166          * Now we immediately bfs out from the current location of
1167          * the anchor, to find all the places to which this block
1168          * can be dragged.
1169          */
1170         memset(ui->reachable, FALSE, wh);
1171         qhead = qtail = 0;
1172         ui->reachable[i] = TRUE;
1173         ui->bfs_queue[qtail++] = i;
1174         for (j = i; j < wh; j++)
1175             if (state->board[j] == DIST(j - i))
1176                 i = j;
1177         while (qhead < qtail) {
1178             int pos = ui->bfs_queue[qhead++];
1179             int x = pos % w, y = pos / w;
1180             int dir;
1181
1182             for (dir = 0; dir < 4; dir++) {
1183                 int dx = (dir == 0 ? -1 : dir == 1 ? +1 : 0);
1184                 int dy = (dir == 2 ? -1 : dir == 3 ? +1 : 0);
1185                 int newpos;
1186
1187                 if (x + dx < 0 || x + dx >= w ||
1188                     y + dy < 0 || y + dy >= h)
1189                     continue;
1190
1191                 newpos = pos + dy*w + dx;
1192                 if (ui->reachable[newpos])
1193                     continue;          /* already done this one */
1194
1195                 /*
1196                  * Now search the grid to see if the block we're
1197                  * dragging could fit into this space.
1198                  */
1199                 for (j = i; j >= 0; j = (ISDIST(state->board[j]) ?
1200                                          j - state->board[j] : -1)) {
1201                     int jx = (j+pos-ui->drag_anchor) % w;
1202                     int jy = (j+pos-ui->drag_anchor) / w;
1203                     int j2;
1204
1205                     if (jx + dx < 0 || jx + dx >= w ||
1206                         jy + dy < 0 || jy + dy >= h)
1207                         break;         /* this position isn't valid at all */
1208
1209                     j2 = (j+pos-ui->drag_anchor) + dy*w + dx;
1210
1211                     if (state->board[j2] == EMPTY &&
1212                         (!state->imm->forcefield[j2] ||
1213                          state->board[ui->drag_anchor] == MAINANCHOR))
1214                         continue;
1215                     while (ISDIST(state->board[j2]))
1216                         j2 -= state->board[j2];
1217                     assert(j2 >= 0 && j2 < wh);
1218                     if (j2 == ui->drag_anchor)
1219                         continue;
1220                     else
1221                         break;
1222                 }
1223
1224                 if (j < 0) {
1225                     /*
1226                      * If we got to the end of that loop without
1227                      * disqualifying this position, mark it as
1228                      * reachable for this drag.
1229                      */
1230                     ui->reachable[newpos] = TRUE;
1231                     ui->bfs_queue[qtail++] = newpos;
1232                 }
1233             }
1234         }
1235
1236         /*
1237          * And that's it. Update the display to reflect the start
1238          * of a drag.
1239          */
1240         return "";
1241     } else if (button == LEFT_DRAG && ui->dragging) {
1242         tx = FROMCOORD(x);
1243         ty = FROMCOORD(y);
1244
1245         tx -= ui->drag_offset_x;
1246         ty -= ui->drag_offset_y;
1247         if (tx < 0 || tx >= w || ty < 0 || ty >= h ||
1248             !ui->reachable[ty*w+tx])
1249             return NULL;               /* this drag has no effect */
1250
1251         ui->drag_currpos = ty*w+tx;
1252         return "";
1253     } else if (button == LEFT_RELEASE && ui->dragging) {
1254         char data[256], *str;
1255
1256         /*
1257          * Terminate the drag, and if the piece has actually moved
1258          * then return a move string quoting the old and new
1259          * locations of the piece's anchor.
1260          */
1261         if (ui->drag_anchor != ui->drag_currpos) {
1262             sprintf(data, "M%d-%d", ui->drag_anchor, ui->drag_currpos);
1263             str = dupstr(data);
1264         } else
1265             str = "";                  /* null move; just update the UI */
1266         
1267         ui->dragging = FALSE;
1268         ui->drag_anchor = ui->drag_currpos = -1;
1269         ui->drag_offset_x = ui->drag_offset_y = -1;
1270         memset(ui->reachable, 0, wh);
1271
1272         return str;
1273     }
1274
1275     return NULL;
1276 }
1277
1278 static int move_piece(int w, int h, const unsigned char *src,
1279                       unsigned char *dst, unsigned char *ff, int from, int to)
1280 {
1281     int wh = w*h;
1282     int i, j;
1283
1284     if (!ISANCHOR(dst[from]))
1285         return FALSE;
1286
1287     /*
1288      * Scan to the far end of the piece's linked list.
1289      */
1290     for (i = j = from; j < wh; j++)
1291         if (src[j] == DIST(j - i))
1292             i = j;
1293
1294     /*
1295      * Remove the piece from its old location in the new
1296      * game state.
1297      */
1298     for (j = i; j >= 0; j = (ISDIST(src[j]) ? j - src[j] : -1))
1299         dst[j] = EMPTY;
1300
1301     /*
1302      * And put it back in at the new location.
1303      */
1304     for (j = i; j >= 0; j = (ISDIST(src[j]) ? j - src[j] : -1)) {
1305         int jn = j + to - from;
1306         if (jn < 0 || jn >= wh)
1307             return FALSE;
1308         if (dst[jn] == EMPTY && (!ff[jn] || src[from] == MAINANCHOR)) {
1309             dst[jn] = src[j];
1310         } else {
1311             return FALSE;
1312         }
1313     }
1314
1315     return TRUE;
1316 }
1317
1318 static game_state *execute_move(game_state *state, char *move)
1319 {
1320     int w = state->w, h = state->h /* , wh = w*h */;
1321     char c;
1322     int a1, a2, n;
1323     game_state *ret = dup_game(state);
1324
1325     while (*move) {
1326         c = *move;
1327         if (c == 'M') {
1328             move++;
1329             if (sscanf(move, "%d-%d%n", &a1, &a2, &n) != 2 ||
1330                 !move_piece(w, h, state->board, ret->board,
1331                             state->imm->forcefield, a1, a2)) {
1332                 free_game(ret);
1333                 return NULL;
1334             }
1335             if (a1 == ret->lastmoved) {
1336                 /*
1337                  * If the player has moved the same piece as they
1338                  * moved last time, don't increment the move
1339                  * count. In fact, if they've put the piece back
1340                  * where it started from, _decrement_ the move
1341                  * count.
1342                  */
1343                 if (a2 == ret->lastmoved_pos) {
1344                     ret->movecount--;  /* reverted last move */
1345                     ret->lastmoved = ret->lastmoved_pos = -1;
1346                 } else {
1347                     ret->lastmoved = a2;
1348                     /* don't change lastmoved_pos */
1349                 }
1350             } else {
1351                 ret->lastmoved = a2;
1352                 ret->lastmoved_pos = a1;
1353                 ret->movecount++;
1354             }
1355             if (ret->board[a2] == MAINANCHOR &&
1356                 a2 == ret->ty * w + ret->tx && ret->completed < 0)
1357                 ret->completed = ret->movecount;
1358             move += n;
1359         } else {
1360             free_game(ret);
1361             return NULL;
1362         }
1363         if (*move == ';')
1364             move++;
1365         else if (*move) {
1366             free_game(ret);
1367             return NULL;
1368         }
1369     }
1370
1371     return ret;
1372 }
1373
1374 /* ----------------------------------------------------------------------
1375  * Drawing routines.
1376  */
1377
1378 static void game_compute_size(game_params *params, int tilesize,
1379                               int *x, int *y)
1380 {
1381     /* fool the macros */
1382     struct dummy { int tilesize; } dummy = { tilesize }, *ds = &dummy;
1383
1384     *x = params->w * TILESIZE + 2*BORDER;
1385     *y = params->h * TILESIZE + 2*BORDER;
1386 }
1387
1388 static void game_set_size(drawing *dr, game_drawstate *ds,
1389                           game_params *params, int tilesize)
1390 {
1391     ds->tilesize = tilesize;
1392 }
1393
1394 static void raise_colour(float *target, float *src, float *limit)
1395 {
1396     int i;
1397     for (i = 0; i < 3; i++)
1398         target[i] = (2*src[i] + limit[i]) / 3;
1399 }
1400
1401 static float *game_colours(frontend *fe, int *ncolours)
1402 {
1403     float *ret = snewn(3 * NCOLOURS, float);
1404
1405     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1406
1407     /*
1408      * When dragging a tile, we light it up a bit.
1409      */
1410     raise_colour(ret+3*COL_DRAGGING,
1411                  ret+3*COL_BACKGROUND, ret+3*COL_HIGHLIGHT);
1412     raise_colour(ret+3*COL_DRAGGING_HIGHLIGHT,
1413                  ret+3*COL_HIGHLIGHT, ret+3*COL_HIGHLIGHT);
1414     raise_colour(ret+3*COL_DRAGGING_LOWLIGHT,
1415                  ret+3*COL_LOWLIGHT, ret+3*COL_HIGHLIGHT);
1416
1417     /*
1418      * The main tile is tinted blue.
1419      */
1420     ret[COL_MAIN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0];
1421     ret[COL_MAIN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1];
1422     ret[COL_MAIN * 3 + 2] = ret[COL_HIGHLIGHT * 3 + 2];
1423     game_mkhighlight_specific(fe, ret, COL_MAIN,
1424                               COL_MAIN_HIGHLIGHT, COL_MAIN_LOWLIGHT);
1425
1426     /*
1427      * And we light that up a bit too when dragging.
1428      */
1429     raise_colour(ret+3*COL_MAIN_DRAGGING,
1430                  ret+3*COL_MAIN, ret+3*COL_MAIN_HIGHLIGHT);
1431     raise_colour(ret+3*COL_MAIN_DRAGGING_HIGHLIGHT,
1432                  ret+3*COL_MAIN_HIGHLIGHT, ret+3*COL_MAIN_HIGHLIGHT);
1433     raise_colour(ret+3*COL_MAIN_DRAGGING_LOWLIGHT,
1434                  ret+3*COL_MAIN_LOWLIGHT, ret+3*COL_MAIN_HIGHLIGHT);
1435
1436     /*
1437      * The target area on the floor is tinted green.
1438      */
1439     ret[COL_TARGET * 3 + 0] = ret[COL_BACKGROUND * 3 + 0];
1440     ret[COL_TARGET * 3 + 1] = ret[COL_HIGHLIGHT * 3 + 1];
1441     ret[COL_TARGET * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1442     game_mkhighlight_specific(fe, ret, COL_TARGET,
1443                               COL_TARGET_HIGHLIGHT, COL_TARGET_LOWLIGHT);
1444
1445     *ncolours = NCOLOURS;
1446     return ret;
1447 }
1448
1449 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1450 {
1451     int w = state->w, h = state->h, wh = w*h;
1452     struct game_drawstate *ds = snew(struct game_drawstate);
1453     int i;
1454
1455     ds->tilesize = 0;
1456     ds->w = w;
1457     ds->h = h;
1458     ds->started = FALSE;
1459     ds->grid = snewn(wh, unsigned long);
1460     for (i = 0; i < wh; i++)
1461         ds->grid[i] = ~(unsigned long)0;
1462
1463     return ds;
1464 }
1465
1466 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1467 {
1468     sfree(ds->grid);
1469     sfree(ds);
1470 }
1471
1472 #define BG_NORMAL       0x00000001UL
1473 #define BG_TARGET       0x00000002UL
1474 #define BG_FORCEFIELD   0x00000004UL
1475 #define FLASH_LOW       0x00000008UL
1476 #define FLASH_HIGH      0x00000010UL
1477 #define FG_WALL         0x00000020UL
1478 #define FG_MAIN         0x00000040UL
1479 #define FG_NORMAL       0x00000080UL
1480 #define FG_DRAGGING     0x00000100UL
1481 #define FG_LBORDER      0x00000200UL
1482 #define FG_TBORDER      0x00000400UL
1483 #define FG_RBORDER      0x00000800UL
1484 #define FG_BBORDER      0x00001000UL
1485 #define FG_TLCORNER     0x00002000UL
1486 #define FG_TRCORNER     0x00004000UL
1487 #define FG_BLCORNER     0x00008000UL
1488 #define FG_BRCORNER     0x00010000UL
1489
1490 /*
1491  * Utility function.
1492  */
1493 #define TYPE_MASK 0xF000
1494 #define COL_MASK 0x0FFF
1495 #define TYPE_RECT 0x0000
1496 #define TYPE_TLCIRC 0x4000
1497 #define TYPE_TRCIRC 0x5000
1498 #define TYPE_BLCIRC 0x6000
1499 #define TYPE_BRCIRC 0x7000
1500 static void maybe_rect(drawing *dr, int x, int y, int w, int h, int coltype)
1501 {
1502     int colour = coltype & COL_MASK, type = coltype & TYPE_MASK;
1503
1504     if (colour > NCOLOURS)
1505         return;
1506     if (type == TYPE_RECT) {
1507         draw_rect(dr, x, y, w, h, colour);
1508     } else {
1509         int cx, cy, r;
1510
1511         clip(dr, x, y, w, h);
1512
1513         cx = x;
1514         cy = y;
1515         assert(w == h);
1516         r = w-1;
1517         if (type & 0x1000)
1518             cx += r;
1519         if (type & 0x2000)
1520             cy += r;
1521         draw_circle(dr, cx, cy, r, colour, colour);
1522
1523         unclip(dr);
1524     }
1525 }
1526
1527 static void draw_tile(drawing *dr, game_drawstate *ds,
1528                       int x, int y, unsigned long val)
1529 {
1530     int tx = COORD(x), ty = COORD(y);
1531     int cc, ch, cl;
1532
1533     /*
1534      * Draw the tile background.
1535      */
1536     if (val & BG_TARGET)
1537         cc = COL_TARGET;
1538     else
1539         cc = COL_BACKGROUND;
1540     ch = cc+1;
1541     cl = cc+2;
1542     if (val & FLASH_LOW)
1543         cc = cl;
1544     else if (val & FLASH_HIGH)
1545         cc = ch;
1546
1547     draw_rect(dr, tx, ty, TILESIZE, TILESIZE, cc);
1548     if (val & BG_FORCEFIELD) {
1549         /*
1550          * Cattle-grid effect to indicate that nothing but the
1551          * main block can slide over this square.
1552          */
1553         int n = 3 * (TILESIZE / (3*HIGHLIGHT_WIDTH));
1554         int i;
1555
1556         for (i = 1; i < n; i += 3) {
1557             draw_rect(dr, tx,ty+(TILESIZE*i/n), TILESIZE,HIGHLIGHT_WIDTH, cl);
1558             draw_rect(dr, tx+(TILESIZE*i/n),ty, HIGHLIGHT_WIDTH,TILESIZE, cl);
1559         }
1560     }
1561
1562     /*
1563      * Draw the tile foreground, i.e. some section of a block or
1564      * wall.
1565      */
1566     if (val & FG_WALL) {
1567         cc = COL_BACKGROUND;
1568         ch = cc+1;
1569         cl = cc+2;
1570         if (val & FLASH_LOW)
1571             cc = cl;
1572         else if (val & FLASH_HIGH)
1573             cc = ch;
1574
1575         draw_rect(dr, tx, ty, TILESIZE, TILESIZE, cc);
1576         if (val & FG_LBORDER)
1577             draw_rect(dr, tx, ty, HIGHLIGHT_WIDTH, TILESIZE,
1578                       ch);
1579         if (val & FG_RBORDER)
1580             draw_rect(dr, tx+TILESIZE-HIGHLIGHT_WIDTH, ty,
1581                       HIGHLIGHT_WIDTH, TILESIZE, cl);
1582         if (val & FG_TBORDER)
1583             draw_rect(dr, tx, ty, TILESIZE, HIGHLIGHT_WIDTH, ch);
1584         if (val & FG_BBORDER)
1585             draw_rect(dr, tx, ty+TILESIZE-HIGHLIGHT_WIDTH,
1586                       TILESIZE, HIGHLIGHT_WIDTH, cl);
1587         if (!((FG_BBORDER | FG_LBORDER) &~ val))
1588             draw_rect(dr, tx, ty+TILESIZE-HIGHLIGHT_WIDTH,
1589                       HIGHLIGHT_WIDTH, HIGHLIGHT_WIDTH, cc);
1590         if (!((FG_TBORDER | FG_RBORDER) &~ val))
1591             draw_rect(dr, tx+TILESIZE-HIGHLIGHT_WIDTH, ty,
1592                       HIGHLIGHT_WIDTH, HIGHLIGHT_WIDTH, cc);
1593         if (val & FG_TLCORNER)
1594             draw_rect(dr, tx, ty, HIGHLIGHT_WIDTH, HIGHLIGHT_WIDTH, ch);
1595         if (val & FG_BRCORNER)
1596             draw_rect(dr, tx+TILESIZE-HIGHLIGHT_WIDTH,
1597                       ty+TILESIZE-HIGHLIGHT_WIDTH,
1598                       HIGHLIGHT_WIDTH, HIGHLIGHT_WIDTH, cl);
1599     } else if (val & (FG_MAIN | FG_NORMAL)) {
1600         int x[6], y[6];
1601
1602         if (val & FG_DRAGGING)
1603             cc = (val & FG_MAIN ? COL_MAIN_DRAGGING : COL_DRAGGING);
1604         else
1605             cc = (val & FG_MAIN ? COL_MAIN : COL_BACKGROUND);
1606         ch = cc+1;
1607         cl = cc+2;
1608
1609         if (val & FLASH_LOW)
1610             cc = cl;
1611         else if (val & FLASH_HIGH)
1612             cc = ch;
1613
1614         /*
1615          * Drawing the blocks is hellishly fiddly. The blocks
1616          * don't stretch to the full size of the tile; there's a
1617          * border around them of size BORDER_WIDTH. Then they have
1618          * bevelled borders of size HIGHLIGHT_WIDTH, and also
1619          * rounded corners.
1620          * 
1621          * I tried for some time to find a clean and clever way to
1622          * figure out what needed drawing from the corner and
1623          * border flags, but in the end the cleanest way I could
1624          * find was the following. We divide the grid square into
1625          * 25 parts by ruling four horizontal and four vertical
1626          * lines across it; those lines are at BORDER_WIDTH and
1627          * BORDER_WIDTH+HIGHLIGHT_WIDTH from the top, from the
1628          * bottom, from the left and from the right. Then we
1629          * carefully consider each of the resulting 25 sections of
1630          * square, and decide separately what needs to go in it
1631          * based on the flags. In complicated cases there can be
1632          * up to five possibilities affecting any given section
1633          * (no corner or border flags, just the corner flag, one
1634          * border flag, the other border flag, both border flags).
1635          * So there's a lot of very fiddly logic here and all I
1636          * could really think to do was give it my best shot and
1637          * then test it and correct all the typos. Not fun to
1638          * write, and I'm sure it isn't fun to read either, but it
1639          * seems to work.
1640          */
1641
1642         x[0] = tx;
1643         x[1] = x[0] + BORDER_WIDTH;
1644         x[2] = x[1] + HIGHLIGHT_WIDTH;
1645         x[5] = tx + TILESIZE;
1646         x[4] = x[5] - BORDER_WIDTH;
1647         x[3] = x[4] - HIGHLIGHT_WIDTH;
1648
1649         y[0] = ty;
1650         y[1] = y[0] + BORDER_WIDTH;
1651         y[2] = y[1] + HIGHLIGHT_WIDTH;
1652         y[5] = ty + TILESIZE;
1653         y[4] = y[5] - BORDER_WIDTH;
1654         y[3] = y[4] - HIGHLIGHT_WIDTH;
1655
1656 #define RECT(p,q) x[p], y[q], x[(p)+1]-x[p], y[(q)+1]-y[q]
1657
1658         maybe_rect(dr, RECT(0,0),
1659                    (val & (FG_TLCORNER | FG_TBORDER | FG_LBORDER)) ? -1 : cc);
1660         maybe_rect(dr, RECT(1,0),
1661                    (val & FG_TLCORNER) ? ch : (val & FG_TBORDER) ? -1 :
1662                    (val & FG_LBORDER) ? ch : cc);
1663         maybe_rect(dr, RECT(2,0),
1664                    (val & FG_TBORDER) ? -1 : cc);
1665         maybe_rect(dr, RECT(3,0),
1666                    (val & FG_TRCORNER) ? cl : (val & FG_TBORDER) ? -1 :
1667                    (val & FG_RBORDER) ? cl : cc);
1668         maybe_rect(dr, RECT(4,0),
1669                    (val & (FG_TRCORNER | FG_TBORDER | FG_RBORDER)) ? -1 : cc);
1670         maybe_rect(dr, RECT(0,1),
1671                    (val & FG_TLCORNER) ? ch : (val & FG_LBORDER) ? -1 :
1672                    (val & FG_TBORDER) ? ch : cc);
1673         maybe_rect(dr, RECT(1,1),
1674                    (val & FG_TLCORNER) ? cc : -1);
1675         maybe_rect(dr, RECT(1,1),
1676                    (val & FG_TLCORNER) ? ch | TYPE_TLCIRC :
1677                    !((FG_TBORDER | FG_LBORDER) &~ val) ? ch | TYPE_BRCIRC :
1678                    (val & (FG_TBORDER | FG_LBORDER)) ? ch : cc);
1679         maybe_rect(dr, RECT(2,1),
1680                    (val & FG_TBORDER) ? ch : cc);
1681         maybe_rect(dr, RECT(3,1),
1682                    (val & (FG_TBORDER | FG_RBORDER)) == FG_TBORDER ? ch :
1683                    (val & (FG_TBORDER | FG_RBORDER)) == FG_RBORDER ? cl :
1684                    !((FG_TBORDER|FG_RBORDER) &~ val) ? cc | TYPE_BLCIRC : cc);
1685         maybe_rect(dr, RECT(4,1),
1686                    (val & FG_TRCORNER) ? ch : (val & FG_RBORDER) ? -1 :
1687                    (val & FG_TBORDER) ? ch : cc);
1688         maybe_rect(dr, RECT(0,2),
1689                    (val & FG_LBORDER) ? -1 : cc);
1690         maybe_rect(dr, RECT(1,2),
1691                    (val & FG_LBORDER) ? ch : cc);
1692         maybe_rect(dr, RECT(2,2),
1693                    cc);
1694         maybe_rect(dr, RECT(3,2),
1695                    (val & FG_RBORDER) ? cl : cc);
1696         maybe_rect(dr, RECT(4,2),
1697                    (val & FG_RBORDER) ? -1 : cc);
1698         maybe_rect(dr, RECT(0,3),
1699                    (val & FG_BLCORNER) ? cl : (val & FG_LBORDER) ? -1 :
1700                    (val & FG_BBORDER) ? cl : cc);
1701         maybe_rect(dr, RECT(1,3),
1702                    (val & (FG_BBORDER | FG_LBORDER)) == FG_BBORDER ? cl :
1703                    (val & (FG_BBORDER | FG_LBORDER)) == FG_LBORDER ? ch :
1704                    !((FG_BBORDER|FG_LBORDER) &~ val) ? cc | TYPE_TRCIRC : cc);
1705         maybe_rect(dr, RECT(2,3),
1706                    (val & FG_BBORDER) ? cl : cc);
1707         maybe_rect(dr, RECT(3,3),
1708                    (val & FG_BRCORNER) ? cc : -1);
1709         maybe_rect(dr, RECT(3,3),
1710                    (val & FG_BRCORNER) ? cl | TYPE_BRCIRC :
1711                    !((FG_BBORDER | FG_RBORDER) &~ val) ? cl | TYPE_TLCIRC :
1712                    (val & (FG_BBORDER | FG_RBORDER)) ? cl : cc);
1713         maybe_rect(dr, RECT(4,3),
1714                    (val & FG_BRCORNER) ? cl : (val & FG_RBORDER) ? -1 :
1715                    (val & FG_BBORDER) ? cl : cc);
1716         maybe_rect(dr, RECT(0,4),
1717                    (val & (FG_BLCORNER | FG_BBORDER | FG_LBORDER)) ? -1 : cc);
1718         maybe_rect(dr, RECT(1,4),
1719                    (val & FG_BLCORNER) ? ch : (val & FG_BBORDER) ? -1 :
1720                    (val & FG_LBORDER) ? ch : cc);
1721         maybe_rect(dr, RECT(2,4),
1722                    (val & FG_BBORDER) ? -1 : cc);
1723         maybe_rect(dr, RECT(3,4),
1724                    (val & FG_BRCORNER) ? cl : (val & FG_BBORDER) ? -1 :
1725                    (val & FG_RBORDER) ? cl : cc);
1726         maybe_rect(dr, RECT(4,4),
1727                    (val & (FG_BRCORNER | FG_BBORDER | FG_RBORDER)) ? -1 : cc);
1728
1729 #undef RECT
1730
1731     }
1732
1733     draw_update(dr, tx, ty, TILESIZE, TILESIZE);
1734 }
1735
1736 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1737                         game_state *state, int dir, game_ui *ui,
1738                         float animtime, float flashtime)
1739 {
1740     int w = state->w, h = state->h, wh = w*h;
1741     unsigned char *board;
1742     int *dsf;
1743     int x, y, mainanchor, mainpos, dragpos;
1744
1745     if (!ds->started) {
1746         /*
1747          * The initial contents of the window are not guaranteed
1748          * and can vary with front ends. To be on the safe side,
1749          * all games should start by drawing a big
1750          * background-colour rectangle covering the whole window.
1751          */
1752         draw_rect(dr, 0, 0, 10*ds->tilesize, 10*ds->tilesize, COL_BACKGROUND);
1753         ds->started = TRUE;
1754     }
1755
1756     /*
1757      * Construct the board we'll be displaying (which may be
1758      * different from the one in state if ui describes a drag in
1759      * progress).
1760      */
1761     board = snewn(wh, unsigned char);
1762     memcpy(board, state->board, wh);
1763     if (ui->dragging) {
1764         int mpret = move_piece(w, h, state->board, board,
1765                                state->imm->forcefield,
1766                                ui->drag_anchor, ui->drag_currpos);
1767         assert(mpret);
1768     }
1769
1770     /*
1771      * Build a dsf out of that board, so we can conveniently tell
1772      * which edges are connected and which aren't.
1773      */
1774     dsf = snew_dsf(wh);
1775     mainanchor = -1;
1776     for (y = 0; y < h; y++)
1777         for (x = 0; x < w; x++) {
1778             int i = y*w+x;
1779
1780             if (ISDIST(board[i]))
1781                 dsf_merge(dsf, i, i - board[i]);
1782             if (board[i] == MAINANCHOR)
1783                 mainanchor = i;
1784             if (board[i] == WALL) {
1785                 if (x > 0 && board[i-1] == WALL)
1786                     dsf_merge(dsf, i, i-1);
1787                 if (y > 0 && board[i-w] == WALL)
1788                     dsf_merge(dsf, i, i-w);
1789             }
1790         }
1791     assert(mainanchor >= 0);
1792     mainpos = dsf_canonify(dsf, mainanchor);
1793     dragpos = ui->drag_currpos > 0 ? dsf_canonify(dsf, ui->drag_currpos) : -1;
1794
1795     /*
1796      * Now we can construct the data about what we want to draw.
1797      */
1798     for (y = 0; y < h; y++)
1799         for (x = 0; x < w; x++) {
1800             int i = y*w+x;
1801             int j;
1802             unsigned long val;
1803             int canon;
1804
1805             /*
1806              * See if this square is part of the target area.
1807              */
1808             j = i + mainanchor - (state->ty * w + state->tx);
1809             while (j >= 0 && j < wh && ISDIST(board[j]))
1810                 j -= board[j];
1811             if (j == mainanchor)
1812                 val = BG_TARGET;
1813             else
1814                 val = BG_NORMAL;
1815
1816             if (state->imm->forcefield[i])
1817                 val |= BG_FORCEFIELD;
1818
1819             if (flashtime > 0) {
1820                 int flashtype = (int)(flashtime / FLASH_INTERVAL) & 1;
1821                 val |= (flashtype ? FLASH_LOW : FLASH_HIGH);
1822             }
1823
1824             if (board[i] != EMPTY) {
1825                 canon = dsf_canonify(dsf, i);
1826
1827                 if (board[i] == WALL)
1828                     val |= FG_WALL;
1829                 else if (canon == mainpos)
1830                     val |= FG_MAIN;
1831                 else
1832                     val |= FG_NORMAL;
1833                 if (canon == dragpos)
1834                     val |= FG_DRAGGING;
1835
1836                 /*
1837                  * Now look around to see if other squares
1838                  * belonging to the same block are adjacent to us.
1839                  */
1840                 if (x == 0 || canon != dsf_canonify(dsf, i-1))
1841                     val |= FG_LBORDER;
1842                 if (y== 0 || canon != dsf_canonify(dsf, i-w))
1843                     val |= FG_TBORDER;
1844                 if (x == w-1 || canon != dsf_canonify(dsf, i+1))
1845                     val |= FG_RBORDER;
1846                 if (y == h-1 || canon != dsf_canonify(dsf, i+w))
1847                     val |= FG_BBORDER;
1848                 if (!(val & (FG_TBORDER | FG_LBORDER)) &&
1849                     canon != dsf_canonify(dsf, i-1-w))
1850                     val |= FG_TLCORNER;
1851                 if (!(val & (FG_TBORDER | FG_RBORDER)) &&
1852                     canon != dsf_canonify(dsf, i+1-w))
1853                     val |= FG_TRCORNER;
1854                 if (!(val & (FG_BBORDER | FG_LBORDER)) &&
1855                     canon != dsf_canonify(dsf, i-1+w))
1856                     val |= FG_BLCORNER;
1857                 if (!(val & (FG_BBORDER | FG_RBORDER)) &&
1858                     canon != dsf_canonify(dsf, i+1+w))
1859                     val |= FG_BRCORNER;
1860             }
1861
1862             if (val != ds->grid[i]) {
1863                 draw_tile(dr, ds, x, y, val);
1864                 ds->grid[i] = val;
1865             }
1866         }
1867
1868     /*
1869      * Update the status bar.
1870      */
1871     {
1872         char statusbuf[256];
1873
1874         /*
1875          * FIXME: do something about auto-solve?
1876          */
1877         sprintf(statusbuf, "%sMoves: %d",
1878                 (state->completed >= 0 ? "COMPLETED! " : ""),
1879                 (state->completed >= 0 ? state->completed : state->movecount));
1880         if (state->minmoves >= 0)
1881             sprintf(statusbuf+strlen(statusbuf), " (min %d)",
1882                     state->minmoves);
1883
1884         status_bar(dr, statusbuf);
1885     }
1886
1887     sfree(dsf);
1888     sfree(board);
1889 }
1890
1891 static float game_anim_length(game_state *oldstate, game_state *newstate,
1892                               int dir, game_ui *ui)
1893 {
1894     return 0.0F;
1895 }
1896
1897 static float game_flash_length(game_state *oldstate, game_state *newstate,
1898                                int dir, game_ui *ui)
1899 {
1900     if (oldstate->completed < 0 && newstate->completed >= 0)
1901         return FLASH_TIME;
1902
1903     return 0.0F;
1904 }
1905
1906 static int game_timing_state(game_state *state, game_ui *ui)
1907 {
1908     return TRUE;
1909 }
1910
1911 static void game_print_size(game_params *params, float *x, float *y)
1912 {
1913 }
1914
1915 static void game_print(drawing *dr, game_state *state, int tilesize)
1916 {
1917 }
1918
1919 #ifdef COMBINED
1920 #define thegame nullgame
1921 #endif
1922
1923 const struct game thegame = {
1924     "Slide", NULL, NULL,
1925     default_params,
1926     game_fetch_preset,
1927     decode_params,
1928     encode_params,
1929     free_params,
1930     dup_params,
1931     TRUE, game_configure, custom_params,
1932     validate_params,
1933     new_game_desc,
1934     validate_desc,
1935     new_game,
1936     dup_game,
1937     free_game,
1938     FALSE, solve_game,                 /* FIXME */
1939     TRUE, game_text_format,
1940     new_ui,
1941     free_ui,
1942     encode_ui,
1943     decode_ui,
1944     game_changed_state,
1945     interpret_move,
1946     execute_move,
1947     PREFERRED_TILESIZE, game_compute_size, game_set_size,
1948     game_colours,
1949     game_new_drawstate,
1950     game_free_drawstate,
1951     game_redraw,
1952     game_anim_length,
1953     game_flash_length,
1954     FALSE, FALSE, game_print_size, game_print,
1955     TRUE,                              /* wants_statusbar */
1956     FALSE, game_timing_state,
1957     0,                                 /* flags */
1958 };