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