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