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