Keyboard cursor support in Galaxies, by James H.
[sgt/puzzles] / galaxies.c
1 /*
2 * galaxies.c: implementation of 'Tentai Show' from Nikoli,
3 * also sometimes called 'Spiral Galaxies'.
4 *
5 * Notes:
6 *
7 * Grid is stored as size (2n-1), holding edges as well as spaces
8 * (and thus vertices too, at edge intersections).
9 *
10 * Any dot will thus be positioned at one of our grid points,
11 * which saves any faffing with half-of-a-square stuff.
12 *
13 * Edges have on/off state; obviously the actual edges of the
14 * board are fixed to on, and everything else starts as off.
15 *
16 * TTD:
17 * Cleverer solver
18 * Think about how to display remote groups of tiles?
19 *
20 * Bugs:
21 *
22 * Notable puzzle IDs:
23 *
24 * Nikoli's example [web site has wrong highlighting]
25 * (at http://www.nikoli.co.jp/en/puzzles/astronomical_show/):
26 * 5x5:eBbbMlaBbOEnf
27 *
28 * The 'spiral galaxies puzzles are NP-complete' paper
29 * (at http://www.stetson.edu/~efriedma/papers/spiral.pdf):
30 * 7x7:chpgdqqqoezdddki
31 *
32 * Puzzle competition pdf examples
33 * (at http://www.puzzleratings.org/Yurekli2006puz.pdf):
34 * 6x6:EDbaMucCohbrecEi
35 * 10x10:beFbufEEzowDlxldibMHezBQzCdcFzjlci
36 * 13x13:dCemIHFFkJajjgDfdbdBzdzEgjccoPOcztHjBczLDjczqktJjmpreivvNcggFi
37 *
38 */
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <assert.h>
44 #include <ctype.h>
45 #include <math.h>
46
47 #include "puzzles.h"
48
49 #ifdef DEBUGGING
50 #define solvep debug
51 #else
52 int solver_show_working;
53 #define solvep(x) do { if (solver_show_working) { printf x; } } while(0)
54 #endif
55
56 #ifdef STANDALONE_PICTURE_GENERATOR
57 /*
58 * Dirty hack to enable the generator to construct a game ID which
59 * solves to a specified black-and-white bitmap. We define a global
60 * variable here which gives the desired colour of each square, and
61 * we arrange that the grid generator never merges squares of
62 * different colours.
63 *
64 * The bitmap as stored here is a simple int array (at these sizes
65 * it isn't worth doing fiddly bit-packing). picture[y*w+x] is 1
66 * iff the pixel at (x,y) is intended to be black.
67 *
68 * (It might be nice to be able to specify some pixels as
69 * don't-care, to give the generator more leeway. But that might be
70 * fiddly.)
71 */
72 static int *picture;
73 #endif
74
75 enum {
76 COL_BACKGROUND,
77 COL_WHITEBG,
78 COL_BLACKBG,
79 COL_WHITEDOT,
80 COL_BLACKDOT,
81 COL_GRID,
82 COL_EDGE,
83 COL_ARROW,
84 COL_CURSOR,
85 NCOLOURS
86 };
87
88 #define DIFFLIST(A) \
89 A(NORMAL,Normal,n) \
90 A(UNREASONABLE,Unreasonable,u)
91
92 #define ENUM(upper,title,lower) DIFF_ ## upper,
93 #define TITLE(upper,title,lower) #title,
94 #define ENCODE(upper,title,lower) #lower
95 #define CONFIG(upper,title,lower) ":" #title
96 enum { DIFFLIST(ENUM)
97 DIFF_IMPOSSIBLE, DIFF_AMBIGUOUS, DIFF_UNFINISHED, DIFF_MAX };
98 static char const *const galaxies_diffnames[] = {
99 DIFFLIST(TITLE) "Impossible", "Ambiguous", "Unfinished" };
100 static char const galaxies_diffchars[] = DIFFLIST(ENCODE);
101 #define DIFFCONFIG DIFFLIST(CONFIG)
102
103 struct game_params {
104 /* X and Y is the area of the board as seen by
105 * the user, not the (2n+1) area the game uses. */
106 int w, h, diff;
107 };
108
109 enum { s_tile, s_edge, s_vertex };
110
111 #define F_DOT 1 /* there's a dot here */
112 #define F_EDGE_SET 2 /* the edge is set */
113 #define F_TILE_ASSOC 4 /* this tile is associated with a dot. */
114 #define F_DOT_BLACK 8 /* (ui only) dot is black. */
115 #define F_MARK 16 /* scratch flag */
116 #define F_REACHABLE 32
117 #define F_SCRATCH 64
118 #define F_MULTIPLE 128
119 #define F_DOT_HOLD 256
120 #define F_GOOD 512
121
122 typedef struct space {
123 int x, y; /* its position */
124 int type;
125 unsigned int flags;
126 int dotx, doty; /* if flags & F_TILE_ASSOC */
127 int nassoc; /* if flags & F_DOT */
128 } space;
129
130 #define INGRID(s,x,y) ((x) >= 0 && (y) >= 0 && \
131 (x) < (state)->sx && (y) < (state)->sy)
132 #define INUI(s,x,y) ((x) > 0 && (y) > 0 && \
133 (x) < ((state)->sx-1) && (y) < ((state)->sy-1))
134
135 #define GRID(s,g,x,y) ((s)->g[((y)*(s)->sx)+(x)])
136 #define SPACE(s,x,y) GRID(s,grid,x,y)
137
138 struct game_state {
139 int w, h; /* size from params */
140 int sx, sy; /* allocated size, (2x-1)*(2y-1) */
141 space *grid;
142 int completed, used_solve;
143 int ndots;
144 space **dots;
145
146 midend *me; /* to call supersede_game_desc */
147 int cdiff; /* difficulty of current puzzle (for status bar),
148 or -1 if stale. */
149 };
150
151 /* ----------------------------------------------------------
152 * Game parameters and presets
153 */
154
155 /* make up some sensible default sizes */
156
157 #define DEFAULT_PRESET 0
158
159 static const game_params galaxies_presets[] = {
160 { 7, 7, DIFF_NORMAL },
161 { 7, 7, DIFF_UNREASONABLE },
162 { 10, 10, DIFF_NORMAL },
163 { 15, 15, DIFF_NORMAL },
164 };
165
166 static int game_fetch_preset(int i, char **name, game_params **params)
167 {
168 game_params *ret;
169 char buf[80];
170
171 if (i < 0 || i >= lenof(galaxies_presets))
172 return FALSE;
173
174 ret = snew(game_params);
175 *ret = galaxies_presets[i]; /* structure copy */
176
177 sprintf(buf, "%dx%d %s", ret->w, ret->h,
178 galaxies_diffnames[ret->diff]);
179
180 if (name) *name = dupstr(buf);
181 *params = ret;
182 return TRUE;
183 }
184
185 static game_params *default_params(void)
186 {
187 game_params *ret;
188 game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
189 return ret;
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->h = params->w = atoi(string);
207 params->diff = DIFF_NORMAL;
208 while (*string && isdigit((unsigned char)*string)) string++;
209 if (*string == 'x') {
210 string++;
211 params->h = atoi(string);
212 while (*string && isdigit((unsigned char)*string)) string++;
213 }
214 if (*string == 'd') {
215 int i;
216 string++;
217 for (i = 0; i <= DIFF_UNREASONABLE; i++)
218 if (*string == galaxies_diffchars[i])
219 params->diff = i;
220 if (*string) string++;
221 }
222 }
223
224 static char *encode_params(game_params *params, int full)
225 {
226 char str[80];
227 sprintf(str, "%dx%d", params->w, params->h);
228 if (full)
229 sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
230 return dupstr(str);
231 }
232
233 static config_item *game_configure(game_params *params)
234 {
235 config_item *ret;
236 char buf[80];
237
238 ret = snewn(4, config_item);
239
240 ret[0].name = "Width";
241 ret[0].type = C_STRING;
242 sprintf(buf, "%d", params->w);
243 ret[0].sval = dupstr(buf);
244 ret[0].ival = 0;
245
246 ret[1].name = "Height";
247 ret[1].type = C_STRING;
248 sprintf(buf, "%d", params->h);
249 ret[1].sval = dupstr(buf);
250 ret[1].ival = 0;
251
252 ret[2].name = "Difficulty";
253 ret[2].type = C_CHOICES;
254 ret[2].sval = DIFFCONFIG;
255 ret[2].ival = params->diff;
256
257 ret[3].name = NULL;
258 ret[3].type = C_END;
259 ret[3].sval = NULL;
260 ret[3].ival = 0;
261
262 return ret;
263 }
264
265 static game_params *custom_params(config_item *cfg)
266 {
267 game_params *ret = snew(game_params);
268
269 ret->w = atoi(cfg[0].sval);
270 ret->h = atoi(cfg[1].sval);
271 ret->diff = cfg[2].ival;
272
273 return ret;
274 }
275
276 static char *validate_params(game_params *params, int full)
277 {
278 if (params->w < 3 || params->h < 3)
279 return "Width and height must both be at least 3";
280 /*
281 * This shouldn't be able to happen at all, since decode_params
282 * and custom_params will never generate anything that isn't
283 * within range.
284 */
285 assert(params->diff <= DIFF_UNREASONABLE);
286
287 return NULL;
288 }
289
290 /* ----------------------------------------------------------
291 * Game utility functions.
292 */
293
294 static void add_dot(space *space) {
295 assert(!(space->flags & F_DOT));
296 space->flags |= F_DOT;
297 space->nassoc = 0;
298 }
299
300 static void remove_dot(space *space) {
301 assert(space->flags & F_DOT);
302 space->flags &= ~F_DOT;
303 }
304
305 static void remove_assoc(game_state *state, space *tile) {
306 if (tile->flags & F_TILE_ASSOC) {
307 SPACE(state, tile->dotx, tile->doty).nassoc--;
308 tile->flags &= ~F_TILE_ASSOC;
309 tile->dotx = -1;
310 tile->doty = -1;
311 }
312 }
313
314 static void add_assoc(game_state *state, space *tile, space *dot) {
315 remove_assoc(state, tile);
316
317 #ifdef STANDALONE_PICTURE_GENERATOR
318 if (picture)
319 assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
320 !(dot->flags & F_DOT_BLACK));
321 #endif
322 tile->flags |= F_TILE_ASSOC;
323 tile->dotx = dot->x;
324 tile->doty = dot->y;
325 dot->nassoc++;
326 /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
327 tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
328 }
329
330 static struct space *sp2dot(game_state *state, int x, int y)
331 {
332 struct space *sp = &SPACE(state, x, y);
333 if (!(sp->flags & F_TILE_ASSOC)) return NULL;
334 return &SPACE(state, sp->dotx, sp->doty);
335 }
336
337 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
338
339 static int game_can_format_as_text_now(game_params *params)
340 {
341 return TRUE;
342 }
343
344 static char *game_text_format(game_state *state)
345 {
346 int maxlen = (state->sx+1)*state->sy, x, y;
347 char *ret, *p;
348 space *sp;
349
350 ret = snewn(maxlen+1, char);
351 p = ret;
352
353 for (y = 0; y < state->sy; y++) {
354 for (x = 0; x < state->sx; x++) {
355 sp = &SPACE(state, x, y);
356 if (sp->flags & F_DOT)
357 *p++ = 'o';
358 #if 0
359 else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
360 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
361 (sp->flags & F_REACHABLE) ? 'R' : 'X';
362 #endif
363 else {
364 switch (sp->type) {
365 case s_tile:
366 if (sp->flags & F_TILE_ASSOC) {
367 space *dot = sp2dot(state, sp->x, sp->y);
368 if (dot->flags & F_DOT)
369 *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
370 else
371 *p++ = '?'; /* association with not-a-dot. */
372 } else
373 *p++ = ' ';
374 break;
375
376 case s_vertex:
377 *p++ = '+';
378 break;
379
380 case s_edge:
381 if (sp->flags & F_EDGE_SET)
382 *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
383 else
384 *p++ = ' ';
385 break;
386
387 default:
388 assert(!"shouldn't get here!");
389 }
390 }
391 }
392 *p++ = '\n';
393 }
394
395 assert(p - ret == maxlen);
396 *p = '\0';
397
398 return ret;
399 }
400
401 static void dbg_state(game_state *state)
402 {
403 #ifdef DEBUGGING
404 char *temp = game_text_format(state);
405 debug(("%s\n", temp));
406 sfree(temp);
407 #endif
408 }
409
410 /* Space-enumeration callbacks should all return 1 for 'progress made',
411 * -1 for 'impossible', and 0 otherwise. */
412 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
413
414 #define IMPOSSIBLE_QUITS 1
415
416 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
417 void *ctx, int startx, int starty)
418 {
419 int x, y, progress = 0, impossible = 0, ret;
420 space *sp;
421
422 for (y = starty; y < state->sy; y += 2) {
423 sp = &SPACE(state, startx, y);
424 for (x = startx; x < state->sx; x += 2) {
425 ret = cb(state, sp, ctx);
426 if (ret == -1) {
427 if (f & IMPOSSIBLE_QUITS) return -1;
428 impossible = -1;
429 } else if (ret == 1) {
430 progress = 1;
431 }
432 sp += 2;
433 }
434 }
435 return impossible ? -1 : progress;
436 }
437
438 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
439 void *ctx)
440 {
441 return foreach_sub(state, cb, f, ctx, 1, 1);
442 }
443
444 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
445 void *ctx)
446 {
447 int ret1, ret2;
448
449 ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
450 ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
451
452 if (ret1 == -1 || ret2 == -1) return -1;
453 return (ret1 || ret2) ? 1 : 0;
454 }
455
456 #if 0
457 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
458 void *ctx)
459 {
460 return foreach_sub(state, cb, f, ctx, 0, 0);
461 }
462 #endif
463
464 #if 0
465 static int is_same_assoc(game_state *state,
466 int x1, int y1, int x2, int y2)
467 {
468 struct space *s1, *s2;
469
470 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
471 return 0;
472
473 s1 = &SPACE(state, x1, y1);
474 s2 = &SPACE(state, x2, y2);
475 assert(s1->type == s_tile && s2->type == s_tile);
476 if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
477 s1->dotx == s2->dotx && s1->doty == s2->doty)
478 return 1;
479 return 0; /* 0 if not same or not both associated. */
480 }
481 #endif
482
483 #if 0
484 static int edges_into_vertex(game_state *state,
485 int x, int y)
486 {
487 int dx, dy, nx, ny, count = 0;
488
489 assert(SPACE(state, x, y).type == s_vertex);
490 for (dx = -1; dx <= 1; dx++) {
491 for (dy = -1; dy <= 1; dy++) {
492 if (dx != 0 && dy != 0) continue;
493 if (dx == 0 && dy == 0) continue;
494
495 nx = x+dx; ny = y+dy;
496 if (!INGRID(state, nx, ny)) continue;
497 assert(SPACE(state, nx, ny).type == s_edge);
498 if (SPACE(state, nx, ny).flags & F_EDGE_SET)
499 count++;
500 }
501 }
502 return count;
503 }
504 #endif
505
506 static struct space *space_opposite_dot(struct game_state *state,
507 struct space *sp, struct space *dot)
508 {
509 int dx, dy, tx, ty;
510 space *sp2;
511
512 dx = sp->x - dot->x;
513 dy = sp->y - dot->y;
514 tx = dot->x - dx;
515 ty = dot->y - dy;
516 if (!INGRID(state, tx, ty)) return NULL;
517
518 sp2 = &SPACE(state, tx, ty);
519 assert(sp2->type == sp->type);
520 return sp2;
521 }
522
523 static struct space *tile_opposite(struct game_state *state, struct space *sp)
524 {
525 struct space *dot;
526
527 assert(sp->flags & F_TILE_ASSOC);
528 dot = &SPACE(state, sp->dotx, sp->doty);
529 return space_opposite_dot(state, sp, dot);
530 }
531
532 static int dotfortile(game_state *state, space *tile, space *dot)
533 {
534 space *tile_opp = space_opposite_dot(state, tile, dot);
535
536 if (!tile_opp) return 0; /* opposite would be off grid */
537 if (tile_opp->flags & F_TILE_ASSOC &&
538 (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
539 return 0; /* opposite already associated with diff. dot */
540 return 1;
541 }
542
543 static void adjacencies(struct game_state *state, struct space *sp,
544 struct space **a1s, struct space **a2s)
545 {
546 int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
547 int n, x, y;
548
549 /* this function needs optimising. */
550
551 for (n = 0; n < 4; n++) {
552 x = sp->x+dxs[n];
553 y = sp->y+dys[n];
554
555 if (INGRID(state, x, y)) {
556 a1s[n] = &SPACE(state, x, y);
557
558 x += dxs[n]; y += dys[n];
559
560 if (INGRID(state, x, y))
561 a2s[n] = &SPACE(state, x, y);
562 else
563 a2s[n] = NULL;
564 } else {
565 a1s[n] = a2s[n] = NULL;
566 }
567 }
568 }
569
570 static int outline_tile_fordot(game_state *state, space *tile, int mark)
571 {
572 struct space *tadj[4], *eadj[4];
573 int i, didsth = 0, edge, same;
574
575 assert(tile->type == s_tile);
576 adjacencies(state, tile, eadj, tadj);
577 for (i = 0; i < 4; i++) {
578 if (!eadj[i]) continue;
579
580 edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
581 if (tadj[i]) {
582 if (!(tile->flags & F_TILE_ASSOC))
583 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
584 else
585 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
586 tile->dotx == tadj[i]->dotx &&
587 tile->doty == tadj[i]->doty) ? 1 : 0;
588 } else
589 same = 0;
590
591 if (!edge && !same) {
592 if (mark) eadj[i]->flags |= F_EDGE_SET;
593 didsth = 1;
594 } else if (edge && same) {
595 if (mark) eadj[i]->flags &= ~F_EDGE_SET;
596 didsth = 1;
597 }
598 }
599 return didsth;
600 }
601
602 static void tiles_from_edge(struct game_state *state,
603 struct space *sp, struct space **ts)
604 {
605 int xs[2], ys[2];
606
607 if (IS_VERTICAL_EDGE(sp->x)) {
608 xs[0] = sp->x-1; ys[0] = sp->y;
609 xs[1] = sp->x+1; ys[1] = sp->y;
610 } else {
611 xs[0] = sp->x; ys[0] = sp->y-1;
612 xs[1] = sp->x; ys[1] = sp->y+1;
613 }
614 ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
615 ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
616 }
617
618 /* Returns a move string for use by 'solve', including the initial
619 * 'S' if issolve is true. */
620 static char *diff_game(game_state *src, game_state *dest, int issolve)
621 {
622 int movelen = 0, movesize = 256, x, y, len;
623 char *move = snewn(movesize, char), buf[80], *sep = "";
624 char achar = issolve ? 'a' : 'A';
625 space *sps, *spd;
626
627 assert(src->sx == dest->sx && src->sy == dest->sy);
628
629 if (issolve) {
630 move[movelen++] = 'S';
631 sep = ";";
632 }
633 move[movelen] = '\0';
634 for (x = 0; x < src->sx; x++) {
635 for (y = 0; y < src->sy; y++) {
636 sps = &SPACE(src, x, y);
637 spd = &SPACE(dest, x, y);
638
639 assert(sps->type == spd->type);
640
641 len = 0;
642 if (sps->type == s_tile) {
643 if ((sps->flags & F_TILE_ASSOC) &&
644 (spd->flags & F_TILE_ASSOC)) {
645 if (sps->dotx != spd->dotx ||
646 sps->doty != spd->doty)
647 /* Both associated; change association, if different */
648 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
649 (int)achar, x, y, spd->dotx, spd->doty);
650 } else if (sps->flags & F_TILE_ASSOC)
651 /* Only src associated; remove. */
652 len = sprintf(buf, "%sU%d,%d", sep, x, y);
653 else if (spd->flags & F_TILE_ASSOC)
654 /* Only dest associated; add. */
655 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
656 (int)achar, x, y, spd->dotx, spd->doty);
657 } else if (sps->type == s_edge) {
658 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
659 /* edge flags are different; flip them. */
660 len = sprintf(buf, "%sE%d,%d", sep, x, y);
661 }
662 if (len) {
663 if (movelen + len >= movesize) {
664 movesize = movelen + len + 256;
665 move = sresize(move, movesize, char);
666 }
667 strcpy(move + movelen, buf);
668 movelen += len;
669 sep = ";";
670 }
671 }
672 }
673 debug(("diff_game src then dest:\n"));
674 dbg_state(src);
675 dbg_state(dest);
676 debug(("diff string %s\n", move));
677 return move;
678 }
679
680 /* Returns 1 if a dot here would not be too close to any other dots
681 * (and would avoid other game furniture). */
682 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
683 {
684 int bx = 0, by = 0, dx, dy;
685 space *adj;
686 #ifdef STANDALONE_PICTURE_GENERATOR
687 int col = -1;
688 #endif
689
690 switch (sp->type) {
691 case s_tile:
692 bx = by = 1; break;
693 case s_edge:
694 if (IS_VERTICAL_EDGE(sp->x)) {
695 bx = 2; by = 1;
696 } else {
697 bx = 1; by = 2;
698 }
699 break;
700 case s_vertex:
701 bx = by = 2; break;
702 }
703
704 for (dx = -bx; dx <= bx; dx++) {
705 for (dy = -by; dy <= by; dy++) {
706 if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
707
708 adj = &SPACE(state, sp->x+dx, sp->y+dy);
709
710 #ifdef STANDALONE_PICTURE_GENERATOR
711 /*
712 * Check that all the squares we're looking at have the
713 * same colour.
714 */
715 if (picture) {
716 if (adj->type == s_tile) {
717 int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
718 if (col < 0)
719 col = c;
720 if (c != col)
721 return 0; /* colour mismatch */
722 }
723 }
724 #endif
725
726 if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
727 return 0;
728
729 if (dx != 0 || dy != 0) {
730 /* Other than our own square, no dots nearby. */
731 if (adj->flags & (F_DOT))
732 return 0;
733 }
734
735 /* We don't want edges within our rectangle
736 * (but don't care about edges on the edge) */
737 if (abs(dx) < bx && abs(dy) < by &&
738 adj->flags & F_EDGE_SET)
739 return 0;
740 }
741 }
742 return 1;
743 }
744
745 /* ----------------------------------------------------------
746 * Game generation, structure creation, and descriptions.
747 */
748
749 static game_state *blank_game(int w, int h)
750 {
751 game_state *state = snew(game_state);
752 int x, y;
753
754 state->w = w;
755 state->h = h;
756
757 state->sx = (w*2)+1;
758 state->sy = (h*2)+1;
759 state->grid = snewn(state->sx * state->sy, struct space);
760 state->completed = state->used_solve = 0;
761
762 for (x = 0; x < state->sx; x++) {
763 for (y = 0; y < state->sy; y++) {
764 struct space *sp = &SPACE(state, x, y);
765 memset(sp, 0, sizeof(struct space));
766 sp->x = x;
767 sp->y = y;
768 if ((x % 2) == 0 && (y % 2) == 0)
769 sp->type = s_vertex;
770 else if ((x % 2) == 0 || (y % 2) == 0) {
771 sp->type = s_edge;
772 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
773 sp->flags |= F_EDGE_SET;
774 } else
775 sp->type = s_tile;
776 }
777 }
778
779 state->ndots = 0;
780 state->dots = NULL;
781
782 state->me = NULL; /* filled in by new_game. */
783 state->cdiff = -1;
784
785 return state;
786 }
787
788 static void game_update_dots(game_state *state)
789 {
790 int i, n, sz = state->sx * state->sy;
791
792 if (state->dots) sfree(state->dots);
793 state->ndots = 0;
794
795 for (i = 0; i < sz; i++) {
796 if (state->grid[i].flags & F_DOT) state->ndots++;
797 }
798 state->dots = snewn(state->ndots, space *);
799 n = 0;
800 for (i = 0; i < sz; i++) {
801 if (state->grid[i].flags & F_DOT)
802 state->dots[n++] = &state->grid[i];
803 }
804 }
805
806 static void clear_game(game_state *state, int cleardots)
807 {
808 int x, y;
809
810 /* don't erase edge flags around outline! */
811 for (x = 1; x < state->sx-1; x++) {
812 for (y = 1; y < state->sy-1; y++) {
813 if (cleardots)
814 SPACE(state, x, y).flags = 0;
815 else
816 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
817 }
818 }
819 if (cleardots) game_update_dots(state);
820 }
821
822 static game_state *dup_game(game_state *state)
823 {
824 game_state *ret = blank_game(state->w, state->h);
825
826 ret->completed = state->completed;
827 ret->used_solve = state->used_solve;
828
829 memcpy(ret->grid, state->grid,
830 ret->sx*ret->sy*sizeof(struct space));
831
832 game_update_dots(ret);
833
834 ret->me = state->me;
835 ret->cdiff = state->cdiff;
836
837 return ret;
838 }
839
840 static void free_game(game_state *state)
841 {
842 if (state->dots) sfree(state->dots);
843 sfree(state->grid);
844 sfree(state);
845 }
846
847 /* Game description is a sequence of letters representing the number
848 * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
849 * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
850 *
851 * I know it's a bitch to generate by hand, so we provide
852 * an edit mode.
853 */
854
855 static char *encode_game(game_state *state)
856 {
857 char *desc, *p;
858 int run, x, y, area;
859 unsigned int f;
860
861 area = (state->sx-2) * (state->sy-2);
862
863 desc = snewn(area, char);
864 p = desc;
865 run = 0;
866 for (y = 1; y < state->sy-1; y++) {
867 for (x = 1; x < state->sx-1; x++) {
868 f = SPACE(state, x, y).flags;
869
870 /* a/A is 0 spaces between, b/B is 1 space, ...
871 * y/Y is 24 spaces, za/zA is 25 spaces, ...
872 * It's easier to count from 0 because we then
873 * don't have to special-case the top left-hand corner
874 * (which could be a dot with 0 spaces before it). */
875 if (!(f & F_DOT))
876 run++;
877 else {
878 while (run > 24) {
879 *p++ = 'z';
880 run -= 25;
881 }
882 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
883 run = 0;
884 }
885 }
886 }
887 assert(p - desc < area);
888 *p++ = '\0';
889 desc = sresize(desc, p - desc, char);
890
891 return desc;
892 }
893
894 struct movedot {
895 int op;
896 space *olddot, *newdot;
897 };
898
899 enum { MD_CHECK, MD_MOVE };
900
901 static int movedot_cb(game_state *state, space *tile, void *vctx)
902 {
903 struct movedot *md = (struct movedot *)vctx;
904 space *newopp = NULL;
905
906 assert(tile->type == s_tile);
907 assert(md->olddot && md->newdot);
908
909 if (!(tile->flags & F_TILE_ASSOC)) return 0;
910 if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
911 return 0;
912
913 newopp = space_opposite_dot(state, tile, md->newdot);
914
915 switch (md->op) {
916 case MD_CHECK:
917 /* If the tile is associated with the old dot, check its
918 * opposite wrt the _new_ dot is empty or same assoc. */
919 if (!newopp) return -1; /* no new opposite */
920 if (newopp->flags & F_TILE_ASSOC) {
921 if (newopp->dotx != md->olddot->x ||
922 newopp->doty != md->olddot->y)
923 return -1; /* associated, but wrong dot. */
924 }
925 #ifdef STANDALONE_PICTURE_GENERATOR
926 if (picture) {
927 /*
928 * Reject if either tile and the dot don't match in colour.
929 */
930 if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
931 !(md->newdot->flags & F_DOT_BLACK))
932 return -1;
933 if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
934 !(md->newdot->flags & F_DOT_BLACK))
935 return -1;
936 }
937 #endif
938 break;
939
940 case MD_MOVE:
941 /* Move dot associations: anything that was associated
942 * with the old dot, and its opposite wrt the new dot,
943 * become associated with the new dot. */
944 assert(newopp);
945 debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
946 tile->x, tile->y, newopp->x, newopp->y,
947 md->newdot->x, md->newdot->y));
948 add_assoc(state, tile, md->newdot);
949 add_assoc(state, newopp, md->newdot);
950 return 1; /* we did something! */
951 }
952 return 0;
953 }
954
955 /* For the given dot, first see if we could expand it into all the given
956 * extra spaces (by checking for empty spaces on the far side), and then
957 * see if we can move the dot to shift the CoG to include the new spaces.
958 */
959 static int dot_expand_or_move(game_state *state, space *dot,
960 space **toadd, int nadd)
961 {
962 space *tileopp;
963 int i, ret, nnew, cx, cy;
964 struct movedot md;
965
966 debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
967 nadd, dot->x, dot->y));
968 for (i = 0; i < nadd; i++)
969 debug(("dot_expand_or_move: dot %d,%d\n",
970 toadd[i]->x, toadd[i]->y));
971 assert(dot->flags & F_DOT);
972
973 #ifdef STANDALONE_PICTURE_GENERATOR
974 if (picture) {
975 /*
976 * Reject the expansion totally if any of the new tiles are
977 * the wrong colour.
978 */
979 for (i = 0; i < nadd; i++) {
980 if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
981 !(dot->flags & F_DOT_BLACK))
982 return 0;
983 }
984 }
985 #endif
986
987 /* First off, could we just expand the current dot's tile to cover
988 * the space(s) passed in and their opposites? */
989 for (i = 0; i < nadd; i++) {
990 tileopp = space_opposite_dot(state, toadd[i], dot);
991 if (!tileopp) goto noexpand;
992 if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
993 #ifdef STANDALONE_PICTURE_GENERATOR
994 if (picture) {
995 /*
996 * The opposite tiles have to be the right colour as well.
997 */
998 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
999 !(dot->flags & F_DOT_BLACK))
1000 goto noexpand;
1001 }
1002 #endif
1003 }
1004 /* OK, all spaces have valid empty opposites: associate spaces and
1005 * opposites with our dot. */
1006 for (i = 0; i < nadd; i++) {
1007 tileopp = space_opposite_dot(state, toadd[i], dot);
1008 add_assoc(state, toadd[i], dot);
1009 add_assoc(state, tileopp, dot);
1010 debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1011 toadd[i]->x, toadd[i]->y,
1012 tileopp->x, tileopp->y,
1013 dot->x, dot->y));
1014 dbg_state(state);
1015 }
1016 return 1;
1017
1018 noexpand:
1019 /* Otherwise, try to move dot so as to encompass given spaces: */
1020 /* first, calculate the 'centre of gravity' of the new dot. */
1021 nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1022 cx = dot->x * dot->nassoc;
1023 cy = dot->y * dot->nassoc;
1024 for (i = 0; i < nadd; i++) {
1025 cx += toadd[i]->x;
1026 cy += toadd[i]->y;
1027 }
1028 /* If the CoG isn't a whole number, it's not possible. */
1029 if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1030 debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1031 dot->x, dot->y));
1032 return 0;
1033 }
1034 cx /= nnew; cy /= nnew;
1035
1036 /* Check whether all spaces in the old tile would have a good
1037 * opposite wrt the new dot. */
1038 md.olddot = dot;
1039 md.newdot = &SPACE(state, cx, cy);
1040 md.op = MD_CHECK;
1041 ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1042 if (ret == -1) {
1043 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1044 dot->x, dot->y));
1045 return 0;
1046 }
1047 /* Also check whether all spaces we're adding would have a good
1048 * opposite wrt the new dot. */
1049 for (i = 0; i < nadd; i++) {
1050 tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1051 if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1052 (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1053 tileopp = NULL;
1054 }
1055 if (!tileopp) {
1056 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1057 dot->x, dot->y));
1058 return 0;
1059 }
1060 #ifdef STANDALONE_PICTURE_GENERATOR
1061 if (picture) {
1062 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1063 !(dot->flags & F_DOT_BLACK))
1064 return 0;
1065 }
1066 #endif
1067 }
1068
1069 /* If we've got here, we're ok. First, associate all of 'toadd'
1070 * with the _old_ dot (so they'll get fixed up, with their opposites,
1071 * in the next step). */
1072 for (i = 0; i < nadd; i++) {
1073 debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1074 toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1075 add_assoc(state, toadd[i], dot);
1076 }
1077
1078 /* Finally, move the dot and fix up all the old associations. */
1079 debug(("Moving dot at %d,%d to %d,%d\n",
1080 dot->x, dot->y, md.newdot->x, md.newdot->y));
1081 {
1082 #ifdef STANDALONE_PICTURE_GENERATOR
1083 int f = dot->flags & F_DOT_BLACK;
1084 #endif
1085 remove_dot(dot);
1086 add_dot(md.newdot);
1087 #ifdef STANDALONE_PICTURE_GENERATOR
1088 md.newdot->flags |= f;
1089 #endif
1090 }
1091
1092 md.op = MD_MOVE;
1093 ret = foreach_tile(state, movedot_cb, 0, &md);
1094 assert(ret == 1);
1095 dbg_state(state);
1096
1097 return 1;
1098 }
1099
1100 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1101 #define MAX_TOADD 4
1102 #define MAX_OUTSIDE 8
1103
1104 #define MAX_TILE_PERC 20
1105
1106 static int generate_try_block(game_state *state, random_state *rs,
1107 int x1, int y1, int x2, int y2)
1108 {
1109 int x, y, nadd = 0, nout = 0, i, maxsz;
1110 space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1111
1112 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1113
1114 /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1115 * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1116 * nothing >40 tiles. */
1117 maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1118 debug(("generate_try_block, maxsz %d\n", maxsz));
1119
1120 /* Make a static list of the spaces; if any space is already
1121 * associated then quit immediately. */
1122 for (x = x1; x <= x2; x += 2) {
1123 for (y = y1; y <= y2; y += 2) {
1124 assert(nadd < MAX_TOADD);
1125 sp = &SPACE(state, x, y);
1126 assert(sp->type == s_tile);
1127 if (sp->flags & F_TILE_ASSOC) return 0;
1128 toadd[nadd++] = sp;
1129 }
1130 }
1131
1132 /* Make a list of the spaces outside of our block, and shuffle it. */
1133 #define OUTSIDE(x, y) do { \
1134 if (INGRID(state, (x), (y))) { \
1135 assert(nout < MAX_OUTSIDE); \
1136 outside[nout++] = &SPACE(state, (x), (y)); \
1137 } \
1138 } while(0)
1139 for (x = x1; x <= x2; x += 2) {
1140 OUTSIDE(x, y1-2);
1141 OUTSIDE(x, y2+2);
1142 }
1143 for (y = y1; y <= y2; y += 2) {
1144 OUTSIDE(x1-2, y);
1145 OUTSIDE(x2+2, y);
1146 }
1147 shuffle(outside, nout, sizeof(space *), rs);
1148
1149 for (i = 0; i < nout; i++) {
1150 if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1151 dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1152 if (dot->nassoc >= maxsz) {
1153 debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1154 dot->x, dot->y, dot->nassoc));
1155 continue;
1156 }
1157 if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1158 }
1159 return 0;
1160 }
1161
1162 #ifdef STANDALONE_SOLVER
1163 int maxtries;
1164 #define MAXTRIES maxtries
1165 #else
1166 #define MAXTRIES 50
1167 #endif
1168
1169 static int solver_obvious_dot(game_state *state,space *dot);
1170
1171 #define GP_DOTS 1
1172
1173 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1174 int perc, unsigned int flags)
1175 {
1176 int sz = state->sx*state->sy, nspc, i, ret;
1177
1178 shuffle(scratch, sz, sizeof(int), rs);
1179
1180 /* This bug took me a, er, little while to track down. On PalmOS,
1181 * which has 16-bit signed ints, puzzles over about 9x9 started
1182 * failing to generate because the nspc calculation would start
1183 * to overflow, causing the dots not to be filled in properly. */
1184 nspc = (int)(((long)perc * (long)sz) / 100L);
1185 debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1186 perc, nspc, state->sx, state->sy, flags));
1187
1188 for (i = 0; i < nspc; i++) {
1189 space *sp = &state->grid[scratch[i]];
1190 int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1191
1192 if (sp->type == s_edge) {
1193 if (IS_VERTICAL_EDGE(sp->x)) {
1194 x1--; x2++;
1195 } else {
1196 y1--; y2++;
1197 }
1198 }
1199 if (sp->type != s_vertex) {
1200 /* heuristic; expanding from vertices tends to generate lots of
1201 * too-big regions of tiles. */
1202 if (generate_try_block(state, rs, x1, y1, x2, y2))
1203 continue; /* we expanded successfully. */
1204 }
1205
1206 if (!(flags & GP_DOTS)) continue;
1207
1208 if ((sp->type == s_edge) && (i % 2)) {
1209 debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1210 continue;
1211 }
1212
1213 /* If we've got here we might want to put a dot down. Check
1214 * if we can, and add one if so. */
1215 if (dot_is_possible(state, sp, 0)) {
1216 add_dot(sp);
1217 #ifdef STANDALONE_PICTURE_GENERATOR
1218 if (picture) {
1219 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1220 sp->flags |= F_DOT_BLACK;
1221 }
1222 #endif
1223 ret = solver_obvious_dot(state, sp);
1224 assert(ret != -1);
1225 debug(("Added dot (and obvious associations) at %d,%d\n",
1226 sp->x, sp->y));
1227 dbg_state(state);
1228 }
1229 }
1230 dbg_state(state);
1231 }
1232
1233 static int check_complete(game_state *state, int *dsf, int *colours);
1234 static int solver_state(game_state *state, int maxdiff);
1235
1236 static char *new_game_desc(game_params *params, random_state *rs,
1237 char **aux, int interactive)
1238 {
1239 game_state *state = blank_game(params->w, params->h), *copy;
1240 char *desc;
1241 int *scratch, sz = state->sx*state->sy, i;
1242 int diff, ntries = 0, cc;
1243
1244 /* Random list of squares to try and process, one-by-one. */
1245 scratch = snewn(sz, int);
1246 for (i = 0; i < sz; i++) scratch[i] = i;
1247
1248 generate:
1249 clear_game(state, 1);
1250 ntries++;
1251
1252 /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1253 /* generate_pass(state, rs, scratch, 100, 0); */
1254 generate_pass(state, rs, scratch, 100, GP_DOTS);
1255
1256 game_update_dots(state);
1257
1258 #ifdef DEBUGGING
1259 {
1260 char *tmp = encode_game(state);
1261 debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1262 sfree(tmp);
1263 }
1264 #endif
1265
1266 for (i = 0; i < state->sx*state->sy; i++)
1267 if (state->grid[i].type == s_tile)
1268 outline_tile_fordot(state, &state->grid[i], TRUE);
1269 cc = check_complete(state, NULL, NULL);
1270 assert(cc);
1271
1272 copy = dup_game(state);
1273 clear_game(copy, 0);
1274 dbg_state(copy);
1275 diff = solver_state(copy, params->diff);
1276 free_game(copy);
1277
1278 assert(diff != DIFF_IMPOSSIBLE);
1279 if (diff != params->diff) {
1280 /*
1281 * We'll grudgingly accept a too-easy puzzle, but we must
1282 * _not_ permit a too-hard one (one which the solver
1283 * couldn't handle at all).
1284 */
1285 if (diff > params->diff ||
1286 ntries < MAXTRIES) goto generate;
1287 }
1288
1289 #ifdef STANDALONE_PICTURE_GENERATOR
1290 /*
1291 * Postprocessing pass to prevent excessive numbers of adjacent
1292 * singletons. Iterate over all edges in random shuffled order;
1293 * for each edge that separates two regions, investigate
1294 * whether removing that edge and merging the regions would
1295 * still yield a valid and soluble puzzle. (The two regions
1296 * must also be the same colour, of course.) If so, do it.
1297 *
1298 * This postprocessing pass is slow (due to repeated solver
1299 * invocations), and seems to be unnecessary during normal
1300 * unconstrained game generation. However, when generating a
1301 * game under colour constraints, excessive singletons seem to
1302 * turn up more often, so it's worth doing this.
1303 */
1304 {
1305 int *posns, nposns;
1306 int i, j, newdiff;
1307 game_state *copy2;
1308
1309 nposns = params->w * (params->h+1) + params->h * (params->w+1);
1310 posns = snewn(nposns, int);
1311 for (i = j = 0; i < state->sx*state->sy; i++)
1312 if (state->grid[i].type == s_edge)
1313 posns[j++] = i;
1314 assert(j == nposns);
1315
1316 shuffle(posns, nposns, sizeof(*posns), rs);
1317
1318 for (i = 0; i < nposns; i++) {
1319 int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1320 space *s0, *s1, *ts, *d0, *d1, *dn;
1321 int ok;
1322
1323 /* Coordinates of edge space */
1324 x = posns[i] % state->sx;
1325 y = posns[i] / state->sx;
1326
1327 /* Coordinates of square spaces on either side of edge */
1328 x0 = ((x+1) & ~1) - 1; /* round down to next odd number */
1329 y0 = ((y+1) & ~1) - 1;
1330 x1 = 2*x-x0; /* and reflect about x to get x1 */
1331 y1 = 2*y-y0;
1332
1333 if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1334 continue; /* outermost edge of grid */
1335 s0 = &SPACE(state, x0, y0);
1336 s1 = &SPACE(state, x1, y1);
1337 assert(s0->type == s_tile && s1->type == s_tile);
1338
1339 if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1340 continue; /* tiles _already_ owned by same dot */
1341
1342 d0 = &SPACE(state, s0->dotx, s0->doty);
1343 d1 = &SPACE(state, s1->dotx, s1->doty);
1344
1345 if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1346 continue; /* different colours: cannot merge */
1347
1348 /*
1349 * Work out where the centre of gravity of the new
1350 * region would be.
1351 */
1352 cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1353 cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1354 cn = d0->nassoc + d1->nassoc;
1355 if (cx % cn || cy % cn)
1356 continue; /* CoG not at integer coordinates */
1357 cx /= cn;
1358 cy /= cn;
1359 assert(INUI(state, cx, cy));
1360
1361 /*
1362 * Ensure that the CoG would actually be _in_ the new
1363 * region, by verifying that all its surrounding tiles
1364 * belong to one or other of our two dots.
1365 */
1366 cx0 = ((cx+1) & ~1) - 1; /* round down to next odd number */
1367 cy0 = ((cy+1) & ~1) - 1;
1368 cx1 = 2*cx-cx0; /* and reflect about cx to get cx1 */
1369 cy1 = 2*cy-cy0;
1370 ok = TRUE;
1371 for (ty = cy0; ty <= cy1; ty += 2)
1372 for (tx = cx0; tx <= cx1; tx += 2) {
1373 ts = &SPACE(state, tx, ty);
1374 assert(ts->type == s_tile);
1375 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1376 (ts->dotx != d1->x || ts->doty != d1->y))
1377 ok = FALSE;
1378 }
1379 if (!ok)
1380 continue;
1381
1382 /*
1383 * Verify that for every tile in either source region,
1384 * that tile's image in the new CoG is also in one of
1385 * the two source regions.
1386 */
1387 for (ty = 1; ty < state->sy; ty += 2) {
1388 for (tx = 1; tx < state->sx; tx += 2) {
1389 int tx1, ty1;
1390
1391 ts = &SPACE(state, tx, ty);
1392 assert(ts->type == s_tile);
1393 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1394 (ts->dotx != d1->x || ts->doty != d1->y))
1395 continue; /* not part of these tiles anyway */
1396 tx1 = 2*cx-tx;
1397 ty1 = 2*cy-ty;
1398 if (!INGRID(state, tx1, ty1)) {
1399 ok = FALSE;
1400 break;
1401 }
1402 ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1403 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1404 (ts->dotx != d1->x || ts->doty != d1->y)) {
1405 ok = FALSE;
1406 break;
1407 }
1408 }
1409 if (!ok)
1410 break;
1411 }
1412 if (!ok)
1413 continue;
1414
1415 /*
1416 * Now we're clear to attempt the merge. We take a copy
1417 * of the game state first, so we can revert it easily
1418 * if the resulting puzzle turns out to have become
1419 * insoluble.
1420 */
1421 copy2 = dup_game(state);
1422
1423 remove_dot(d0);
1424 remove_dot(d1);
1425 dn = &SPACE(state, cx, cy);
1426 add_dot(dn);
1427 dn->flags |= (d0->flags & F_DOT_BLACK);
1428 for (ty = 1; ty < state->sy; ty += 2) {
1429 for (tx = 1; tx < state->sx; tx += 2) {
1430 ts = &SPACE(state, tx, ty);
1431 assert(ts->type == s_tile);
1432 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1433 (ts->dotx != d1->x || ts->doty != d1->y))
1434 continue; /* not part of these tiles anyway */
1435 add_assoc(state, ts, dn);
1436 }
1437 }
1438
1439 copy = dup_game(state);
1440 clear_game(copy, 0);
1441 dbg_state(copy);
1442 newdiff = solver_state(copy, params->diff);
1443 free_game(copy);
1444 if (diff == newdiff) {
1445 /* Still just as soluble. Let the merge stand. */
1446 free_game(copy2);
1447 } else {
1448 /* Became insoluble. Revert. */
1449 free_game(state);
1450 state = copy2;
1451 }
1452 }
1453 }
1454 #endif
1455
1456 desc = encode_game(state);
1457 #ifndef STANDALONE_SOLVER
1458 debug(("new_game_desc generated: \n"));
1459 dbg_state(state);
1460 #endif
1461
1462 free_game(state);
1463 sfree(scratch);
1464
1465 return desc;
1466 }
1467
1468 static int solver_obvious(game_state *state);
1469
1470 static int dots_too_close(game_state *state)
1471 {
1472 /* Quick-and-dirty check, using half the solver:
1473 * solver_obvious will only fail if the dots are
1474 * too close together, so dot-proximity associations
1475 * overlap. */
1476 game_state *tmp = dup_game(state);
1477 int ret = solver_obvious(tmp);
1478 free_game(tmp);
1479 return (ret == -1) ? 1 : 0;
1480 }
1481
1482 static game_state *load_game(game_params *params, char *desc,
1483 char **why_r)
1484 {
1485 game_state *state = blank_game(params->w, params->h);
1486 char *why = NULL;
1487 int i, x, y, n;
1488 unsigned int df;
1489
1490 i = 0;
1491 while (*desc) {
1492 n = *desc++;
1493 if (n == 'z') {
1494 i += 25;
1495 continue;
1496 }
1497 if (n >= 'a' && n <= 'y') {
1498 i += n - 'a';
1499 df = 0;
1500 } else if (n >= 'A' && n <= 'Y') {
1501 i += n - 'A';
1502 df = F_DOT_BLACK;
1503 } else {
1504 why = "Invalid characters in game description"; goto fail;
1505 }
1506 /* if we got here we incremented i and have a dot to add. */
1507 y = (i / (state->sx-2)) + 1;
1508 x = (i % (state->sx-2)) + 1;
1509 if (!INUI(state, x, y)) {
1510 why = "Too much data to fit in grid"; goto fail;
1511 }
1512 add_dot(&SPACE(state, x, y));
1513 SPACE(state, x, y).flags |= df;
1514 i++;
1515 }
1516 game_update_dots(state);
1517
1518 if (dots_too_close(state)) {
1519 why = "Dots too close together"; goto fail;
1520 }
1521
1522 return state;
1523
1524 fail:
1525 free_game(state);
1526 if (why_r) *why_r = why;
1527 return NULL;
1528 }
1529
1530 static char *validate_desc(game_params *params, char *desc)
1531 {
1532 char *why = NULL;
1533 game_state *dummy = load_game(params, desc, &why);
1534 if (dummy) {
1535 free_game(dummy);
1536 assert(!why);
1537 } else
1538 assert(why);
1539 return why;
1540 }
1541
1542 static game_state *new_game(midend *me, game_params *params, char *desc)
1543 {
1544 game_state *state = load_game(params, desc, NULL);
1545 if (!state) {
1546 assert("Unable to load ?validated game.");
1547 return NULL;
1548 }
1549 #ifdef EDITOR
1550 state->me = me;
1551 #endif
1552 return state;
1553 }
1554
1555 /* ----------------------------------------------------------
1556 * Solver and all its little wizards.
1557 */
1558
1559 int solver_recurse_depth;
1560
1561 typedef struct solver_ctx {
1562 game_state *state;
1563 int sz; /* state->sx * state->sy */
1564 space **scratch; /* size sz */
1565
1566 } solver_ctx;
1567
1568 static solver_ctx *new_solver(game_state *state)
1569 {
1570 solver_ctx *sctx = snew(solver_ctx);
1571 sctx->state = state;
1572 sctx->sz = state->sx*state->sy;
1573 sctx->scratch = snewn(sctx->sz, space *);
1574 return sctx;
1575 }
1576
1577 static void free_solver(solver_ctx *sctx)
1578 {
1579 sfree(sctx->scratch);
1580 sfree(sctx);
1581 }
1582
1583 /* Solver ideas so far:
1584 *
1585 * For any empty space, work out how many dots it could associate
1586 * with:
1587 * it needs line-of-sight
1588 * it needs an empty space on the far side
1589 * any adjacent lines need corresponding line possibilities.
1590 */
1591
1592 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1593 *
1594 * Solver techniques, in order of difficulty:
1595 * obvious adjacency to dots
1596 * transferring tiles to opposite side
1597 * transferring lines to opposite side
1598 * one possible dot for a given tile based on opposite availability
1599 * tile with 3 definite edges next to an associated tile must associate
1600 with same dot.
1601 *
1602 * one possible dot for a given tile based on line-of-sight
1603 */
1604
1605 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1606 const char *why)
1607 {
1608 space *dot, *tile_opp;
1609
1610 dot = &SPACE(state, dx, dy);
1611 tile_opp = space_opposite_dot(state, tile, dot);
1612
1613 assert(tile->type == s_tile);
1614 if (tile->flags & F_TILE_ASSOC) {
1615 if ((tile->dotx != dx) || (tile->doty != dy)) {
1616 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1617 "already --> %d,%d.\n",
1618 solver_recurse_depth*4, "",
1619 tile->x, tile->y, dx, dy, why,
1620 tile->dotx, tile->doty));
1621 return -1;
1622 }
1623 return 0; /* no-op */
1624 }
1625 if (!tile_opp) {
1626 solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1627 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1628 return -1;
1629 }
1630 if (tile_opp->flags & F_TILE_ASSOC &&
1631 (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1632 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1633 "opposite already --> %d,%d.\n",
1634 solver_recurse_depth*4, "",
1635 tile->x, tile->y, dx, dy, why,
1636 tile_opp->dotx, tile_opp->doty));
1637 return -1;
1638 }
1639
1640 add_assoc(state, tile, dot);
1641 add_assoc(state, tile_opp, dot);
1642 solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1643 solver_recurse_depth*4, "",
1644 tile->x, tile->y,dx, dy, why));
1645 solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1646 solver_recurse_depth*4, "",
1647 tile_opp->x, tile_opp->y, dx, dy, why));
1648 return 1;
1649 }
1650
1651 static int solver_obvious_dot(game_state *state, space *dot)
1652 {
1653 int dx, dy, ret, didsth = 0;
1654 space *tile;
1655
1656 debug(("%*ssolver_obvious_dot for %d,%d.\n",
1657 solver_recurse_depth*4, "", dot->x, dot->y));
1658
1659 assert(dot->flags & F_DOT);
1660 for (dx = -1; dx <= 1; dx++) {
1661 for (dy = -1; dy <= 1; dy++) {
1662 if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1663
1664 tile = &SPACE(state, dot->x+dx, dot->y+dy);
1665 if (tile->type == s_tile) {
1666 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1667 "next to dot");
1668 if (ret < 0) return -1;
1669 if (ret > 0) didsth = 1;
1670 }
1671 }
1672 }
1673 return didsth;
1674 }
1675
1676 static int solver_obvious(game_state *state)
1677 {
1678 int i, didsth = 0, ret;
1679
1680 debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1681
1682 for (i = 0; i < state->ndots; i++) {
1683 ret = solver_obvious_dot(state, state->dots[i]);
1684 if (ret < 0) return -1;
1685 if (ret > 0) didsth = 1;
1686 }
1687 return didsth;
1688 }
1689
1690 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1691 {
1692 int didsth = 0, n, dx, dy;
1693 space *tiles[2], *tile_opp, *edge_opp;
1694
1695 assert(edge->type == s_edge);
1696
1697 tiles_from_edge(state, edge, tiles);
1698
1699 /* if tiles[0] && tiles[1] && they're both associated
1700 * and they're both associated with different dots,
1701 * ensure the line is set. */
1702 if (!(edge->flags & F_EDGE_SET) &&
1703 tiles[0] && tiles[1] &&
1704 (tiles[0]->flags & F_TILE_ASSOC) &&
1705 (tiles[1]->flags & F_TILE_ASSOC) &&
1706 (tiles[0]->dotx != tiles[1]->dotx ||
1707 tiles[0]->doty != tiles[1]->doty)) {
1708 /* No edge, but the two adjacent tiles are both
1709 * associated with different dots; add the edge. */
1710 solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1711 solver_recurse_depth*4, "", edge->x, edge->y));
1712 edge->flags |= F_EDGE_SET;
1713 didsth = 1;
1714 }
1715
1716 if (!(edge->flags & F_EDGE_SET)) return didsth;
1717 for (n = 0; n < 2; n++) {
1718 if (!tiles[n]) continue;
1719 assert(tiles[n]->type == s_tile);
1720 if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1721
1722 tile_opp = tile_opposite(state, tiles[n]);
1723 if (!tile_opp) {
1724 solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1725 " with no opposite.\n",
1726 solver_recurse_depth*4, "",
1727 edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1728 /* edge of tile has no opposite edge (off grid?);
1729 * this is impossible. */
1730 return -1;
1731 }
1732
1733 dx = tiles[n]->x - edge->x;
1734 dy = tiles[n]->y - edge->y;
1735 assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1736 edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1737 if (!(edge_opp->flags & F_EDGE_SET)) {
1738 solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1739 solver_recurse_depth*4, "",
1740 tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1741 edge_opp->flags |= F_EDGE_SET;
1742 didsth = 1;
1743 }
1744 }
1745 return didsth;
1746 }
1747
1748 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1749 {
1750 int n, eset, ret;
1751 struct space *edgeadj[4], *tileadj[4];
1752 int dotx, doty;
1753
1754 assert(tile->type == s_tile);
1755 if (tile->flags & F_TILE_ASSOC) return 0;
1756
1757 adjacencies(state, tile, edgeadj, tileadj);
1758
1759 /* Empty tile. If each edge is either set, or associated with
1760 * the same dot, we must also associate with dot. */
1761 eset = 0; dotx = -1; doty = -1;
1762 for (n = 0; n < 4; n++) {
1763 assert(edgeadj[n]);
1764 assert(edgeadj[n]->type == s_edge);
1765 if (edgeadj[n]->flags & F_EDGE_SET) {
1766 eset++;
1767 } else {
1768 assert(tileadj[n]);
1769 assert(tileadj[n]->type == s_tile);
1770
1771 /* If an adjacent tile is empty we can't make any deductions.*/
1772 if (!(tileadj[n]->flags & F_TILE_ASSOC))
1773 return 0;
1774
1775 /* If an adjacent tile is assoc. with a different dot
1776 * we can't make any deductions. */
1777 if (dotx != -1 && doty != -1 &&
1778 (tileadj[n]->dotx != dotx ||
1779 tileadj[n]->doty != doty))
1780 return 0;
1781
1782 dotx = tileadj[n]->dotx;
1783 doty = tileadj[n]->doty;
1784 }
1785 }
1786 if (eset == 4) {
1787 solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1788 solver_recurse_depth*4, "",
1789 tile->x, tile->y));
1790 return -1;
1791 }
1792 assert(dotx != -1 && doty != -1);
1793
1794 ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1795 if (ret == -1) return -1;
1796 assert(ret != 0); /* really should have done something. */
1797
1798 return 1;
1799 }
1800
1801 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1802 *
1803 * The solver_ctx already stores a list of dots: the algorithm proceeds by
1804 * expanding outwards from each dot in turn, expanding first to the boundary
1805 * of its currently-connected tile and then to all empty tiles that could see
1806 * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1807 *
1808 * Expansion will happen by (symmetrically opposite) pairs of squares; if
1809 * a square hasn't an opposite number there's no point trying to expand through
1810 * it. Empty tiles will therefore also be tagged in pairs.
1811 *
1812 * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1813 * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1814 * because we're looking for single-dot possibilities.
1815 *
1816 * Once we've gone through all the dots, any which still have a 'can see dot'
1817 * tag get associated with that dot (because it must have been the only one);
1818 * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1819 * marked.
1820 *
1821 * The expansion will happen each time with a stored list of (space *) pairs,
1822 * rather than a mark-and-sweep idea; that's horrifically inefficient.
1823 *
1824 * expansion algorithm:
1825 *
1826 * * allocate list of (space *) the size of s->sx*s->sy.
1827 * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1828 *
1829 * clear second grid (flags = 0, all dotx and doty = 0)
1830 * flags: F_REACHABLE, F_MULTIPLE
1831 *
1832 *
1833 * * for each dot, start with one pair of tiles that are associated with it --
1834 * * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1835 * * edge --> (adj1, adj2)
1836 * * tile --> (tile, tile) ???
1837 * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1838 * * add two tiles to start of list.
1839 *
1840 * set start = 0, end = next = 2
1841 *
1842 * from (start to end-1, step 2) {
1843 * * we have two tiles (t1, t2), opposites wrt our dot.
1844 * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1845 * * work out at2 as the opposite to at1
1846 * * assert at1 and at2 have the same F_MARK values.
1847 * * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1848 * * if either are associated with a different dot
1849 * * mark both with F_MARK (so we ignore them later)
1850 * * otherwise (assoc. with our dot, or empty):
1851 * * mark both with F_MARK
1852 * * add their space * values to the end of the list, set next += 2.
1853 * }
1854 *
1855 * if (end == next)
1856 * * we didn't add any new squares; exit the loop.
1857 * else
1858 * * set start = next+1, end = next. go round again
1859 *
1860 * We've finished expanding from the dot. Now, for each square we have
1861 * in our list (--> each square with F_MARK):
1862 * * if the tile is empty:
1863 * * if F_REACHABLE was already set
1864 * * set F_MULTIPLE
1865 * * otherwise
1866 * * set F_REACHABLE, set dotx and doty to our dot.
1867 *
1868 * Then, continue the whole thing for each dot in turn.
1869 *
1870 * Once we've done for each dot, go through the entire grid looking for
1871 * empty tiles: for each empty tile:
1872 * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1873 * if !F_REACHABLE, return as impossible.
1874 *
1875 */
1876
1877 /* Returns 1 if this tile is either already associated with this dot,
1878 * or blank. */
1879 static int solver_expand_checkdot(space *tile, space *dot)
1880 {
1881 if (!(tile->flags & F_TILE_ASSOC)) return 1;
1882 if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1883 return 0;
1884 }
1885
1886 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1887 {
1888 int i, j, x, y, start, end, next;
1889 space *sp;
1890
1891 /* Clear the grid of the (space) flags we'll use. */
1892
1893 /* This is well optimised; analysis showed that:
1894 for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1895 took up ~85% of the total function time! */
1896 for (y = 1; y < state->sy; y += 2) {
1897 sp = &SPACE(state, 1, y);
1898 for (x = 1; x < state->sx; x += 2, sp += 2)
1899 sp->flags &= ~F_MARK;
1900 }
1901
1902 /* Seed the list of marked squares with two that must be associated
1903 * with our dot (possibly the same space) */
1904 if (dot->type == s_tile) {
1905 sctx->scratch[0] = sctx->scratch[1] = dot;
1906 } else if (dot->type == s_edge) {
1907 tiles_from_edge(state, dot, sctx->scratch);
1908 } else if (dot->type == s_vertex) {
1909 /* pick two of the opposite ones arbitrarily. */
1910 sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1911 sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1912 }
1913 assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1914 assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1915
1916 sctx->scratch[0]->flags |= F_MARK;
1917 sctx->scratch[1]->flags |= F_MARK;
1918
1919 debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1920 solver_recurse_depth*4, "", dot->x, dot->y,
1921 sctx->scratch[0]->x, sctx->scratch[0]->y,
1922 sctx->scratch[1]->x, sctx->scratch[1]->y));
1923
1924 start = 0; end = 2; next = 2;
1925
1926 expand:
1927 debug(("%*sexpand: start %d, end %d, next %d\n",
1928 solver_recurse_depth*4, "", start, end, next));
1929 for (i = start; i < end; i += 2) {
1930 space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1931 space *edges[4], *tileadj[4], *tileadj2;
1932
1933 adjacencies(state, t1, edges, tileadj);
1934
1935 for (j = 0; j < 4; j++) {
1936 assert(edges[j]);
1937 if (edges[j]->flags & F_EDGE_SET) continue;
1938 assert(tileadj[j]);
1939
1940 if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1941
1942 /* We have a tile adjacent to t1; find its opposite. */
1943 tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1944 if (!tileadj2) {
1945 debug(("%*sMarking %d,%d, no opposite.\n",
1946 solver_recurse_depth*4, "",
1947 tileadj[j]->x, tileadj[j]->y));
1948 tileadj[j]->flags |= F_MARK;
1949 continue; /* no opposite, so mark for next time. */
1950 }
1951 /* If the tile had an opposite we should have either seen both of
1952 * these, or neither of these, before. */
1953 assert(!(tileadj2->flags & F_MARK));
1954
1955 if (solver_expand_checkdot(tileadj[j], dot) &&
1956 solver_expand_checkdot(tileadj2, dot)) {
1957 /* Both tiles could associate with this dot; add them to
1958 * our list. */
1959 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
1960 solver_recurse_depth*4, "",
1961 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1962 sctx->scratch[next++] = tileadj[j];
1963 sctx->scratch[next++] = tileadj2;
1964 }
1965 /* Either way, we've seen these tiles already so mark them. */
1966 debug(("%*sMarking %d,%d and %d,%d.\n",
1967 solver_recurse_depth*4, "",
1968 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1969 tileadj[j]->flags |= F_MARK;
1970 tileadj2->flags |= F_MARK;
1971 }
1972 }
1973 if (next > end) {
1974 /* We added more squares; go back and try again. */
1975 start = end; end = next; goto expand;
1976 }
1977
1978 /* We've expanded as far as we can go. Now we update the main flags
1979 * on all tiles we've expanded into -- if they were empty, we have
1980 * found possible associations for this dot. */
1981 for (i = 0; i < end; i++) {
1982 if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
1983 if (sctx->scratch[i]->flags & F_REACHABLE) {
1984 /* This is (at least) the second dot this tile could
1985 * associate with. */
1986 debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
1987 solver_recurse_depth*4, "",
1988 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1989 sctx->scratch[i]->flags |= F_MULTIPLE;
1990 } else {
1991 /* This is the first (possibly only) dot. */
1992 debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
1993 solver_recurse_depth*4, "",
1994 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1995 sctx->scratch[i]->flags |= F_REACHABLE;
1996 sctx->scratch[i]->dotx = dot->x;
1997 sctx->scratch[i]->doty = dot->y;
1998 }
1999 }
2000 dbg_state(state);
2001 }
2002
2003 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2004 {
2005 assert(tile->type == s_tile);
2006
2007 if (tile->flags & F_TILE_ASSOC) return 0;
2008
2009 if (!(tile->flags & F_REACHABLE)) {
2010 solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2011 solver_recurse_depth*4, "", tile->x, tile->y));
2012 return -1;
2013 }
2014 if (tile->flags & F_MULTIPLE) return 0;
2015
2016 return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2017 "single possible dot after expansion");
2018 }
2019
2020 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2021 {
2022 int i;
2023
2024 for (i = 0; i < sctx->sz; i++)
2025 state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2026
2027 for (i = 0; i < state->ndots; i++)
2028 solver_expand_fromdot(state, state->dots[i], sctx);
2029
2030 return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2031 }
2032
2033 struct recurse_ctx {
2034 space *best;
2035 int bestn;
2036 };
2037
2038 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2039 {
2040 struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2041 int i, n = 0;
2042
2043 assert(tile->type == s_tile);
2044 if (tile->flags & F_TILE_ASSOC) return 0;
2045
2046 /* We're unassociated: count up all the dots we could associate with. */
2047 for (i = 0; i < state->ndots; i++) {
2048 if (dotfortile(state, tile, state->dots[i]))
2049 n++;
2050 }
2051 if (n > rctx->bestn) {
2052 rctx->bestn = n;
2053 rctx->best = tile;
2054 }
2055 return 0;
2056 }
2057
2058 static int solver_state(game_state *state, int maxdiff);
2059
2060 #define MAXRECURSE 5
2061
2062 static int solver_recurse(game_state *state, int maxdiff)
2063 {
2064 int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2065 space *ingrid, *outgrid = NULL, *bestopp;
2066 struct recurse_ctx rctx;
2067
2068 if (solver_recurse_depth >= MAXRECURSE) {
2069 solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2070 return DIFF_UNFINISHED;
2071 }
2072
2073 /* Work out the cell to recurse on; go through all unassociated tiles
2074 * and find which one has the most possible dots it could associate
2075 * with. */
2076 rctx.best = NULL;
2077 rctx.bestn = 0;
2078
2079 foreach_tile(state, solver_recurse_cb, 0, &rctx);
2080 if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2081 assert(rctx.best);
2082
2083 solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2084 solver_recurse_depth*4, "",
2085 rctx.best->x, rctx.best->y, rctx.bestn));
2086
2087 #ifdef STANDALONE_SOLVER
2088 solver_recurse_depth++;
2089 #endif
2090
2091 ingrid = snewn(gsz, struct space);
2092 memcpy(ingrid, state->grid, gsz * sizeof(struct space));
2093
2094 for (n = 0; n < state->ndots; n++) {
2095 memcpy(state->grid, ingrid, gsz * sizeof(struct space));
2096
2097 if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2098
2099 /* set cell (temporarily) pointing to that dot. */
2100 solver_add_assoc(state, rctx.best,
2101 state->dots[n]->x, state->dots[n]->y,
2102 "Attempting for recursion");
2103
2104 ret = solver_state(state, maxdiff);
2105
2106 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2107 /* we found our first solved grid; copy it away. */
2108 assert(!outgrid);
2109 outgrid = snewn(gsz, struct space);
2110 memcpy(outgrid, state->grid, gsz * sizeof(struct space));
2111 }
2112 /* reset cell back to unassociated. */
2113 bestopp = tile_opposite(state, rctx.best);
2114 assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2115
2116 remove_assoc(state, rctx.best);
2117 remove_assoc(state, bestopp);
2118
2119 if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2120 diff = ret;
2121 else if (ret == DIFF_IMPOSSIBLE)
2122 /* no change */;
2123 else {
2124 /* precisely one solution */
2125 if (diff == DIFF_IMPOSSIBLE)
2126 diff = DIFF_UNREASONABLE;
2127 else
2128 diff = DIFF_AMBIGUOUS;
2129 }
2130 /* if we've found >1 solution, or ran out of recursion,
2131 * give up immediately. */
2132 if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2133 break;
2134 }
2135
2136 #ifdef STANDALONE_SOLVER
2137 solver_recurse_depth--;
2138 #endif
2139
2140 if (outgrid) {
2141 /* we found (at least one) soln; copy it back to state */
2142 memcpy(state->grid, outgrid, gsz * sizeof(struct space));
2143 sfree(outgrid);
2144 }
2145 sfree(ingrid);
2146 return diff;
2147 }
2148
2149 static int solver_state(game_state *state, int maxdiff)
2150 {
2151 solver_ctx *sctx = new_solver(state);
2152 int ret, diff = DIFF_NORMAL;
2153
2154 #ifdef STANDALONE_PICTURE_GENERATOR
2155 /* hack, hack: set picture to NULL during solving so that add_assoc
2156 * won't complain when we attempt recursive guessing and guess wrong */
2157 int *savepic = picture;
2158 picture = NULL;
2159 #endif
2160
2161 ret = solver_obvious(state);
2162 if (ret < 0) {
2163 diff = DIFF_IMPOSSIBLE;
2164 goto got_result;
2165 }
2166
2167 #define CHECKRET(d) do { \
2168 if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; } \
2169 if (ret > 0) { diff = max(diff, (d)); goto cont; } \
2170 } while(0)
2171
2172 while (1) {
2173 cont:
2174 ret = foreach_edge(state, solver_lines_opposite_cb,
2175 IMPOSSIBLE_QUITS, sctx);
2176 CHECKRET(DIFF_NORMAL);
2177
2178 ret = foreach_tile(state, solver_spaces_oneposs_cb,
2179 IMPOSSIBLE_QUITS, sctx);
2180 CHECKRET(DIFF_NORMAL);
2181
2182 ret = solver_expand_dots(state, sctx);
2183 CHECKRET(DIFF_NORMAL);
2184
2185 if (maxdiff <= DIFF_NORMAL)
2186 break;
2187
2188 /* harder still? */
2189
2190 /* if we reach here, we've made no deductions, so we terminate. */
2191 break;
2192 }
2193
2194 if (check_complete(state, NULL, NULL)) goto got_result;
2195
2196 diff = (maxdiff >= DIFF_UNREASONABLE) ?
2197 solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2198
2199 got_result:
2200 free_solver(sctx);
2201 #ifndef STANDALONE_SOLVER
2202 debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2203 dbg_state(state);
2204 #endif
2205
2206 #ifdef STANDALONE_PICTURE_GENERATOR
2207 picture = savepic;
2208 #endif
2209
2210 return diff;
2211 }
2212
2213 #ifndef EDITOR
2214 static char *solve_game(game_state *state, game_state *currstate,
2215 char *aux, char **error)
2216 {
2217 game_state *tosolve;
2218 char *ret;
2219 int i;
2220 int diff;
2221
2222 tosolve = dup_game(currstate);
2223 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2224 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2225 debug(("solve_game solved with current state.\n"));
2226 goto solved;
2227 }
2228 free_game(tosolve);
2229
2230 tosolve = dup_game(state);
2231 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2232 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2233 debug(("solve_game solved with original state.\n"));
2234 goto solved;
2235 }
2236 free_game(tosolve);
2237
2238 return NULL;
2239
2240 solved:
2241 /*
2242 * Clear tile associations: the solution will only include the
2243 * edges.
2244 */
2245 for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2246 tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2247 ret = diff_game(currstate, tosolve, 1);
2248 free_game(tosolve);
2249 return ret;
2250 }
2251 #endif
2252
2253 /* ----------------------------------------------------------
2254 * User interface.
2255 */
2256
2257 struct game_ui {
2258 int dragging;
2259 int dx, dy; /* pixel coords of drag pos. */
2260 int dotx, doty; /* grid coords of dot we're dragging from. */
2261 int srcx, srcy; /* grid coords of drag start */
2262 int cur_x, cur_y, cur_visible;
2263 };
2264
2265 static game_ui *new_ui(game_state *state)
2266 {
2267 game_ui *ui = snew(game_ui);
2268 ui->dragging = FALSE;
2269 ui->cur_x = ui->cur_y = 1;
2270 ui->cur_visible = 0;
2271 return ui;
2272 }
2273
2274 static void free_ui(game_ui *ui)
2275 {
2276 sfree(ui);
2277 }
2278
2279 static char *encode_ui(game_ui *ui)
2280 {
2281 return NULL;
2282 }
2283
2284 static void decode_ui(game_ui *ui, char *encoding)
2285 {
2286 }
2287
2288 static void game_changed_state(game_ui *ui, game_state *oldstate,
2289 game_state *newstate)
2290 {
2291 }
2292
2293 #define FLASH_TIME 0.15F
2294
2295 #define PREFERRED_TILE_SIZE 32
2296 #define TILE_SIZE (ds->tilesize)
2297 #define DOT_SIZE (TILE_SIZE / 4)
2298 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2299 #define BORDER TILE_SIZE
2300
2301 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2302 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2303 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2304
2305 #define DRAW_WIDTH (BORDER * 2 + ds->w * TILE_SIZE)
2306 #define DRAW_HEIGHT (BORDER * 2 + ds->h * TILE_SIZE)
2307
2308 #define CURSOR_SIZE DOT_SIZE
2309
2310 struct game_drawstate {
2311 int started;
2312 int w, h;
2313 int tilesize;
2314 unsigned long *grid;
2315 int *dx, *dy;
2316 blitter *bl;
2317
2318 int dragging, dragx, dragy;
2319
2320 int *colour_scratch;
2321
2322 int cx, cy, cur_visible;
2323 blitter *cur_bl;
2324 };
2325
2326 #define CORNER_TOLERANCE 0.15F
2327 #define CENTRE_TOLERANCE 0.15F
2328
2329 /*
2330 * Round FP coordinates to the centre of the nearest edge.
2331 */
2332 #ifndef EDITOR
2333 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2334 {
2335 float xs, ys, xv, yv, dx, dy;
2336
2337 /*
2338 * Find the nearest square-centre.
2339 */
2340 xs = (float)floor(x) + 0.5F;
2341 ys = (float)floor(y) + 0.5F;
2342
2343 /*
2344 * Find the nearest grid vertex.
2345 */
2346 xv = (float)floor(x + 0.5F);
2347 yv = (float)floor(y + 0.5F);
2348
2349 /*
2350 * Determine whether the horizontal or vertical edge from that
2351 * vertex alongside that square is closer to us, by comparing
2352 * distances from the square cente.
2353 */
2354 dx = (float)fabs(x - xs);
2355 dy = (float)fabs(y - ys);
2356 if (dx > dy) {
2357 /* Vertical edge: x-coord of corner,
2358 * y-coord of square centre. */
2359 *xr = 2 * (int)xv;
2360 *yr = 1 + 2 * (int)floor(ys);
2361 } else {
2362 /* Horizontal edge: x-coord of square centre,
2363 * y-coord of corner. */
2364 *xr = 1 + 2 * (int)floor(xs);
2365 *yr = 2 * (int)yv;
2366 }
2367 }
2368 #endif
2369
2370 #ifdef EDITOR
2371 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2372 int x, int y, int button)
2373 {
2374 char buf[80];
2375 int px, py;
2376 struct space *sp;
2377
2378 px = 2*FROMCOORD((float)x) + 0.5;
2379 py = 2*FROMCOORD((float)y) + 0.5;
2380
2381 state->cdiff = -1;
2382
2383 if (button == 'C' || button == 'c') return dupstr("C");
2384
2385 if (button == 'S' || button == 's') {
2386 char *ret;
2387 game_state *tmp = dup_game(state);
2388 state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2389 ret = diff_game(state, tmp, 0);
2390 free_game(tmp);
2391 return ret;
2392 }
2393
2394 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2395 if (!INUI(state, px, py)) return NULL;
2396 sp = &SPACE(state, px, py);
2397 if (!dot_is_possible(state, sp, 1)) return NULL;
2398 sprintf(buf, "%c%d,%d",
2399 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2400 return dupstr(buf);
2401 }
2402
2403 return NULL;
2404 }
2405 #else
2406 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2407 int x, int y, int button)
2408 {
2409 /* UI operations (play mode):
2410 *
2411 * Toggle edge (set/unset) (left-click on edge)
2412 * Associate space with dot (left-drag from dot)
2413 * Unassociate space (left-drag from space off grid)
2414 * Autofill lines around shape? (right-click?)
2415 *
2416 * (edit mode; will clear all lines/associations)
2417 *
2418 * Add or remove dot (left-click)
2419 */
2420 char buf[80];
2421 const char *sep = "";
2422 int px, py;
2423 struct space *sp, *dot;
2424
2425 buf[0] = '\0';
2426
2427 if (button == 'H' || button == 'h') {
2428 char *ret;
2429 game_state *tmp = dup_game(state);
2430 solver_obvious(tmp);
2431 ret = diff_game(state, tmp, 0);
2432 free_game(tmp);
2433 return ret;
2434 }
2435
2436 if (button == LEFT_BUTTON) {
2437 ui->cur_visible = 0;
2438 coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2439 &px, &py);
2440
2441 if (!INUI(state, px, py)) return NULL;
2442
2443 sp = &SPACE(state, px, py);
2444 assert(sp->type == s_edge);
2445 {
2446 sprintf(buf, "E%d,%d", px, py);
2447 return dupstr(buf);
2448 }
2449 } else if (button == RIGHT_BUTTON) {
2450 int px1, py1;
2451
2452 ui->cur_visible = 0;
2453
2454 px = (int)(2*FROMCOORD((float)x) + 0.5);
2455 py = (int)(2*FROMCOORD((float)y) + 0.5);
2456
2457 dot = NULL;
2458
2459 /*
2460 * If there's a dot anywhere nearby, we pick up an arrow
2461 * pointing at that dot.
2462 */
2463 for (py1 = py-1; py1 <= py+1; py1++)
2464 for (px1 = px-1; px1 <= px+1; px1++) {
2465 if (px1 >= 0 && px1 < state->sx &&
2466 py1 >= 0 && py1 < state->sy &&
2467 x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2468 y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2469 SPACE(state, px1, py1).flags & F_DOT) {
2470 /*
2471 * Found a dot. Begin a drag from it.
2472 */
2473 dot = &SPACE(state, px1, py1);
2474 ui->srcx = px1;
2475 ui->srcy = py1;
2476 goto done; /* multi-level break */
2477 }
2478 }
2479
2480 /*
2481 * Otherwise, find the nearest _square_, and pick up the
2482 * same arrow as it's got on it, if any.
2483 */
2484 if (!dot) {
2485 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2486 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2487 if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2488 sp = &SPACE(state, px, py);
2489 if (sp->flags & F_TILE_ASSOC) {
2490 dot = &SPACE(state, sp->dotx, sp->doty);
2491 ui->srcx = px;
2492 ui->srcy = py;
2493 }
2494 }
2495 }
2496
2497 done:
2498 /*
2499 * Now, if we've managed to find a dot, begin a drag.
2500 */
2501 if (dot) {
2502 ui->dragging = TRUE;
2503 ui->dx = x;
2504 ui->dy = y;
2505 ui->dotx = dot->x;
2506 ui->doty = dot->y;
2507 return "";
2508 }
2509 } else if (button == RIGHT_DRAG && ui->dragging) {
2510 /* just move the drag coords. */
2511 ui->dx = x;
2512 ui->dy = y;
2513 return "";
2514 } else if (button == RIGHT_RELEASE && ui->dragging) {
2515 ui->dragging = FALSE;
2516
2517 /*
2518 * Drags are always targeted at a single square.
2519 */
2520 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2521 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2522
2523 /*
2524 * Dragging an arrow on to the same square it started from
2525 * is a null move; just update the ui and finish.
2526 */
2527 if (px == ui->srcx && py == ui->srcy)
2528 return "";
2529
2530 /*
2531 * Otherwise, we remove the arrow from its starting
2532 * square if we didn't start from a dot...
2533 */
2534 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2535 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2536 sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2537 sep = ";";
2538 }
2539
2540 /*
2541 * ... and if the square we're moving it _to_ is valid, we
2542 * add one there instead.
2543 */
2544 if (INUI(state, px, py)) {
2545 sp = &SPACE(state, px, py);
2546
2547 if (!(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC))
2548 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2549 sep, px, py, ui->dotx, ui->doty);
2550 }
2551
2552 if (buf[0])
2553 return dupstr(buf);
2554 else
2555 return "";
2556 } else if (IS_CURSOR_MOVE(button)) {
2557 move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2558 if (ui->cur_x < 1) ui->cur_x = 1;
2559 if (ui->cur_y < 1) ui->cur_y = 1;
2560 ui->cur_visible = 1;
2561 if (ui->dragging) {
2562 ui->dx = SCOORD(ui->cur_x);
2563 ui->dy = SCOORD(ui->cur_y);
2564 }
2565 return "";
2566 } else if (IS_CURSOR_SELECT(button)) {
2567 if (!ui->cur_visible) {
2568 ui->cur_visible = 1;
2569 return "";
2570 }
2571 sp = &SPACE(state, ui->cur_x, ui->cur_y);
2572 if (ui->dragging) {
2573 ui->dragging = FALSE;
2574
2575 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2576 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2577 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2578 sep = ";";
2579 }
2580 if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2581 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2582 sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2583 }
2584 return dupstr(buf);
2585 } else if (sp->flags & F_DOT) {
2586 ui->dragging = TRUE;
2587 ui->dx = SCOORD(ui->cur_x);
2588 ui->dy = SCOORD(ui->cur_y);
2589 ui->dotx = ui->srcx = ui->cur_x;
2590 ui->doty = ui->srcy = ui->cur_y;
2591 return "";
2592 } else if (sp->flags & F_TILE_ASSOC) {
2593 assert(sp->type == s_tile);
2594 ui->dragging = TRUE;
2595 ui->dx = SCOORD(ui->cur_x);
2596 ui->dy = SCOORD(ui->cur_y);
2597 ui->dotx = sp->dotx;
2598 ui->doty = sp->doty;
2599 ui->srcx = ui->cur_x;
2600 ui->srcy = ui->cur_y;
2601 return "";
2602 } else if (sp->type == s_edge) {
2603 sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2604 return dupstr(buf);
2605 }
2606 }
2607
2608 return NULL;
2609 }
2610 #endif
2611
2612 static int check_complete(game_state *state, int *dsf, int *colours)
2613 {
2614 int w = state->w, h = state->h;
2615 int x, y, i, ret;
2616
2617 int free_dsf;
2618 struct sqdata {
2619 int minx, miny, maxx, maxy;
2620 int cx, cy;
2621 int valid, colour;
2622 } *sqdata;
2623
2624 if (!dsf) {
2625 dsf = snew_dsf(w*h);
2626 free_dsf = TRUE;
2627 } else {
2628 dsf_init(dsf, w*h);
2629 free_dsf = FALSE;
2630 }
2631
2632 /*
2633 * During actual game play, completion checking is done on the
2634 * basis of the edges rather than the square associations. So
2635 * first we must go through the grid figuring out the connected
2636 * components into which the edges divide it.
2637 */
2638 for (y = 0; y < h; y++)
2639 for (x = 0; x < w; x++) {
2640 if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2641 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2642 if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2643 dsf_merge(dsf, y*w+x, y*w+(x+1));
2644 }
2645
2646 /*
2647 * That gives us our connected components. Now, for each
2648 * component, decide whether it's _valid_. A valid component is
2649 * one which:
2650 *
2651 * - is 180-degree rotationally symmetric
2652 * - has a dot at its centre of symmetry
2653 * - has no other dots anywhere within it (including on its
2654 * boundary)
2655 * - contains no internal edges (i.e. edges separating two
2656 * squares which are both part of the component).
2657 */
2658
2659 /*
2660 * First, go through the grid finding the bounding box of each
2661 * component.
2662 */
2663 sqdata = snewn(w*h, struct sqdata);
2664 for (i = 0; i < w*h; i++) {
2665 sqdata[i].minx = w+1;
2666 sqdata[i].miny = h+1;
2667 sqdata[i].maxx = sqdata[i].maxy = -1;
2668 sqdata[i].valid = FALSE;
2669 }
2670 for (y = 0; y < h; y++)
2671 for (x = 0; x < w; x++) {
2672 i = dsf_canonify(dsf, y*w+x);
2673 if (sqdata[i].minx > x)
2674 sqdata[i].minx = x;
2675 if (sqdata[i].maxx < x)
2676 sqdata[i].maxx = x;
2677 if (sqdata[i].miny > y)
2678 sqdata[i].miny = y;
2679 if (sqdata[i].maxy < y)
2680 sqdata[i].maxy = y;
2681 sqdata[i].valid = TRUE;
2682 }
2683
2684 /*
2685 * Now we're in a position to loop over each actual component
2686 * and figure out where its centre of symmetry has to be if
2687 * it's anywhere.
2688 */
2689 for (i = 0; i < w*h; i++)
2690 if (sqdata[i].valid) {
2691 int cx, cy;
2692 cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2693 cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2694 if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2695 sqdata[i].valid = FALSE; /* no dot at centre of symmetry */
2696 if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2697 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2698 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2699 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2700 sqdata[i].valid = FALSE; /* dot at cx,cy isn't ours */
2701 if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2702 sqdata[i].colour = 2;
2703 else
2704 sqdata[i].colour = 1;
2705 }
2706
2707 /*
2708 * Now we loop over the whole grid again, this time finding
2709 * extraneous dots (any dot which wholly or partially overlaps
2710 * a square and is not at the centre of symmetry of that
2711 * square's component disqualifies the component from validity)
2712 * and extraneous edges (any edge separating two squares
2713 * belonging to the same component also disqualifies that
2714 * component).
2715 */
2716 for (y = 1; y < state->sy-1; y++)
2717 for (x = 1; x < state->sx-1; x++) {
2718 space *sp = &SPACE(state, x, y);
2719
2720 if (sp->flags & F_DOT) {
2721 /*
2722 * There's a dot here. Use it to disqualify any
2723 * component which deserves it.
2724 */
2725 int cx, cy;
2726 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2727 for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2728 i = dsf_canonify(dsf, cy*w+cx);
2729 if (x != sqdata[i].cx || y != sqdata[i].cy)
2730 sqdata[i].valid = FALSE;
2731 }
2732 }
2733
2734 if (sp->flags & F_EDGE_SET) {
2735 /*
2736 * There's an edge here. Use it to disqualify a
2737 * component if necessary.
2738 */
2739 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2740 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2741 assert((cx1==cx2) ^ (cy1==cy2));
2742 i = dsf_canonify(dsf, cy1*w+cx1);
2743 if (i == dsf_canonify(dsf, cy2*w+cx2))
2744 sqdata[i].valid = FALSE;
2745 }
2746 }
2747
2748 /*
2749 * And finally we test rotational symmetry: for each square in
2750 * the grid, find which component it's in, test that that
2751 * component also has a square in the symmetric position, and
2752 * disqualify it if it doesn't.
2753 */
2754 for (y = 0; y < h; y++)
2755 for (x = 0; x < w; x++) {
2756 int x2, y2;
2757
2758 i = dsf_canonify(dsf, y*w+x);
2759
2760 x2 = sqdata[i].cx - 1 - x;
2761 y2 = sqdata[i].cy - 1 - y;
2762 if (i != dsf_canonify(dsf, y2*w+x2))
2763 sqdata[i].valid = FALSE;
2764 }
2765
2766 /*
2767 * That's it. We now have all the connected components marked
2768 * as valid or not valid. So now we return a `colours' array if
2769 * we were asked for one, and also we return an overall
2770 * true/false value depending on whether _every_ square in the
2771 * grid is part of a valid component.
2772 */
2773 ret = TRUE;
2774 for (i = 0; i < w*h; i++) {
2775 int ci = dsf_canonify(dsf, i);
2776 int thisok = sqdata[ci].valid;
2777 if (colours)
2778 colours[i] = thisok ? sqdata[ci].colour : 0;
2779 ret = ret && thisok;
2780 }
2781
2782 sfree(sqdata);
2783 if (free_dsf)
2784 sfree(dsf);
2785
2786 return ret;
2787 }
2788
2789 static game_state *execute_move(game_state *state, char *move)
2790 {
2791 int x, y, ax, ay, n, dx, dy;
2792 game_state *ret = dup_game(state);
2793 struct space *sp, *dot;
2794
2795 debug(("%s\n", move));
2796
2797 while (*move) {
2798 char c = *move;
2799 if (c == 'E' || c == 'U' || c == 'M'
2800 #ifdef EDITOR
2801 || c == 'D' || c == 'd'
2802 #endif
2803 ) {
2804 move++;
2805 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2806 !INUI(state, x, y))
2807 goto badmove;
2808
2809 sp = &SPACE(ret, x, y);
2810 #ifdef EDITOR
2811 if (c == 'D' || c == 'd') {
2812 unsigned int currf, newf, maskf;
2813
2814 if (!dot_is_possible(state, sp, 1)) goto badmove;
2815
2816 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2817 currf = GRID(ret, grid, x, y).flags;
2818 maskf = F_DOT | F_DOT_BLACK;
2819 /* if we clicked 'white dot':
2820 * white --> empty, empty --> white, black --> white.
2821 * if we clicker 'black dot':
2822 * black --> empty, empty --> black, white --> black.
2823 */
2824 if (currf & maskf) {
2825 sp->flags &= ~maskf;
2826 if ((currf & maskf) != newf)
2827 sp->flags |= newf;
2828 } else
2829 sp->flags |= newf;
2830 sp->nassoc = 0; /* edit-mode disallows associations. */
2831 game_update_dots(ret);
2832 } else
2833 #endif
2834 if (c == 'E') {
2835 if (sp->type != s_edge) goto badmove;
2836 sp->flags ^= F_EDGE_SET;
2837 } else if (c == 'U') {
2838 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2839 goto badmove;
2840 remove_assoc(ret, sp);
2841 } else if (c == 'M') {
2842 if (!(sp->flags & F_DOT)) goto badmove;
2843 sp->flags ^= F_DOT_HOLD;
2844 }
2845 move += n;
2846 } else if (c == 'A' || c == 'a') {
2847 move++;
2848 if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2849 x < 1 || y < 1 || x >= (state->sx-1) || y >= (state->sy-1) ||
2850 ax < 1 || ay < 1 || ax >= (state->sx-1) || ay >= (state->sy-1))
2851 goto badmove;
2852
2853 dot = &GRID(ret, grid, ax, ay);
2854 if (!(dot->flags & F_DOT))goto badmove;
2855 if (dot->flags & F_DOT_HOLD) goto badmove;
2856
2857 for (dx = -1; dx <= 1; dx++) {
2858 for (dy = -1; dy <= 1; dy++) {
2859 sp = &GRID(ret, grid, x+dx, y+dy);
2860 if (sp->type != s_tile) continue;
2861 if (sp->flags & F_TILE_ASSOC) {
2862 space *dot = &SPACE(state, sp->dotx, sp->doty);
2863 if (dot->flags & F_DOT_HOLD) continue;
2864 }
2865 add_assoc(state, sp, dot);
2866 }
2867 }
2868 move += n;
2869 #ifdef EDITOR
2870 } else if (c == 'C') {
2871 move++;
2872 clear_game(ret, 1);
2873 #endif
2874 } else if (c == 'S') {
2875 move++;
2876 ret->used_solve = 1;
2877 } else
2878 goto badmove;
2879
2880 if (*move == ';')
2881 move++;
2882 else if (*move)
2883 goto badmove;
2884 }
2885 if (check_complete(ret, NULL, NULL))
2886 ret->completed = 1;
2887 return ret;
2888
2889 badmove:
2890 free_game(ret);
2891 return NULL;
2892 }
2893
2894 /* ----------------------------------------------------------------------
2895 * Drawing routines.
2896 */
2897
2898 /* Lines will be much smaller size than squares; say, 1/8 the size?
2899 *
2900 * Need a 'top-left corner of location XxY' to take this into account;
2901 * alternaticaly, that could give the middle of that location, and the
2902 * drawing code would just know the expected dimensions.
2903 *
2904 * We also need something to take a click and work out what it was
2905 * we were interested in. Clicking on vertices is required because
2906 * we may want to drag from them, for example.
2907 */
2908
2909 static void game_compute_size(game_params *params, int sz,
2910 int *x, int *y)
2911 {
2912 struct { int tilesize, w, h; } ads, *ds = &ads;
2913
2914 ds->tilesize = sz;
2915 ds->w = params->w;
2916 ds->h = params->h;
2917
2918 *x = DRAW_WIDTH;
2919 *y = DRAW_HEIGHT;
2920 }
2921
2922 static void game_set_size(drawing *dr, game_drawstate *ds,
2923 game_params *params, int sz)
2924 {
2925 ds->tilesize = sz;
2926
2927 assert(TILE_SIZE > 0);
2928
2929 assert(!ds->bl);
2930 ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2931
2932 assert(!ds->cur_bl);
2933 ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2934 }
2935
2936 static float *game_colours(frontend *fe, int *ncolours)
2937 {
2938 float *ret = snewn(3 * NCOLOURS, float);
2939 int i;
2940
2941 /*
2942 * We call game_mkhighlight to ensure the background colour
2943 * isn't completely white. We don't actually use the high- and
2944 * lowlight colours it generates.
2945 */
2946 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
2947
2948 for (i = 0; i < 3; i++) {
2949 /*
2950 * Currently, white dots and white-background squares are
2951 * both pure white.
2952 */
2953 ret[COL_WHITEDOT * 3 + i] = 1.0F;
2954 ret[COL_WHITEBG * 3 + i] = 1.0F;
2955
2956 /*
2957 * But black-background squares are a dark grey, whereas
2958 * black dots are really black.
2959 */
2960 ret[COL_BLACKDOT * 3 + i] = 0.0F;
2961 ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
2962
2963 /*
2964 * In unfilled squares, we draw a faint gridwork.
2965 */
2966 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
2967
2968 /*
2969 * Edges and arrows are filled in in pure black.
2970 */
2971 ret[COL_EDGE * 3 + i] = 0.0F;
2972 ret[COL_ARROW * 3 + i] = 0.0F;
2973 }
2974
2975 #ifdef EDITOR
2976 /* tinge the edit background to bluey */
2977 ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2978 ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2979 ret[COL_BACKGROUND * 3 + 2] = max(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2980 #endif
2981
2982 ret[COL_CURSOR * 3 + 0] = max(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2983 ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2984 ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2985
2986 *ncolours = NCOLOURS;
2987 return ret;
2988 }
2989
2990 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2991 {
2992 struct game_drawstate *ds = snew(struct game_drawstate);
2993 int i;
2994
2995 ds->started = 0;
2996 ds->w = state->w;
2997 ds->h = state->h;
2998
2999 ds->grid = snewn(ds->w*ds->h, unsigned long);
3000 for (i = 0; i < ds->w*ds->h; i++)
3001 ds->grid[i] = 0xFFFFFFFFUL;
3002 ds->dx = snewn(ds->w*ds->h, int);
3003 ds->dy = snewn(ds->w*ds->h, int);
3004
3005 ds->bl = NULL;
3006 ds->dragging = FALSE;
3007 ds->dragx = ds->dragy = 0;
3008
3009 ds->colour_scratch = snewn(ds->w * ds->h, int);
3010
3011 ds->cur_bl = NULL;
3012 ds->cx = ds->cy = 0;
3013 ds->cur_visible = 0;
3014
3015 return ds;
3016 }
3017
3018 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3019 {
3020 if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3021 sfree(ds->colour_scratch);
3022 if (ds->bl) blitter_free(dr, ds->bl);
3023 sfree(ds->dx);
3024 sfree(ds->dy);
3025 sfree(ds->grid);
3026 sfree(ds);
3027 }
3028
3029 #define DRAW_EDGE_L 0x0001
3030 #define DRAW_EDGE_R 0x0002
3031 #define DRAW_EDGE_U 0x0004
3032 #define DRAW_EDGE_D 0x0008
3033 #define DRAW_CORNER_UL 0x0010
3034 #define DRAW_CORNER_UR 0x0020
3035 #define DRAW_CORNER_DL 0x0040
3036 #define DRAW_CORNER_DR 0x0080
3037 #define DRAW_WHITE 0x0100
3038 #define DRAW_BLACK 0x0200
3039 #define DRAW_ARROW 0x0400
3040 #define DRAW_CURSOR 0x0800
3041 #define DOT_SHIFT_C 12
3042 #define DOT_SHIFT_M 2
3043 #define DOT_WHITE 1UL
3044 #define DOT_BLACK 2UL
3045
3046 /*
3047 * Draw an arrow centred on (cx,cy), pointing in the direction
3048 * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3049 */
3050 static void draw_arrow(drawing *dr, game_drawstate *ds,
3051 int cx, int cy, int ddx, int ddy, int col)
3052 {
3053 float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3054 float xdx = ddx/vlen, xdy = ddy/vlen;
3055 float ydx = -xdy, ydy = xdx;
3056 int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3057 int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3058 int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3059 int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3060
3061 draw_line(dr, e1x, e1y, e2x, e2y, col);
3062 draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3063 draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3064 }
3065
3066 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3067 unsigned long flags, int ddx, int ddy)
3068 {
3069 int lx = COORD(x), ly = COORD(y);
3070 int dx, dy;
3071 int gridcol;
3072
3073 clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3074
3075 /*
3076 * Draw the tile background.
3077 */
3078 draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3079 (flags & DRAW_WHITE ? COL_WHITEBG :
3080 flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3081
3082 /*
3083 * Draw the grid.
3084 */
3085 gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3086 draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3087 draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3088
3089 /*
3090 * Draw the arrow, if present, or the cursor, if here.
3091 */
3092 if (flags & DRAW_ARROW)
3093 draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3094 (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3095 else if (flags & DRAW_CURSOR)
3096 draw_rect_outline(dr,
3097 lx + TILE_SIZE/2 - CURSOR_SIZE,
3098 ly + TILE_SIZE/2 - CURSOR_SIZE,
3099 2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3100 COL_CURSOR);
3101
3102 /*
3103 * Draw the edges.
3104 */
3105 if (flags & DRAW_EDGE_L)
3106 draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3107 if (flags & DRAW_EDGE_R)
3108 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3109 EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3110 if (flags & DRAW_EDGE_U)
3111 draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3112 if (flags & DRAW_EDGE_D)
3113 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3114 TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3115 if (flags & DRAW_CORNER_UL)
3116 draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3117 if (flags & DRAW_CORNER_UR)
3118 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3119 EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3120 if (flags & DRAW_CORNER_DL)
3121 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3122 EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3123 if (flags & DRAW_CORNER_DR)
3124 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3125 ly + TILE_SIZE - EDGE_THICKNESS + 1,
3126 EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3127
3128 /*
3129 * Draw the dots.
3130 */
3131 for (dy = 0; dy < 3; dy++)
3132 for (dx = 0; dx < 3; dx++) {
3133 int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3134 dotval &= (1 << DOT_SHIFT_M)-1;
3135
3136 if (dotval)
3137 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3138 DOT_SIZE,
3139 (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3140 COL_BLACKDOT);
3141 }
3142
3143 unclip(dr);
3144 draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3145 }
3146
3147 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3148 game_state *state, int dir, game_ui *ui,
3149 float animtime, float flashtime)
3150 {
3151 int w = ds->w, h = ds->h;
3152 int x, y, flashing = FALSE;
3153
3154 if (flashtime > 0) {
3155 int frame = (int)(flashtime / FLASH_TIME);
3156 flashing = (frame % 2 == 0);
3157 }
3158
3159 if (ds->dragging) {
3160 assert(ds->bl);
3161 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3162 draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3163 ds->dragging = FALSE;
3164 }
3165 if (ds->cur_visible) {
3166 assert(ds->cur_bl);
3167 blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3168 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3169 ds->cur_visible = FALSE;
3170 }
3171
3172 if (!ds->started) {
3173 draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3174 draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3175 w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3176 h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3177 draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3178 ds->started = TRUE;
3179 }
3180
3181 check_complete(state, NULL, ds->colour_scratch);
3182
3183 for (y = 0; y < h; y++)
3184 for (x = 0; x < w; x++) {
3185 unsigned long flags = 0;
3186 int ddx = 0, ddy = 0;
3187 space *sp;
3188 int dx, dy;
3189
3190 /*
3191 * Set up the flags for this square. Firstly, see if we
3192 * have edges.
3193 */
3194 if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3195 flags |= DRAW_EDGE_L;
3196 if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3197 flags |= DRAW_EDGE_R;
3198 if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3199 flags |= DRAW_EDGE_U;
3200 if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3201 flags |= DRAW_EDGE_D;
3202
3203 /*
3204 * Also, mark corners of neighbouring edges.
3205 */
3206 if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3207 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3208 flags |= DRAW_CORNER_UL;
3209 if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3210 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3211 flags |= DRAW_CORNER_UR;
3212 if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3213 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3214 flags |= DRAW_CORNER_DL;
3215 if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3216 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3217 flags |= DRAW_CORNER_DR;
3218
3219 /*
3220 * If this square is part of a valid region, paint it
3221 * that region's colour. Exception: if we're flashing,
3222 * everything goes briefly back to background colour.
3223 */
3224 sp = &SPACE(state, x*2+1, y*2+1);
3225 if (ds->colour_scratch[y*w+x] && !flashing) {
3226 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3227 DRAW_BLACK : DRAW_WHITE);
3228 }
3229
3230 /*
3231 * If this square is associated with a dot but it isn't
3232 * part of a valid region, draw an arrow in it pointing
3233 * in the direction of that dot.
3234 *
3235 * Exception: if this is the source point of an active
3236 * drag, we don't draw the arrow.
3237 */
3238 if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3239 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3240 /* don't do it */
3241 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3242 flags |= DRAW_ARROW;
3243 ddy = sp->doty - (y*2+1);
3244 ddx = sp->dotx - (x*2+1);
3245 }
3246 }
3247
3248 /*
3249 * Now go through the nine possible places we could
3250 * have dots.
3251 */
3252 for (dy = 0; dy < 3; dy++)
3253 for (dx = 0; dx < 3; dx++) {
3254 sp = &SPACE(state, x*2+dx, y*2+dy);
3255 if (sp->flags & F_DOT) {
3256 unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3257 DOT_BLACK : DOT_WHITE);
3258 flags |= dotval << (DOT_SHIFT_C +
3259 DOT_SHIFT_M*(dy*3+dx));
3260 }
3261 }
3262
3263 /*
3264 * Now work out if we have to draw a cursor for this square;
3265 * cursors-on-lines are taken care of below.
3266 */
3267 if (ui->cur_visible &&
3268 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3269 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3270 flags |= DRAW_CURSOR;
3271
3272 /*
3273 * Now we have everything we're going to need. Draw the
3274 * square.
3275 */
3276 if (ds->grid[y*w+x] != flags ||
3277 ds->dx[y*w+x] != ddx ||
3278 ds->dy[y*w+x] != ddy) {
3279 draw_square(dr, ds, x, y, flags, ddx, ddy);
3280 ds->grid[y*w+x] = flags;
3281 ds->dx[y*w+x] = ddx;
3282 ds->dy[y*w+x] = ddy;
3283 }
3284 }
3285
3286 /*
3287 * Draw a cursor. This secondary blitter is much less invasive than trying
3288 * to fix up all of the rest of the code with sufficient flags to be able to
3289 * display this sensibly.
3290 */
3291 if (ui->cur_visible) {
3292 space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3293 ds->cur_visible = TRUE;
3294 ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3295 ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3296 blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3297 if (sp->flags & F_DOT) {
3298 /* draw a red dot (over the top of whatever would be there already) */
3299 draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3300 COL_CURSOR, COL_BLACKDOT);
3301 } else if (sp->type != s_tile) {
3302 /* draw an edge/vertex square; tile cursors are dealt with above. */
3303 int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3304 int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3305 int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3306 int xs = dx*2+1, ys = dy*2+1;
3307
3308 draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3309 }
3310 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3311 }
3312
3313 if (ui->dragging) {
3314 ds->dragging = TRUE;
3315 ds->dragx = ui->dx - TILE_SIZE/2;
3316 ds->dragy = ui->dy - TILE_SIZE/2;
3317 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3318 draw_arrow(dr, ds, ui->dx, ui->dy,
3319 SCOORD(ui->dotx) - ui->dx,
3320 SCOORD(ui->doty) - ui->dy, COL_ARROW);
3321 }
3322 #ifdef EDITOR
3323 {
3324 char buf[256];
3325 if (state->cdiff != -1)
3326 sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3327 else
3328 buf[0] = '\0';
3329 status_bar(dr, buf);
3330 }
3331 #endif
3332 }
3333
3334 static float game_anim_length(game_state *oldstate, game_state *newstate,
3335 int dir, game_ui *ui)
3336 {
3337 return 0.0F;
3338 }
3339
3340 static float game_flash_length(game_state *oldstate, game_state *newstate,
3341 int dir, game_ui *ui)
3342 {
3343 if ((!oldstate->completed && newstate->completed) &&
3344 !(newstate->used_solve))
3345 return 3 * FLASH_TIME;
3346 else
3347 return 0.0F;
3348 }
3349
3350 static int game_timing_state(game_state *state, game_ui *ui)
3351 {
3352 return TRUE;
3353 }
3354
3355 #ifndef EDITOR
3356 static void game_print_size(game_params *params, float *x, float *y)
3357 {
3358 int pw, ph;
3359
3360 /*
3361 * 8mm squares by default. (There isn't all that much detail
3362 * that needs to go in each square.)
3363 */
3364 game_compute_size(params, 800, &pw, &ph);
3365 *x = pw / 100.0F;
3366 *y = ph / 100.0F;
3367 }
3368
3369 static void game_print(drawing *dr, game_state *state, int sz)
3370 {
3371 int w = state->w, h = state->h;
3372 int white, black, blackish;
3373 int x, y, i, j;
3374 int *colours, *dsf;
3375 int *coords = NULL;
3376 int ncoords = 0, coordsize = 0;
3377
3378 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3379 game_drawstate ads, *ds = &ads;
3380 ds->tilesize = sz;
3381
3382 white = print_mono_colour(dr, 1);
3383 black = print_mono_colour(dr, 0);
3384 blackish = print_hatched_colour(dr, HATCH_X);
3385
3386 /*
3387 * Get the completion information.
3388 */
3389 dsf = snewn(w * h, int);
3390 colours = snewn(w * h, int);
3391 check_complete(state, dsf, colours);
3392
3393 /*
3394 * Draw the grid.
3395 */
3396 print_line_width(dr, TILE_SIZE / 64);
3397 for (x = 1; x < w; x++)
3398 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3399 for (y = 1; y < h; y++)
3400 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3401
3402 /*
3403 * Shade the completed regions. Just in case any particular
3404 * printing platform deals badly with adjacent
3405 * similarly-hatched regions, we'll fill each one as a single
3406 * polygon.
3407 */
3408 for (i = 0; i < w*h; i++) {
3409 j = dsf_canonify(dsf, i);
3410 if (colours[j] != 0) {
3411 int dx, dy, t;
3412
3413 /*
3414 * This is the first square we've run into belonging to
3415 * this polyomino, which means an edge of the polyomino
3416 * is certain to be to our left. (After we finish
3417 * tracing round it, we'll set the colours[] entry to
3418 * zero to prevent accidentally doing it again.)
3419 */
3420
3421 x = i % w;
3422 y = i / w;
3423 dx = -1;
3424 dy = 0;
3425 ncoords = 0;
3426 while (1) {
3427 /*
3428 * We are currently sitting on square (x,y), which
3429 * we know to be in our polyomino, and we also know
3430 * that (x+dx,y+dy) is not. The way I visualise
3431 * this is that we're standing to the right of a
3432 * boundary line, stretching our left arm out to
3433 * point to the exterior square on the far side.
3434 */
3435
3436 /*
3437 * First, check if we've gone round the entire
3438 * polyomino.
3439 */
3440 if (ncoords > 0 &&
3441 (x == i%w && y == i/w && dx == -1 && dy == 0))
3442 break;
3443
3444 /*
3445 * Add to our coordinate list the coordinate
3446 * backwards and to the left of where we are.
3447 */
3448 if (ncoords + 2 > coordsize) {
3449 coordsize = (ncoords * 3 / 2) + 64;
3450 coords = sresize(coords, coordsize, int);
3451 }
3452 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3453 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3454
3455 /*
3456 * Follow the edge round. If the square directly in
3457 * front of us is not part of the polyomino, we
3458 * turn right; if it is and so is the square in
3459 * front of (x+dx,y+dy), we turn left; otherwise we
3460 * go straight on.
3461 */
3462 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3463 dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3464 /* Turn right. */
3465 t = dx;
3466 dx = -dy;
3467 dy = t;
3468 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3469 y+dy+dx >= 0 && y+dy+dx < h &&
3470 dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3471 /* Turn left. */
3472 x += dx;
3473 y += dy;
3474 t = dx;
3475 dx = dy;
3476 dy = -t;
3477 x -= dx;
3478 y -= dy;
3479 } else {
3480 /* Straight on. */
3481 x -= dy;
3482 y += dx;
3483 }
3484 }
3485
3486 /*
3487 * Now we have our polygon complete, so fill it.
3488 */
3489 draw_polygon(dr, coords, ncoords/2,
3490 colours[j] == 2 ? blackish : -1, black);
3491
3492 /*
3493 * And mark this polyomino as done.
3494 */
3495 colours[j] = 0;
3496 }
3497 }
3498
3499 /*
3500 * Draw the edges.
3501 */
3502 for (y = 0; y <= h; y++)
3503 for (x = 0; x <= w; x++) {
3504 if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3505 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3506 EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3507 black);
3508 if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3509 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3510 EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3511 black);
3512 }
3513
3514 /*
3515 * Draw the dots.
3516 */
3517 for (y = 0; y <= 2*h; y++)
3518 for (x = 0; x <= 2*w; x++)
3519 if (SPACE(state, x, y).flags & F_DOT) {
3520 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3521 (SPACE(state, x, y).flags & F_DOT_BLACK ?
3522 black : white), black);
3523 }
3524
3525 sfree(dsf);
3526 sfree(colours);
3527 sfree(coords);
3528 }
3529 #endif
3530
3531 #ifdef COMBINED
3532 #define thegame galaxies
3533 #endif
3534
3535 const struct game thegame = {
3536 "Galaxies", "games.galaxies", "galaxies",
3537 default_params,
3538 game_fetch_preset,
3539 decode_params,
3540 encode_params,
3541 free_params,
3542 dup_params,
3543 TRUE, game_configure, custom_params,
3544 validate_params,
3545 new_game_desc,
3546 validate_desc,
3547 new_game,
3548 dup_game,
3549 free_game,
3550 #ifdef EDITOR
3551 FALSE, NULL,
3552 #else
3553 TRUE, solve_game,
3554 #endif
3555 TRUE, game_can_format_as_text_now, game_text_format,
3556 new_ui,
3557 free_ui,
3558 encode_ui,
3559 decode_ui,
3560 game_changed_state,
3561 interpret_move,
3562 execute_move,
3563 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3564 game_colours,
3565 game_new_drawstate,
3566 game_free_drawstate,
3567 game_redraw,
3568 game_anim_length,
3569 game_flash_length,
3570 #ifdef EDITOR
3571 FALSE, FALSE, NULL, NULL,
3572 TRUE, /* wants_statusbar */
3573 #else
3574 TRUE, FALSE, game_print_size, game_print,
3575 FALSE, /* wants_statusbar */
3576 #endif
3577 FALSE, game_timing_state,
3578 REQUIRE_RBUTTON, /* flags */
3579 };
3580
3581 #ifdef STANDALONE_SOLVER
3582
3583 const char *quis;
3584
3585 #include <time.h>
3586
3587 static void usage_exit(const char *msg)
3588 {
3589 if (msg)
3590 fprintf(stderr, "%s: %s\n", quis, msg);
3591 fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3592 exit(1);
3593 }
3594
3595 static void dump_state(game_state *state)
3596 {
3597 char *temp = game_text_format(state);
3598 printf("%s\n", temp);
3599 sfree(temp);
3600 }
3601
3602 static int gen(game_params *p, random_state *rs, int debug)
3603 {
3604 char *desc;
3605 int diff;
3606 game_state *state;
3607
3608 #ifndef DEBUGGING
3609 solver_show_working = debug;
3610 #endif
3611 printf("Generating a %dx%d %s puzzle.\n",
3612 p->w, p->h, galaxies_diffnames[p->diff]);
3613
3614 desc = new_game_desc(p, rs, NULL, 0);
3615 state = new_game(NULL, p, desc);
3616 dump_state(state);
3617
3618 diff = solver_state(state, DIFF_UNREASONABLE);
3619 printf("Generated %s game %dx%d:%s\n",
3620 galaxies_diffnames[diff], p->w, p->h, desc);
3621 dump_state(state);
3622
3623 free_game(state);
3624 sfree(desc);
3625
3626 return diff;
3627 }
3628
3629 static void soak(game_params *p, random_state *rs)
3630 {
3631 time_t tt_start, tt_now, tt_last;
3632 char *desc;
3633 game_state *st;
3634 int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3635
3636 #ifndef DEBUGGING
3637 solver_show_working = 0;
3638 #endif
3639 tt_start = tt_now = time(NULL);
3640 for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3641 maxtries = 1;
3642
3643 printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3644 p->w, p->h, galaxies_diffnames[p->diff]);
3645 printf(" [");
3646 for (i = 0; i < DIFF_MAX; i++)
3647 printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3648 printf("]\n");
3649
3650 while (1) {
3651 desc = new_game_desc(p, rs, NULL, 0);
3652 st = new_game(NULL, p, desc);
3653 diff = solver_state(st, p->diff);
3654 nspaces += st->w*st->h;
3655 for (i = 0; i < st->sx*st->sy; i++)
3656 if (st->grid[i].flags & F_DOT) ndots++;
3657 free_game(st);
3658 sfree(desc);
3659
3660 diffs[diff]++;
3661 n++;
3662 tt_last = time(NULL);
3663 if (tt_last > tt_now) {
3664 tt_now = tt_last;
3665 printf("%d total, %3.1f/s, [",
3666 n, (double)n / ((double)tt_now - tt_start));
3667 for (i = 0; i < DIFF_MAX; i++)
3668 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3669 100.0 * ((double)diffs[i] / (double)n));
3670 printf("], %.1f%% dots\n",
3671 100.0 * ((double)ndots / (double)nspaces));
3672 }
3673 }
3674 }
3675
3676 int main(int argc, char **argv)
3677 {
3678 game_params *p;
3679 char *id = NULL, *desc, *err;
3680 game_state *s;
3681 int diff, do_soak = 0, verbose = 0;
3682 random_state *rs;
3683 time_t seed = time(NULL);
3684
3685 quis = argv[0];
3686 while (--argc > 0) {
3687 char *p = *++argv;
3688 if (!strcmp(p, "-v")) {
3689 verbose = 1;
3690 } else if (!strcmp(p, "--seed")) {
3691 if (argc == 0) usage_exit("--seed needs an argument");
3692 seed = (time_t)atoi(*++argv);
3693 argc--;
3694 } else if (!strcmp(p, "--soak")) {
3695 do_soak = 1;
3696 } else if (*p == '-') {
3697 usage_exit("unrecognised option");
3698 } else {
3699 id = p;
3700 }
3701 }
3702
3703 maxtries = 50;
3704
3705 p = default_params();
3706 rs = random_new((void*)&seed, sizeof(time_t));
3707
3708 if (do_soak) {
3709 if (!id) usage_exit("need one argument for --soak");
3710 decode_params(p, *argv);
3711 soak(p, rs);
3712 return 0;
3713 }
3714
3715 if (!id) {
3716 while (1) {
3717 p->w = random_upto(rs, 15) + 3;
3718 p->h = random_upto(rs, 15) + 3;
3719 p->diff = random_upto(rs, DIFF_UNREASONABLE);
3720 diff = gen(p, rs, 0);
3721 }
3722 return 0;
3723 }
3724
3725 desc = strchr(id, ':');
3726 if (!desc) {
3727 decode_params(p, id);
3728 gen(p, rs, verbose);
3729 } else {
3730 #ifndef DEBUGGING
3731 solver_show_working = 1;
3732 #endif
3733 *desc++ = '\0';
3734 decode_params(p, id);
3735 err = validate_desc(p, desc);
3736 if (err) {
3737 fprintf(stderr, "%s: %s\n", argv[0], err);
3738 exit(1);
3739 }
3740 s = new_game(NULL, p, desc);
3741 diff = solver_state(s, DIFF_UNREASONABLE);
3742 dump_state(s);
3743 printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3744 free_game(s);
3745 }
3746
3747 free_params(p);
3748
3749 return 0;
3750 }
3751
3752 #endif
3753
3754 #ifdef STANDALONE_PICTURE_GENERATOR
3755
3756 /*
3757 * Main program for the standalone picture generator. To use it,
3758 * simply provide it with an XBM-format bitmap file (note XBM, not
3759 * XPM) on standard input, and it will output a game ID in return.
3760 * For example:
3761 *
3762 * $ ./galaxiespicture < badly-drawn-cat.xbm
3763 * 11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3764 *
3765 * If you want a puzzle with a non-standard difficulty level, pass
3766 * a partial parameters string as a command-line argument (e.g.
3767 * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3768 * which if it appeared in a random-seed game ID would set the
3769 * difficulty level to Unreasonable). However, be aware that if the
3770 * generator fails to produce an adequately difficult puzzle too
3771 * many times then it will give up and return an easier one (just
3772 * as it does during normal GUI play). To be sure you really have
3773 * the difficulty you asked for, use galaxiessolver to
3774 * double-check.
3775 *
3776 * (Perhaps I ought to include an option to make this standalone
3777 * generator carry on looping until it really does get the right
3778 * difficulty. Hmmm.)
3779 */
3780
3781 #include <time.h>
3782
3783 int main(int argc, char **argv)
3784 {
3785 game_params *par;
3786 char *params, *desc;
3787 random_state *rs;
3788 time_t seed = time(NULL);
3789 char buf[4096];
3790 int i;
3791 int x, y;
3792
3793 par = default_params();
3794 if (argc > 1)
3795 decode_params(par, argv[1]); /* get difficulty */
3796 par->w = par->h = -1;
3797
3798 /*
3799 * Now read an XBM file from standard input. This is simple and
3800 * hacky and will do very little error detection, so don't feed
3801 * it bogus data.
3802 */
3803 picture = NULL;
3804 x = y = 0;
3805 while (fgets(buf, sizeof(buf), stdin)) {
3806 buf[strcspn(buf, "\r\n")] = '\0';
3807 if (!strncmp(buf, "#define", 7)) {
3808 /*
3809 * Lines starting `#define' give the width and height.
3810 */
3811 char *num = buf + strlen(buf);
3812 char *symend;
3813
3814 while (num > buf && isdigit((unsigned char)num[-1]))
3815 num--;
3816 symend = num;
3817 while (symend > buf && isspace((unsigned char)symend[-1]))
3818 symend--;
3819
3820 if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3821 par->w = atoi(num);
3822 else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3823 par->h = atoi(num);
3824 } else {
3825 /*
3826 * Otherwise, break the string up into words and take
3827 * any word of the form `0x' plus hex digits to be a
3828 * byte.
3829 */
3830 char *p, *wordstart;
3831
3832 if (!picture) {
3833 if (par->w < 0 || par->h < 0) {
3834 printf("failed to read width and height\n");
3835 return 1;
3836 }
3837 picture = snewn(par->w * par->h, int);
3838 for (i = 0; i < par->w * par->h; i++)
3839 picture[i] = -1;
3840 }
3841
3842 p = buf;
3843 while (*p) {
3844 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3845 p++;
3846 wordstart = p;
3847 while (*p && !(*p == ',' || *p == '}' ||
3848 isspace((unsigned char)*p)))
3849 p++;
3850 if (*p)
3851 *p++ = '\0';
3852
3853 if (wordstart[0] == '0' &&
3854 (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3855 !wordstart[2 + strspn(wordstart+2,
3856 "0123456789abcdefABCDEF")]) {
3857 unsigned long byte = strtoul(wordstart+2, NULL, 16);
3858 for (i = 0; i < 8; i++) {
3859 int bit = (byte >> i) & 1;
3860 if (y < par->h && x < par->w)
3861 picture[y * par->w + x] = bit;
3862 x++;
3863 }
3864
3865 if (x >= par->w) {
3866 x = 0;
3867 y++;
3868 }
3869 }
3870 }
3871 }
3872 }
3873
3874 for (i = 0; i < par->w * par->h; i++)
3875 if (picture[i] < 0) {
3876 fprintf(stderr, "failed to read enough bitmap data\n");
3877 return 1;
3878 }
3879
3880 rs = random_new((void*)&seed, sizeof(time_t));
3881
3882 desc = new_game_desc(par, rs, NULL, FALSE);
3883 params = encode_params(par, FALSE);
3884 printf("%s:%s\n", params, desc);
3885
3886 sfree(desc);
3887 sfree(params);
3888 free_params(par);
3889 random_free(rs);
3890
3891 return 0;
3892 }
3893
3894 #endif
3895
3896 /* vim: set shiftwidth=4 tabstop=8: */