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