16 * The standard user interface for Net simply has left- and
17 * right-button mouse clicks in a square rotate it one way or the
18 * other. We also provide, by #ifdef, a separate interface based on
19 * rotational dragging motions. I initially developed this for the
20 * Mac on the basis that it might work better than the click
21 * interface with only one mouse button available, but in fact
22 * found it to be quite strange and unintuitive. Apparently it
23 * works better on stylus-driven platforms such as Palm and
24 * PocketPC, though, so we enable it by default there.
30 #define MATMUL(xr,yr,m,x,y) do { \
31 float rx, ry, xx = (x), yy = (y), *mat = (m); \
32 rx = mat[0] * xx + mat[2] * yy; \
33 ry = mat[1] * xx + mat[3] * yy; \
34 (xr) = rx; (yr) = ry; \
37 /* Direction and other bitfields */
44 #define RLOOP (R << 6)
45 #define ULOOP (U << 6)
46 #define LLOOP (L << 6)
47 #define DLOOP (D << 6)
48 #define LOOP(dir) ((dir) << 6)
50 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
51 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
52 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
53 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
54 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
55 ((n)&3) == 1 ? A(x) : \
56 ((n)&3) == 2 ? F(x) : C(x) )
58 /* X and Y displacements */
59 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
60 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
63 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
64 (((x) & 0x02) >> 1) + ((x) & 0x01) )
66 #define PREFERRED_TILE_SIZE 32
67 #define TILE_SIZE (ds->tilesize)
70 #define WINDOW_OFFSET 4
72 #define WINDOW_OFFSET 16
75 #define ROTATE_TIME 0.13F
76 #define FLASH_FRAME 0.07F
78 /* Transform physical coords to game coords using game_drawstate ds */
79 #define GX(x) (((x) + ds->org_x) % ds->width)
80 #define GY(y) (((y) + ds->org_y) % ds->height)
81 /* ...and game coords to physical coords */
82 #define RX(x) (((x) + ds->width - ds->org_x) % ds->width)
83 #define RY(y) (((y) + ds->height - ds->org_y) % ds->height)
102 float barrier_probability;
105 typedef struct game_immutable_state {
107 unsigned char *barriers;
108 } game_immutable_state;
111 int width, height, wrapping, completed;
112 int last_rotate_x, last_rotate_y, last_rotate_dir;
114 unsigned char *tiles;
115 struct game_immutable_state *imm;
118 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
119 ( (x2) = ((x1) + width + X((dir))) % width, \
120 (y2) = ((y1) + height + Y((dir))) % height)
122 #define OFFSET(x2,y2,x1,y1,dir,state) \
123 OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
125 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
126 #define tile(state, x, y) index(state, (state)->tiles, x, y)
127 #define barrier(state, x, y) index(state, (state)->imm->barriers, x, y)
133 static int xyd_cmp(const void *av, const void *bv) {
134 const struct xyd *a = (const struct xyd *)av;
135 const struct xyd *b = (const struct xyd *)bv;
144 if (a->direction < b->direction)
146 if (a->direction > b->direction)
151 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
153 static struct xyd *new_xyd(int x, int y, int direction)
155 struct xyd *xyd = snew(struct xyd);
158 xyd->direction = direction;
162 /* ----------------------------------------------------------------------
163 * Manage game parameters.
165 static game_params *default_params(void)
167 game_params *ret = snew(game_params);
171 ret->wrapping = FALSE;
173 ret->barrier_probability = 0.0;
178 static const struct game_params net_presets[] = {
179 {5, 5, FALSE, TRUE, 0.0},
180 {7, 7, FALSE, TRUE, 0.0},
181 {9, 9, FALSE, TRUE, 0.0},
182 {11, 11, FALSE, TRUE, 0.0},
184 {13, 11, FALSE, TRUE, 0.0},
186 {5, 5, TRUE, TRUE, 0.0},
187 {7, 7, TRUE, TRUE, 0.0},
188 {9, 9, TRUE, TRUE, 0.0},
189 {11, 11, TRUE, TRUE, 0.0},
191 {13, 11, TRUE, TRUE, 0.0},
195 static int game_fetch_preset(int i, char **name, game_params **params)
200 if (i < 0 || i >= lenof(net_presets))
203 ret = snew(game_params);
204 *ret = net_presets[i];
206 sprintf(str, "%dx%d%s", ret->width, ret->height,
207 ret->wrapping ? " wrapping" : "");
214 static void free_params(game_params *params)
219 static game_params *dup_params(const game_params *params)
221 game_params *ret = snew(game_params);
222 *ret = *params; /* structure copy */
226 static void decode_params(game_params *ret, char const *string)
228 char const *p = string;
230 ret->width = atoi(p);
231 while (*p && isdigit((unsigned char)*p)) p++;
234 ret->height = atoi(p);
235 while (*p && isdigit((unsigned char)*p)) p++;
237 ret->height = ret->width;
243 ret->wrapping = TRUE;
244 } else if (*p == 'b') {
246 ret->barrier_probability = (float)atof(p);
247 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
248 } else if (*p == 'a') {
252 p++; /* skip any other gunk */
256 static char *encode_params(const game_params *params, int full)
261 len = sprintf(ret, "%dx%d", params->width, params->height);
262 if (params->wrapping)
264 if (full && params->barrier_probability)
265 len += sprintf(ret+len, "b%g", params->barrier_probability);
266 if (full && !params->unique)
268 assert(len < lenof(ret));
274 static config_item *game_configure(const game_params *params)
279 ret = snewn(6, config_item);
281 ret[0].name = "Width";
282 ret[0].type = C_STRING;
283 sprintf(buf, "%d", params->width);
284 ret[0].sval = dupstr(buf);
287 ret[1].name = "Height";
288 ret[1].type = C_STRING;
289 sprintf(buf, "%d", params->height);
290 ret[1].sval = dupstr(buf);
293 ret[2].name = "Walls wrap around";
294 ret[2].type = C_BOOLEAN;
296 ret[2].ival = params->wrapping;
298 ret[3].name = "Barrier probability";
299 ret[3].type = C_STRING;
300 sprintf(buf, "%g", params->barrier_probability);
301 ret[3].sval = dupstr(buf);
304 ret[4].name = "Ensure unique solution";
305 ret[4].type = C_BOOLEAN;
307 ret[4].ival = params->unique;
317 static game_params *custom_params(const config_item *cfg)
319 game_params *ret = snew(game_params);
321 ret->width = atoi(cfg[0].sval);
322 ret->height = atoi(cfg[1].sval);
323 ret->wrapping = cfg[2].ival;
324 ret->barrier_probability = (float)atof(cfg[3].sval);
325 ret->unique = cfg[4].ival;
330 static char *validate_params(const game_params *params, int full)
332 if (params->width <= 0 || params->height <= 0)
333 return "Width and height must both be greater than zero";
334 if (params->width <= 1 && params->height <= 1)
335 return "At least one of width and height must be greater than one";
336 if (params->barrier_probability < 0)
337 return "Barrier probability may not be negative";
338 if (params->barrier_probability > 1)
339 return "Barrier probability may not be greater than 1";
342 * Specifying either grid dimension as 2 in a wrapping puzzle
343 * makes it actually impossible to ensure a unique puzzle
348 * Without loss of generality, let us assume the puzzle _width_
349 * is 2, so we can conveniently discuss rows without having to
350 * say `rows/columns' all the time. (The height may be 2 as
351 * well, but that doesn't matter.)
353 * In each row, there are two edges between tiles: the inner
354 * edge (running down the centre of the grid) and the outer
355 * edge (the identified left and right edges of the grid).
357 * Lemma: In any valid 2xn puzzle there must be at least one
358 * row in which _exactly one_ of the inner edge and outer edge
361 * Proof: No row can have _both_ inner and outer edges
362 * connected, because this would yield a loop. So the only
363 * other way to falsify the lemma is for every row to have
364 * _neither_ the inner nor outer edge connected. But this
365 * means there is no connection at all between the left and
366 * right columns of the puzzle, so there are two disjoint
367 * subgraphs, which is also disallowed. []
369 * Given such a row, it is always possible to make the
370 * disconnected edge connected and the connected edge
371 * disconnected without changing the state of any other edge.
372 * (This is easily seen by case analysis on the various tiles:
373 * left-pointing and right-pointing endpoints can be exchanged,
374 * likewise T-pieces, and a corner piece can select its
375 * horizontal connectivity independently of its vertical.) This
376 * yields a distinct valid solution.
378 * Thus, for _every_ row in which exactly one of the inner and
379 * outer edge is connected, there are two valid states for that
380 * row, and hence the total number of solutions of the puzzle
381 * is at least 2^(number of such rows), and in particular is at
382 * least 2 since there must be at least one such row. []
384 if (full && params->unique && params->wrapping &&
385 (params->width == 2 || params->height == 2))
386 return "No wrapping puzzle with a width or height of 2 can have"
387 " a unique solution";
392 /* ----------------------------------------------------------------------
393 * Solver used to assure solution uniqueness during generation.
397 * Test cases I used while debugging all this were
399 * ./net --generate 1 13x11w#12300
400 * which expands under the non-unique grid generation rules to
401 * 13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
402 * and has two ambiguous areas.
404 * An even better one is
405 * 13x11w#507896411361192
407 * 13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
408 * and has an ambiguous area _and_ a situation where loop avoidance
409 * is a necessary deductive technique.
412 * 48x25w#820543338195187
414 * 48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
415 * which has a spot (far right) where slightly more complex loop
416 * avoidance is required.
420 unsigned char *marked;
426 static struct todo *todo_new(int maxsize)
428 struct todo *todo = snew(struct todo);
429 todo->marked = snewn(maxsize, unsigned char);
430 memset(todo->marked, 0, maxsize);
431 todo->buflen = maxsize + 1;
432 todo->buffer = snewn(todo->buflen, int);
433 todo->head = todo->tail = 0;
437 static void todo_free(struct todo *todo)
444 static void todo_add(struct todo *todo, int index)
446 if (todo->marked[index])
447 return; /* already on the list */
448 todo->marked[index] = TRUE;
449 todo->buffer[todo->tail++] = index;
450 if (todo->tail == todo->buflen)
454 static int todo_get(struct todo *todo) {
457 if (todo->head == todo->tail)
458 return -1; /* list is empty */
459 ret = todo->buffer[todo->head++];
460 if (todo->head == todo->buflen)
462 todo->marked[ret] = FALSE;
468 * Return values: -1 means puzzle was proved inconsistent, 0 means we
469 * failed to narrow down to a unique solution, +1 means we solved it
472 static int net_solver(int w, int h, unsigned char *tiles,
473 unsigned char *barriers, int wrapping)
475 unsigned char *tilestate;
476 unsigned char *edgestate;
485 * Set up the solver's data structures.
489 * tilestate stores the possible orientations of each tile.
490 * There are up to four of these, so we'll index the array in
491 * fours. tilestate[(y * w + x) * 4] and its three successive
492 * members give the possible orientations, clearing to 255 from
493 * the end as things are ruled out.
495 * In this loop we also count up the area of the grid (which is
496 * not _necessarily_ equal to w*h, because there might be one
497 * or more blank squares present. This will never happen in a
498 * grid generated _by_ this program, but it's worth keeping the
499 * solver as general as possible.)
501 tilestate = snewn(w * h * 4, unsigned char);
503 for (i = 0; i < w*h; i++) {
504 tilestate[i * 4] = tiles[i] & 0xF;
505 for (j = 1; j < 4; j++) {
506 if (tilestate[i * 4 + j - 1] == 255 ||
507 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
508 tilestate[i * 4 + j] = 255;
510 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
517 * edgestate stores the known state of each edge. It is 0 for
518 * unknown, 1 for open (connected) and 2 for closed (not
521 * In principle we need only worry about each edge once each,
522 * but in fact it's easier to track each edge twice so that we
523 * can reference it from either side conveniently. Also I'm
524 * going to allocate _five_ bytes per tile, rather than the
525 * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
526 * where d is 1,2,4,8 and they never overlap.
528 edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
529 memset(edgestate, 0, (w * h - 1) * 5 + 9);
532 * deadends tracks which edges have dead ends on them. It is
533 * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
534 * tells you whether heading out of tile (x,y) in direction d
535 * can reach a limited amount of the grid. Values are area+1
536 * (no dead end known) or less than that (can reach _at most_
537 * this many other tiles by heading this way out of this tile).
539 deadends = snewn((w * h - 1) * 5 + 9, int);
540 for (i = 0; i < (w * h - 1) * 5 + 9; i++)
541 deadends[i] = area+1;
544 * equivalence tracks which sets of tiles are known to be
545 * connected to one another, so we can avoid creating loops by
546 * linking together tiles which are already linked through
549 * This is a disjoint set forest structure: equivalence[i]
550 * contains the index of another member of the equivalence
551 * class containing i, or contains i itself for precisely one
552 * member in each such class. To find a representative member
553 * of the equivalence class containing i, you keep replacing i
554 * with equivalence[i] until it stops changing; then you go
555 * _back_ along the same path and point everything on it
556 * directly at the representative member so as to speed up
557 * future searches. Then you test equivalence between tiles by
558 * finding the representative of each tile and seeing if
559 * they're the same; and you create new equivalence (merge
560 * classes) by finding the representative of each tile and
561 * setting equivalence[one]=the_other.
563 equivalence = snew_dsf(w * h);
566 * On a non-wrapping grid, we instantly know that all the edges
567 * round the edge are closed.
570 for (i = 0; i < w; i++) {
571 edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
573 for (i = 0; i < h; i++) {
574 edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
579 * If we have barriers available, we can mark those edges as
583 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
585 for (d = 1; d <= 8; d += d) {
586 if (barriers[y*w+x] & d) {
589 * In principle the barrier list should already
590 * contain each barrier from each side, but
591 * let's not take chances with our internal
594 OFFSETWH(x2, y2, x, y, d, w, h);
595 edgestate[(y*w+x) * 5 + d] = 2;
596 edgestate[(y2*w+x2) * 5 + F(d)] = 2;
603 * Since most deductions made by this solver are local (the
604 * exception is loop avoidance, where joining two tiles
605 * together on one side of the grid can theoretically permit a
606 * fresh deduction on the other), we can address the scaling
607 * problem inherent in iterating repeatedly over the entire
608 * grid by instead working with a to-do list.
610 todo = todo_new(w * h);
613 * Main deductive loop.
615 done_something = TRUE; /* prevent instant termination! */
620 * Take a tile index off the todo list and process it.
622 index = todo_get(todo);
625 * If we have run out of immediate things to do, we
626 * have no choice but to scan the whole grid for
627 * longer-range things we've missed. Hence, I now add
628 * every square on the grid back on to the to-do list.
629 * I also set `done_something' to FALSE at this point;
630 * if we later come back here and find it still FALSE,
631 * we will know we've scanned the entire grid without
632 * finding anything new to do, and we can terminate.
636 for (i = 0; i < w*h; i++)
638 done_something = FALSE;
640 index = todo_get(todo);
646 int d, ourclass = dsf_canonify(equivalence, y*w+x);
649 deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
651 for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
653 int nnondeadends, nondeadends[4], deadendtotal;
654 int nequiv, equiv[5];
655 int val = tilestate[(y*w+x) * 4 + i];
658 nnondeadends = deadendtotal = 0;
661 for (d = 1; d <= 8; d += d) {
663 * Immediately rule out this orientation if it
664 * conflicts with any known edge.
666 if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
667 (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
672 * Count up the dead-end statistics.
674 if (deadends[(y*w+x) * 5 + d] <= area) {
675 deadendtotal += deadends[(y*w+x) * 5 + d];
677 nondeadends[nnondeadends++] = d;
681 * Ensure we aren't linking to any tiles,
682 * through edges not already known to be
683 * open, which create a loop.
685 if (edgestate[(y*w+x) * 5 + d] == 0) {
688 OFFSETWH(x2, y2, x, y, d, w, h);
689 c = dsf_canonify(equivalence, y2*w+x2);
690 for (k = 0; k < nequiv; k++)
701 if (nnondeadends == 0) {
703 * If this orientation links together dead-ends
704 * with a total area of less than the entire
705 * grid, it is invalid.
707 * (We add 1 to deadendtotal because of the
708 * tile itself, of course; one tile linking
709 * dead ends of size 2 and 3 forms a subnetwork
710 * with a total area of 6, not 5.)
712 if (deadendtotal > 0 && deadendtotal+1 < area)
714 } else if (nnondeadends == 1) {
716 * If this orientation links together one or
717 * more dead-ends with precisely one
718 * non-dead-end, then we may have to mark that
719 * non-dead-end as a dead end going the other
720 * way. However, it depends on whether all
721 * other orientations share the same property.
724 if (deadendmax[nondeadends[0]] < deadendtotal)
725 deadendmax[nondeadends[0]] = deadendtotal;
728 * If this orientation links together two or
729 * more non-dead-ends, then we can rule out the
730 * possibility of putting in new dead-end
731 * markings in those directions.
734 for (k = 0; k < nnondeadends; k++)
735 deadendmax[nondeadends[k]] = area+1;
739 tilestate[(y*w+x) * 4 + j++] = val;
740 #ifdef SOLVER_DIAGNOSTICS
742 printf("ruling out orientation %x at %d,%d\n", val, x, y);
747 /* If we've ruled out all possible orientations for a
748 * tile, then our puzzle has no solution at all. */
753 done_something = TRUE;
756 * We have ruled out at least one tile orientation.
757 * Make sure the rest are blanked.
760 tilestate[(y*w+x) * 4 + j++] = 255;
764 * Now go through the tile orientations again and see
765 * if we've deduced anything new about any edges.
771 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
772 a &= tilestate[(y*w+x) * 4 + i];
773 o |= tilestate[(y*w+x) * 4 + i];
775 for (d = 1; d <= 8; d += d)
776 if (edgestate[(y*w+x) * 5 + d] == 0) {
778 OFFSETWH(x2, y2, x, y, d, w, h);
781 /* This edge is open in all orientations. */
782 #ifdef SOLVER_DIAGNOSTICS
783 printf("marking edge %d,%d:%d open\n", x, y, d);
785 edgestate[(y*w+x) * 5 + d] = 1;
786 edgestate[(y2*w+x2) * 5 + d2] = 1;
787 dsf_merge(equivalence, y*w+x, y2*w+x2);
788 done_something = TRUE;
789 todo_add(todo, y2*w+x2);
790 } else if (!(o & d)) {
791 /* This edge is closed in all orientations. */
792 #ifdef SOLVER_DIAGNOSTICS
793 printf("marking edge %d,%d:%d closed\n", x, y, d);
795 edgestate[(y*w+x) * 5 + d] = 2;
796 edgestate[(y2*w+x2) * 5 + d2] = 2;
797 done_something = TRUE;
798 todo_add(todo, y2*w+x2);
805 * Now check the dead-end markers and see if any of
806 * them has lowered from the real ones.
808 for (d = 1; d <= 8; d += d) {
810 OFFSETWH(x2, y2, x, y, d, w, h);
812 if (deadendmax[d] > 0 &&
813 deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
814 #ifdef SOLVER_DIAGNOSTICS
815 printf("setting dead end value %d,%d:%d to %d\n",
816 x2, y2, d2, deadendmax[d]);
818 deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
819 done_something = TRUE;
820 todo_add(todo, y2*w+x2);
828 * Mark all completely determined tiles as locked.
831 for (i = 0; i < w*h; i++) {
832 if (tilestate[i * 4 + 1] == 255) {
833 assert(tilestate[i * 4 + 0] != 255);
834 tiles[i] = tilestate[i * 4] | LOCKED;
842 * Free up working space.
853 /* ----------------------------------------------------------------------
854 * Randomly select a new game description.
858 * Function to randomly perturb an ambiguous section in a grid, to
859 * attempt to ensure unique solvability.
861 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
862 random_state *rs, int startx, int starty, int startd)
864 struct xyd *perimeter, *perim2, *loop[2], looppos[2];
865 int nperim, perimsize, nloop[2], loopsize[2];
869 * We know that the tile at (startx,starty) is part of an
870 * ambiguous section, and we also know that its neighbour in
871 * direction startd is fully specified. We begin by tracing all
872 * the way round the ambiguous area.
874 nperim = perimsize = 0;
879 #ifdef PERTURB_DIAGNOSTICS
880 printf("perturb %d,%d:%d\n", x, y, d);
885 if (nperim >= perimsize) {
886 perimsize = perimsize * 3 / 2 + 32;
887 perimeter = sresize(perimeter, perimsize, struct xyd);
889 perimeter[nperim].x = x;
890 perimeter[nperim].y = y;
891 perimeter[nperim].direction = d;
893 #ifdef PERTURB_DIAGNOSTICS
894 printf("perimeter: %d,%d:%d\n", x, y, d);
898 * First, see if we can simply turn left from where we are
899 * and find another locked square.
902 OFFSETWH(x2, y2, x, y, d2, w, h);
903 if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
904 (tiles[y2*w+x2] & LOCKED)) {
908 * Failing that, step left into the new square and look
913 OFFSETWH(x2, y2, x, y, d, w, h);
914 if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
915 !(tiles[y2*w+x2] & LOCKED)) {
917 * And failing _that_, we're going to have to step
918 * forward into _that_ square and look right at the
919 * same locked square as we started with.
927 } while (x != startx || y != starty || d != startd);
930 * Our technique for perturbing this ambiguous area is to
931 * search round its edge for a join we can make: that is, an
932 * edge on the perimeter which is (a) not currently connected,
933 * and (b) connecting it would not yield a full cross on either
934 * side. Then we make that join, search round the network to
935 * find the loop thus constructed, and sever the loop at a
936 * randomly selected other point.
938 perim2 = snewn(nperim, struct xyd);
939 memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
940 /* Shuffle the perimeter, so as to search it without directional bias. */
941 shuffle(perim2, nperim, sizeof(*perim2), rs);
942 for (i = 0; i < nperim; i++) {
947 d = perim2[i].direction;
949 OFFSETWH(x2, y2, x, y, d, w, h);
950 if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
951 continue; /* can't link across non-wrapping border */
952 if (tiles[y*w+x] & d)
953 continue; /* already linked in this direction! */
954 if (((tiles[y*w+x] | d) & 15) == 15)
955 continue; /* can't turn this tile into a cross */
956 if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
957 continue; /* can't turn other tile into a cross */
960 * We've found the point at which we're going to make a new
963 #ifdef PERTURB_DIAGNOSTICS
964 printf("linking %d,%d:%d\n", x, y, d);
967 tiles[y2*w+x2] |= F(d);
975 return; /* nothing we can do! */
979 * Now we've constructed a new link, we need to find the entire
980 * loop of which it is a part.
982 * In principle, this involves doing a complete search round
983 * the network. However, I anticipate that in the vast majority
984 * of cases the loop will be quite small, so what I'm going to
985 * do is make _two_ searches round the network in parallel, one
986 * keeping its metaphorical hand on the left-hand wall while
987 * the other keeps its hand on the right. As soon as one of
988 * them gets back to its starting point, I abandon the other.
990 for (i = 0; i < 2; i++) {
991 loopsize[i] = nloop[i] = 0;
995 looppos[i].direction = d;
998 for (i = 0; i < 2; i++) {
1003 d = looppos[i].direction;
1005 OFFSETWH(x2, y2, x, y, d, w, h);
1008 * Add this path segment to the loop, unless it exactly
1009 * reverses the previous one on the loop in which case
1010 * we take it away again.
1012 #ifdef PERTURB_DIAGNOSTICS
1013 printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
1016 loop[i][nloop[i]-1].x == x2 &&
1017 loop[i][nloop[i]-1].y == y2 &&
1018 loop[i][nloop[i]-1].direction == F(d)) {
1019 #ifdef PERTURB_DIAGNOSTICS
1020 printf("removing path segment %d,%d:%d from loop[%d]\n",
1025 if (nloop[i] >= loopsize[i]) {
1026 loopsize[i] = loopsize[i] * 3 / 2 + 32;
1027 loop[i] = sresize(loop[i], loopsize[i], struct xyd);
1029 #ifdef PERTURB_DIAGNOSTICS
1030 printf("adding path segment %d,%d:%d to loop[%d]\n",
1033 loop[i][nloop[i]++] = looppos[i];
1036 #ifdef PERTURB_DIAGNOSTICS
1037 printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
1040 for (j = 0; j < 4; j++) {
1045 #ifdef PERTURB_DIAGNOSTICS
1046 printf("trying dir %d\n", d);
1048 if (tiles[y2*w+x2] & d) {
1051 looppos[i].direction = d;
1057 assert(nloop[i] > 0);
1059 if (looppos[i].x == loop[i][0].x &&
1060 looppos[i].y == loop[i][0].y &&
1061 looppos[i].direction == loop[i][0].direction) {
1062 #ifdef PERTURB_DIAGNOSTICS
1063 printf("loop %d finished tracking\n", i);
1067 * Having found our loop, we now sever it at a
1068 * randomly chosen point - absolutely any will do -
1069 * which is not the one we joined it at to begin
1070 * with. Conveniently, the one we joined it at is
1071 * loop[i][0], so we just avoid that one.
1073 j = random_upto(rs, nloop[i]-1) + 1;
1076 d = loop[i][j].direction;
1077 OFFSETWH(x2, y2, x, y, d, w, h);
1079 tiles[y2*w+x2] &= ~F(d);
1091 * Finally, we must mark the entire disputed section as locked,
1092 * to prevent the perturb function being called on it multiple
1095 * To do this, we _sort_ the perimeter of the area. The
1096 * existing xyd_cmp function will arrange things into columns
1097 * for us, in such a way that each column has the edges in
1098 * vertical order. Then we can work down each column and fill
1099 * in all the squares between an up edge and a down edge.
1101 qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1103 for (i = 0; i <= nperim; i++) {
1104 if (i == nperim || perimeter[i].x > x) {
1106 * Fill in everything from the last Up edge to the
1107 * bottom of the grid, if necessary.
1111 #ifdef PERTURB_DIAGNOSTICS
1112 printf("resolved: locking tile %d,%d\n", x, y);
1114 tiles[y * w + x] |= LOCKED;
1127 if (perimeter[i].direction == U) {
1130 } else if (perimeter[i].direction == D) {
1132 * Fill in everything from the last Up edge to here.
1134 assert(x == perimeter[i].x && y <= perimeter[i].y);
1135 while (y <= perimeter[i].y) {
1136 #ifdef PERTURB_DIAGNOSTICS
1137 printf("resolved: locking tile %d,%d\n", x, y);
1139 tiles[y * w + x] |= LOCKED;
1149 static int *compute_loops_inner(int w, int h, int wrapping,
1150 const unsigned char *tiles,
1151 const unsigned char *barriers);
1153 static char *new_game_desc(const game_params *params, random_state *rs,
1154 char **aux, int interactive)
1156 tree234 *possibilities, *barriertree;
1157 int w, h, x, y, cx, cy, nbarriers;
1158 unsigned char *tiles, *barriers;
1167 tiles = snewn(w * h, unsigned char);
1168 barriers = snewn(w * h, unsigned char);
1172 memset(tiles, 0, w * h);
1173 memset(barriers, 0, w * h);
1176 * Construct the unshuffled grid.
1178 * To do this, we simply start at the centre point, repeatedly
1179 * choose a random possibility out of the available ways to
1180 * extend a used square into an unused one, and do it. After
1181 * extending the third line out of a square, we remove the
1182 * fourth from the possibilities list to avoid any full-cross
1183 * squares (which would make the game too easy because they
1184 * only have one orientation).
1186 * The slightly worrying thing is the avoidance of full-cross
1187 * squares. Can this cause our unsophisticated construction
1188 * algorithm to paint itself into a corner, by getting into a
1189 * situation where there are some unreached squares and the
1190 * only way to reach any of them is to extend a T-piece into a
1193 * Answer: no it can't, and here's a proof.
1195 * Any contiguous group of such unreachable squares must be
1196 * surrounded on _all_ sides by T-pieces pointing away from the
1197 * group. (If not, then there is a square which can be extended
1198 * into one of the `unreachable' ones, and so it wasn't
1199 * unreachable after all.) In particular, this implies that
1200 * each contiguous group of unreachable squares must be
1201 * rectangular in shape (any deviation from that yields a
1202 * non-T-piece next to an `unreachable' square).
1204 * So we have a rectangle of unreachable squares, with T-pieces
1205 * forming a solid border around the rectangle. The corners of
1206 * that border must be connected (since every tile connects all
1207 * the lines arriving in it), and therefore the border must
1208 * form a closed loop around the rectangle.
1210 * But this can't have happened in the first place, since we
1211 * _know_ we've avoided creating closed loops! Hence, no such
1212 * situation can ever arise, and the naive grid construction
1213 * algorithm will guaranteeably result in a complete grid
1214 * containing no unreached squares, no full crosses _and_ no
1217 possibilities = newtree234(xyd_cmp_nc);
1220 add234(possibilities, new_xyd(cx, cy, R));
1222 add234(possibilities, new_xyd(cx, cy, U));
1224 add234(possibilities, new_xyd(cx, cy, L));
1226 add234(possibilities, new_xyd(cx, cy, D));
1228 while (count234(possibilities) > 0) {
1231 int x1, y1, d1, x2, y2, d2, d;
1234 * Extract a randomly chosen possibility from the list.
1236 i = random_upto(rs, count234(possibilities));
1237 xyd = delpos234(possibilities, i);
1240 d1 = xyd->direction;
1243 OFFSET(x2, y2, x1, y1, d1, params);
1245 #ifdef GENERATION_DIAGNOSTICS
1246 printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1247 x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1251 * Make the connection. (We should be moving to an as yet
1254 index(params, tiles, x1, y1) |= d1;
1255 assert(index(params, tiles, x2, y2) == 0);
1256 index(params, tiles, x2, y2) |= d2;
1259 * If we have created a T-piece, remove its last
1262 if (COUNT(index(params, tiles, x1, y1)) == 3) {
1263 struct xyd xyd1, *xydp;
1267 xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1269 xydp = find234(possibilities, &xyd1, NULL);
1272 #ifdef GENERATION_DIAGNOSTICS
1273 printf("T-piece; removing (%d,%d,%c)\n",
1274 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1276 del234(possibilities, xydp);
1282 * Remove all other possibilities that were pointing at the
1283 * tile we've just moved into.
1285 for (d = 1; d < 0x10; d <<= 1) {
1287 struct xyd xyd1, *xydp;
1289 OFFSET(x3, y3, x2, y2, d, params);
1294 xyd1.direction = d3;
1296 xydp = find234(possibilities, &xyd1, NULL);
1299 #ifdef GENERATION_DIAGNOSTICS
1300 printf("Loop avoidance; removing (%d,%d,%c)\n",
1301 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1303 del234(possibilities, xydp);
1309 * Add new possibilities to the list for moving _out_ of
1310 * the tile we have just moved into.
1312 for (d = 1; d < 0x10; d <<= 1) {
1316 continue; /* we've got this one already */
1318 if (!params->wrapping) {
1319 if (d == U && y2 == 0)
1321 if (d == D && y2 == h-1)
1323 if (d == L && x2 == 0)
1325 if (d == R && x2 == w-1)
1329 OFFSET(x3, y3, x2, y2, d, params);
1331 if (index(params, tiles, x3, y3))
1332 continue; /* this would create a loop */
1334 #ifdef GENERATION_DIAGNOSTICS
1335 printf("New frontier; adding (%d,%d,%c)\n",
1336 x2, y2, "0RU3L567D9abcdef"[d]);
1338 add234(possibilities, new_xyd(x2, y2, d));
1341 /* Having done that, we should have no possibilities remaining. */
1342 assert(count234(possibilities) == 0);
1343 freetree234(possibilities);
1345 if (params->unique) {
1349 * Run the solver to check unique solubility.
1351 while (net_solver(w, h, tiles, NULL, params->wrapping) != 1) {
1355 * We expect (in most cases) that most of the grid will
1356 * be uniquely specified already, and the remaining
1357 * ambiguous sections will be small and separate. So
1358 * our strategy is to find each individual such
1359 * section, and perform a perturbation on the network
1362 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1363 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1365 if (tiles[y*w+x] & LOCKED)
1366 perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1368 perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1370 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1372 if (tiles[y*w+x] & LOCKED)
1373 perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1375 perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1380 * Now n counts the number of ambiguous sections we
1381 * have fiddled with. If we haven't managed to decrease
1382 * it from the last time we ran the solver, give up and
1383 * regenerate the entire grid.
1385 if (prevn != -1 && prevn <= n)
1386 goto begin_generation; /* (sorry) */
1392 * The solver will have left a lot of LOCKED bits lying
1393 * around in the tiles array. Remove them.
1395 for (x = 0; x < w*h; x++)
1396 tiles[x] &= ~LOCKED;
1400 * Now compute a list of the possible barrier locations.
1402 barriertree = newtree234(xyd_cmp_nc);
1403 for (y = 0; y < h; y++) {
1404 for (x = 0; x < w; x++) {
1406 if (!(index(params, tiles, x, y) & R) &&
1407 (params->wrapping || x < w-1))
1408 add234(barriertree, new_xyd(x, y, R));
1409 if (!(index(params, tiles, x, y) & D) &&
1410 (params->wrapping || y < h-1))
1411 add234(barriertree, new_xyd(x, y, D));
1416 * Save the unshuffled grid in aux.
1422 solution = snewn(w * h + 1, char);
1423 for (i = 0; i < w * h; i++)
1424 solution[i] = "0123456789abcdef"[tiles[i] & 0xF];
1425 solution[w*h] = '\0';
1431 * Now shuffle the grid.
1433 * In order to avoid accidentally generating an already-solved
1434 * grid, we will reshuffle as necessary to ensure that at least
1435 * one edge has a mismatched connection.
1437 * This can always be done, since validate_params() enforces a
1438 * grid area of at least 2 and our generator never creates
1439 * either type of rotationally invariant tile (cross and
1440 * blank). Hence there must be at least one edge separating
1441 * distinct tiles, and it must be possible to find orientations
1442 * of those tiles such that one tile is trying to connect
1443 * through that edge and the other is not.
1445 * (We could be more subtle, and allow the shuffle to generate
1446 * a grid in which all tiles match up locally and the only
1447 * criterion preventing the grid from being already solved is
1448 * connectedness. However, that would take more effort, and
1449 * it's easier to simply make sure every grid is _obviously_
1452 * We also require that our shuffle produces no loops in the
1453 * initial grid state, because it's a bit rude to light up a 'HEY,
1454 * YOU DID SOMETHING WRONG!' indicator when the user hasn't even
1455 * had a chance to do _anything_ yet. This also is possible just
1456 * by retrying the whole shuffle on failure, because it's clear
1457 * that at least one non-solved shuffle with no loops must exist.
1458 * (Proof: take the _solved_ state of the puzzle, and rotate one
1462 int mismatches, prev_loopsquares, this_loopsquares, i;
1466 for (y = 0; y < h; y++) {
1467 for (x = 0; x < w; x++) {
1468 int orig = index(params, tiles, x, y);
1469 int rot = random_upto(rs, 4);
1470 index(params, tiles, x, y) = ROT(orig, rot);
1475 * Check for loops, and try to fix them by reshuffling just
1476 * the squares involved.
1478 prev_loopsquares = w*h+1;
1480 loops = compute_loops_inner(w, h, params->wrapping, tiles, NULL);
1481 this_loopsquares = 0;
1482 for (i = 0; i < w*h; i++) {
1484 int orig = tiles[i];
1485 int rot = random_upto(rs, 4);
1486 tiles[i] = ROT(orig, rot);
1491 if (this_loopsquares > prev_loopsquares) {
1493 * We're increasing rather than reducing the number of
1494 * loops. Give up and go back to the full shuffle.
1498 if (this_loopsquares == 0)
1500 prev_loopsquares = this_loopsquares;
1505 * I can't even be bothered to check for mismatches across
1506 * a wrapping edge, so I'm just going to enforce that there
1507 * must be a mismatch across a non-wrapping edge, which is
1508 * still always possible.
1510 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1511 if (x+1 < w && ((ROT(index(params, tiles, x, y), 2) ^
1512 index(params, tiles, x+1, y)) & L))
1514 if (y+1 < h && ((ROT(index(params, tiles, x, y), 2) ^
1515 index(params, tiles, x, y+1)) & U))
1519 if (mismatches == 0)
1527 * And now choose barrier locations. (We carefully do this
1528 * _after_ shuffling, so that changing the barrier rate in the
1529 * params while keeping the random seed the same will give the
1530 * same shuffled grid and _only_ change the barrier locations.
1531 * Also the way we choose barrier locations, by repeatedly
1532 * choosing one possibility from the list until we have enough,
1533 * is designed to ensure that raising the barrier rate while
1534 * keeping the seed the same will provide a superset of the
1535 * previous barrier set - i.e. if you ask for 10 barriers, and
1536 * then decide that's still too hard and ask for 20, you'll get
1537 * the original 10 plus 10 more, rather than getting 20 new
1538 * ones and the chance of remembering your first 10.)
1540 nbarriers = (int)(params->barrier_probability * count234(barriertree));
1541 assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1543 while (nbarriers > 0) {
1546 int x1, y1, d1, x2, y2, d2;
1549 * Extract a randomly chosen barrier from the list.
1551 i = random_upto(rs, count234(barriertree));
1552 xyd = delpos234(barriertree, i);
1554 assert(xyd != NULL);
1558 d1 = xyd->direction;
1561 OFFSET(x2, y2, x1, y1, d1, params);
1564 index(params, barriers, x1, y1) |= d1;
1565 index(params, barriers, x2, y2) |= d2;
1571 * Clean up the rest of the barrier list.
1576 while ( (xyd = delpos234(barriertree, 0)) != NULL)
1579 freetree234(barriertree);
1583 * Finally, encode the grid into a string game description.
1585 * My syntax is extremely simple: each square is encoded as a
1586 * hex digit in which bit 0 means a connection on the right,
1587 * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1588 * encoding as used internally). Each digit is followed by
1589 * optional barrier indicators: `v' means a vertical barrier to
1590 * the right of it, and `h' means a horizontal barrier below
1593 desc = snewn(w * h * 3 + 1, char);
1595 for (y = 0; y < h; y++) {
1596 for (x = 0; x < w; x++) {
1597 *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1598 if ((params->wrapping || x < w-1) &&
1599 (index(params, barriers, x, y) & R))
1601 if ((params->wrapping || y < h-1) &&
1602 (index(params, barriers, x, y) & D))
1606 assert(p - desc <= w*h*3);
1615 static char *validate_desc(const game_params *params, const char *desc)
1617 int w = params->width, h = params->height;
1620 for (i = 0; i < w*h; i++) {
1621 if (*desc >= '0' && *desc <= '9')
1623 else if (*desc >= 'a' && *desc <= 'f')
1625 else if (*desc >= 'A' && *desc <= 'F')
1628 return "Game description shorter than expected";
1630 return "Game description contained unexpected character";
1632 while (*desc == 'h' || *desc == 'v')
1636 return "Game description longer than expected";
1641 /* ----------------------------------------------------------------------
1642 * Construct an initial game state, given a description and parameters.
1645 static game_state *new_game(midend *me, const game_params *params,
1651 assert(params->width > 0 && params->height > 0);
1652 assert(params->width > 1 || params->height > 1);
1655 * Create a blank game state.
1657 state = snew(game_state);
1658 w = state->width = params->width;
1659 h = state->height = params->height;
1660 state->wrapping = params->wrapping;
1661 state->imm = snew(game_immutable_state);
1662 state->imm->refcount = 1;
1663 state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1664 state->completed = state->used_solve = FALSE;
1665 state->tiles = snewn(state->width * state->height, unsigned char);
1666 memset(state->tiles, 0, state->width * state->height);
1667 state->imm->barriers = snewn(state->width * state->height, unsigned char);
1668 memset(state->imm->barriers, 0, state->width * state->height);
1671 * Parse the game description into the grid.
1673 for (y = 0; y < h; y++) {
1674 for (x = 0; x < w; x++) {
1675 if (*desc >= '0' && *desc <= '9')
1676 tile(state, x, y) = *desc - '0';
1677 else if (*desc >= 'a' && *desc <= 'f')
1678 tile(state, x, y) = *desc - 'a' + 10;
1679 else if (*desc >= 'A' && *desc <= 'F')
1680 tile(state, x, y) = *desc - 'A' + 10;
1683 while (*desc == 'h' || *desc == 'v') {
1690 OFFSET(x2, y2, x, y, d1, state);
1693 barrier(state, x, y) |= d1;
1694 barrier(state, x2, y2) |= d2;
1702 * Set up border barriers if this is a non-wrapping game.
1704 if (!state->wrapping) {
1705 for (x = 0; x < state->width; x++) {
1706 barrier(state, x, 0) |= U;
1707 barrier(state, x, state->height-1) |= D;
1709 for (y = 0; y < state->height; y++) {
1710 barrier(state, 0, y) |= L;
1711 barrier(state, state->width-1, y) |= R;
1715 * We check whether this is de-facto a non-wrapping game
1716 * despite the parameters, in case we were passed the
1717 * description of a non-wrapping game. This is so that we
1718 * can change some aspects of the UI behaviour.
1720 state->wrapping = FALSE;
1721 for (x = 0; x < state->width; x++)
1722 if (!(barrier(state, x, 0) & U) ||
1723 !(barrier(state, x, state->height-1) & D))
1724 state->wrapping = TRUE;
1725 for (y = 0; y < state->height; y++)
1726 if (!(barrier(state, 0, y) & L) ||
1727 !(barrier(state, state->width-1, y) & R))
1728 state->wrapping = TRUE;
1734 static game_state *dup_game(const game_state *state)
1738 ret = snew(game_state);
1739 ret->imm = state->imm;
1740 ret->imm->refcount++;
1741 ret->width = state->width;
1742 ret->height = state->height;
1743 ret->wrapping = state->wrapping;
1744 ret->completed = state->completed;
1745 ret->used_solve = state->used_solve;
1746 ret->last_rotate_dir = state->last_rotate_dir;
1747 ret->last_rotate_x = state->last_rotate_x;
1748 ret->last_rotate_y = state->last_rotate_y;
1749 ret->tiles = snewn(state->width * state->height, unsigned char);
1750 memcpy(ret->tiles, state->tiles, state->width * state->height);
1755 static void free_game(game_state *state)
1757 if (--state->imm->refcount == 0) {
1758 sfree(state->imm->barriers);
1761 sfree(state->tiles);
1765 static char *solve_game(const game_state *state, const game_state *currstate,
1766 const char *aux, char **error)
1768 unsigned char *tiles;
1770 int retlen, retsize;
1773 tiles = snewn(state->width * state->height, unsigned char);
1777 * Run the internal solver on the provided grid. This might
1778 * not yield a complete solution.
1782 memcpy(tiles, state->tiles, state->width * state->height);
1783 solver_result = net_solver(state->width, state->height, tiles,
1784 state->imm->barriers, state->wrapping);
1786 if (solver_result < 0) {
1787 *error = "No solution exists for this puzzle";
1792 for (i = 0; i < state->width * state->height; i++) {
1795 if (c >= '0' && c <= '9')
1797 else if (c >= 'a' && c <= 'f')
1798 tiles[i] = c - 'a' + 10;
1799 else if (c >= 'A' && c <= 'F')
1800 tiles[i] = c - 'A' + 10;
1807 * Now construct a string which can be passed to execute_move()
1808 * to transform the current grid into the solved one.
1811 ret = snewn(retsize, char);
1813 ret[retlen++] = 'S';
1815 for (i = 0; i < state->width * state->height; i++) {
1816 int from = currstate->tiles[i], to = tiles[i];
1817 int ft = from & (R|L|U|D), tt = to & (R|L|U|D);
1818 int x = i % state->width, y = i / state->width;
1820 char buf[80], *p = buf;
1823 continue; /* nothing needs doing at all */
1826 * To transform this tile into the desired tile: first
1827 * unlock the tile if it's locked, then rotate it if
1828 * necessary, then lock it if necessary.
1831 p += sprintf(p, ";L%d,%d", x, y);
1835 else if (tt == C(ft))
1837 else if (tt == F(ft))
1844 p += sprintf(p, ";%c%d,%d", chr, x, y);
1847 p += sprintf(p, ";L%d,%d", x, y);
1850 if (retlen + (p - buf) >= retsize) {
1851 retsize = retlen + (p - buf) + 512;
1852 ret = sresize(ret, retsize, char);
1854 memcpy(ret+retlen, buf, p - buf);
1859 assert(retlen < retsize);
1861 ret = sresize(ret, retlen+1, char);
1868 static int game_can_format_as_text_now(const game_params *params)
1873 static char *game_text_format(const game_state *state)
1878 /* ----------------------------------------------------------------------
1883 * Compute which squares are reachable from the centre square, as a
1884 * quick visual aid to determining how close the game is to
1885 * completion. This is also a simple way to tell if the game _is_
1886 * completed - just call this function and see whether every square
1889 static unsigned char *compute_active(const game_state *state, int cx, int cy)
1891 unsigned char *active;
1895 active = snewn(state->width * state->height, unsigned char);
1896 memset(active, 0, state->width * state->height);
1899 * We only store (x,y) pairs in todo, but it's easier to reuse
1900 * xyd_cmp and just store direction 0 every time.
1902 todo = newtree234(xyd_cmp_nc);
1903 index(state, active, cx, cy) = ACTIVE;
1904 add234(todo, new_xyd(cx, cy, 0));
1906 while ( (xyd = delpos234(todo, 0)) != NULL) {
1907 int x1, y1, d1, x2, y2, d2;
1913 for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1914 OFFSET(x2, y2, x1, y1, d1, state);
1918 * If the next tile in this direction is connected to
1919 * us, and there isn't a barrier in the way, and it
1920 * isn't already marked active, then mark it active and
1921 * add it to the to-examine list.
1923 if ((tile(state, x1, y1) & d1) &&
1924 (tile(state, x2, y2) & d2) &&
1925 !(barrier(state, x1, y1) & d1) &&
1926 !index(state, active, x2, y2)) {
1927 index(state, active, x2, y2) = ACTIVE;
1928 add234(todo, new_xyd(x2, y2, 0));
1932 /* Now we expect the todo list to have shrunk to zero size. */
1933 assert(count234(todo) == 0);
1939 struct net_neighbour_ctx {
1941 const unsigned char *tiles, *barriers;
1942 int i, n, neighbours[4];
1944 static int net_neighbour(int vertex, void *vctx)
1946 struct net_neighbour_ctx *ctx = (struct net_neighbour_ctx *)vctx;
1949 int x = vertex % ctx->w, y = vertex / ctx->w;
1950 int tile, dir, x1, y1, v1;
1952 ctx->i = ctx->n = 0;
1954 tile = ctx->tiles[vertex];
1956 tile &= ~ctx->barriers[vertex];
1958 for (dir = 1; dir < 0x10; dir <<= 1) {
1961 OFFSETWH(x1, y1, x, y, dir, ctx->w, ctx->h);
1962 v1 = y1 * ctx->w + x1;
1963 if (ctx->tiles[v1] & F(dir))
1964 ctx->neighbours[ctx->n++] = v1;
1968 if (ctx->i < ctx->n)
1969 return ctx->neighbours[ctx->i++];
1974 static int *compute_loops_inner(int w, int h, int wrapping,
1975 const unsigned char *tiles,
1976 const unsigned char *barriers)
1978 struct net_neighbour_ctx ctx;
1979 struct findloopstate *fls;
1983 fls = findloop_new_state(w*h);
1987 ctx.barriers = barriers;
1988 findloop_run(fls, w*h, net_neighbour, &ctx);
1990 loops = snewn(w*h, int);
1992 for (y = 0; y < h; y++) {
1993 for (x = 0; x < w; x++) {
1997 for (dir = 1; dir < 0x10; dir <<= 1) {
1998 if ((tiles[y*w+x] & dir) &&
1999 !(barriers && (barriers[y*w+x] & dir))) {
2000 OFFSETWH(x1, y1, x, y, dir, w, h);
2001 if ((tiles[y1*w+x1] & F(dir)) &&
2002 findloop_is_loop_edge(fls, y*w+x, y1*w+x1))
2006 loops[y*w+x] = flags;
2010 findloop_free_state(fls);
2014 static int *compute_loops(const game_state *state)
2016 return compute_loops_inner(state->width, state->height, state->wrapping,
2017 state->tiles, state->imm->barriers);
2021 int org_x, org_y; /* origin */
2022 int cx, cy; /* source tile (game coordinates) */
2025 random_state *rs; /* used for jumbling */
2027 int dragtilex, dragtiley, dragstartx, dragstarty, dragged;
2031 static game_ui *new_ui(const game_state *state)
2035 game_ui *ui = snew(game_ui);
2036 ui->org_x = ui->org_y = 0;
2037 ui->cur_x = ui->cx = state->width / 2;
2038 ui->cur_y = ui->cy = state->height / 2;
2039 ui->cur_visible = FALSE;
2040 get_random_seed(&seed, &seedsize);
2041 ui->rs = random_new(seed, seedsize);
2047 static void free_ui(game_ui *ui)
2049 random_free(ui->rs);
2053 static char *encode_ui(const game_ui *ui)
2057 * We preserve the origin and centre-point coordinates over a
2060 sprintf(buf, "O%d,%d;C%d,%d", ui->org_x, ui->org_y, ui->cx, ui->cy);
2064 static void decode_ui(game_ui *ui, const char *encoding)
2066 sscanf(encoding, "O%d,%d;C%d,%d",
2067 &ui->org_x, &ui->org_y, &ui->cx, &ui->cy);
2070 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2071 const game_state *newstate)
2075 struct game_drawstate {
2083 /* ----------------------------------------------------------------------
2086 static char *interpret_move(const game_state *state, game_ui *ui,
2087 const game_drawstate *ds,
2088 int x, int y, int button)
2091 int tx = -1, ty = -1, dir = 0;
2092 int shift = button & MOD_SHFT, ctrl = button & MOD_CTRL;
2094 NONE, ROTATE_LEFT, ROTATE_180, ROTATE_RIGHT, TOGGLE_LOCK, JUMBLE,
2095 MOVE_ORIGIN, MOVE_SOURCE, MOVE_ORIGIN_AND_SOURCE, MOVE_CURSOR
2098 button &= ~MOD_MASK;
2102 if (button == LEFT_BUTTON ||
2103 button == MIDDLE_BUTTON ||
2105 button == LEFT_DRAG ||
2106 button == LEFT_RELEASE ||
2107 button == RIGHT_DRAG ||
2108 button == RIGHT_RELEASE ||
2110 button == RIGHT_BUTTON) {
2112 if (ui->cur_visible) {
2113 ui->cur_visible = FALSE;
2118 * The button must have been clicked on a valid tile.
2120 x -= WINDOW_OFFSET + TILE_BORDER;
2121 y -= WINDOW_OFFSET + TILE_BORDER;
2126 if (tx >= state->width || ty >= state->height)
2128 /* Transform from physical to game coords */
2129 tx = (tx + ui->org_x) % state->width;
2130 ty = (ty + ui->org_y) % state->height;
2131 if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
2132 y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
2137 if (button == MIDDLE_BUTTON
2139 || button == RIGHT_BUTTON /* with a stylus, `right-click' locks */
2143 * Middle button never drags: it only toggles the lock.
2145 action = TOGGLE_LOCK;
2146 } else if (button == LEFT_BUTTON
2147 #ifndef STYLUS_BASED
2148 || button == RIGHT_BUTTON /* (see above) */
2152 * Otherwise, we note down the start point for a drag.
2156 ui->dragstartx = x % TILE_SIZE;
2157 ui->dragstarty = y % TILE_SIZE;
2158 ui->dragged = FALSE;
2159 return nullret; /* no actual action */
2160 } else if (button == LEFT_DRAG
2161 #ifndef STYLUS_BASED
2162 || button == RIGHT_DRAG
2166 * Find the new drag point and see if it necessitates a
2169 int x0,y0, xA,yA, xC,yC, xF,yF;
2171 int d0, dA, dC, dF, dmin;
2176 mx = x - (ui->dragtilex * TILE_SIZE);
2177 my = y - (ui->dragtiley * TILE_SIZE);
2179 x0 = ui->dragstartx;
2180 y0 = ui->dragstarty;
2181 xA = ui->dragstarty;
2182 yA = TILE_SIZE-1 - ui->dragstartx;
2183 xF = TILE_SIZE-1 - ui->dragstartx;
2184 yF = TILE_SIZE-1 - ui->dragstarty;
2185 xC = TILE_SIZE-1 - ui->dragstarty;
2186 yC = ui->dragstartx;
2188 d0 = (mx-x0)*(mx-x0) + (my-y0)*(my-y0);
2189 dA = (mx-xA)*(mx-xA) + (my-yA)*(my-yA);
2190 dF = (mx-xF)*(mx-xF) + (my-yF)*(my-yF);
2191 dC = (mx-xC)*(mx-xC) + (my-yC)*(my-yC);
2193 dmin = min(min(d0,dA),min(dF,dC));
2197 } else if (dF == dmin) {
2198 action = ROTATE_180;
2199 ui->dragstartx = xF;
2200 ui->dragstarty = yF;
2202 } else if (dA == dmin) {
2203 action = ROTATE_LEFT;
2204 ui->dragstartx = xA;
2205 ui->dragstarty = yA;
2207 } else /* dC == dmin */ {
2208 action = ROTATE_RIGHT;
2209 ui->dragstartx = xC;
2210 ui->dragstarty = yC;
2213 } else if (button == LEFT_RELEASE
2214 #ifndef STYLUS_BASED
2215 || button == RIGHT_RELEASE
2220 * There was a click but no perceptible drag:
2221 * revert to single-click behaviour.
2226 if (button == LEFT_RELEASE)
2227 action = ROTATE_LEFT;
2229 action = ROTATE_RIGHT;
2231 return nullret; /* no action */
2234 #else /* USE_DRAGGING */
2236 action = (button == LEFT_BUTTON ? ROTATE_LEFT :
2237 button == RIGHT_BUTTON ? ROTATE_RIGHT : TOGGLE_LOCK);
2239 #endif /* USE_DRAGGING */
2241 } else if (IS_CURSOR_MOVE(button)) {
2243 case CURSOR_UP: dir = U; break;
2244 case CURSOR_DOWN: dir = D; break;
2245 case CURSOR_LEFT: dir = L; break;
2246 case CURSOR_RIGHT: dir = R; break;
2247 default: return nullret;
2249 if (shift && ctrl) action = MOVE_ORIGIN_AND_SOURCE;
2250 else if (shift) action = MOVE_ORIGIN;
2251 else if (ctrl) action = MOVE_SOURCE;
2252 else action = MOVE_CURSOR;
2253 } else if (button == 'a' || button == 's' || button == 'd' ||
2254 button == 'A' || button == 'S' || button == 'D' ||
2255 button == 'f' || button == 'F' ||
2256 IS_CURSOR_SELECT(button)) {
2259 if (button == 'a' || button == 'A' || button == CURSOR_SELECT)
2260 action = ROTATE_LEFT;
2261 else if (button == 's' || button == 'S' || button == CURSOR_SELECT2)
2262 action = TOGGLE_LOCK;
2263 else if (button == 'd' || button == 'D')
2264 action = ROTATE_RIGHT;
2265 else if (button == 'f' || button == 'F')
2266 action = ROTATE_180;
2267 ui->cur_visible = TRUE;
2268 } else if (button == 'j' || button == 'J') {
2269 /* XXX should we have some mouse control for this? */
2275 * The middle button locks or unlocks a tile. (A locked tile
2276 * cannot be turned, and is visually marked as being locked.
2277 * This is a convenience for the player, so that once they are
2278 * sure which way round a tile goes, they can lock it and thus
2279 * avoid forgetting later on that they'd already done that one;
2280 * and the locking also prevents them turning the tile by
2281 * accident. If they change their mind, another middle click
2284 if (action == TOGGLE_LOCK) {
2286 sprintf(buf, "L%d,%d", tx, ty);
2288 } else if (action == ROTATE_LEFT || action == ROTATE_RIGHT ||
2289 action == ROTATE_180) {
2293 * The left and right buttons have no effect if clicked on a
2296 if (tile(state, tx, ty) & LOCKED)
2300 * Otherwise, turn the tile one way or the other. Left button
2301 * turns anticlockwise; right button turns clockwise.
2303 sprintf(buf, "%c%d,%d", (int)(action == ROTATE_LEFT ? 'A' :
2304 action == ROTATE_RIGHT ? 'C' : 'F'), tx, ty);
2306 } else if (action == JUMBLE) {
2308 * Jumble all unlocked tiles to random orientations.
2315 * Maximum string length assumes no int can be converted to
2316 * decimal and take more than 11 digits!
2318 maxlen = state->width * state->height * 25 + 3;
2320 ret = snewn(maxlen, char);
2324 for (jy = 0; jy < state->height; jy++) {
2325 for (jx = 0; jx < state->width; jx++) {
2326 if (!(tile(state, jx, jy) & LOCKED)) {
2327 int rot = random_upto(ui->rs, 4);
2329 p += sprintf(p, ";%c%d,%d", "AFC"[rot-1], jx, jy);
2335 assert(p - ret < maxlen);
2336 ret = sresize(ret, p - ret, char);
2339 } else if (action == MOVE_ORIGIN || action == MOVE_SOURCE ||
2340 action == MOVE_ORIGIN_AND_SOURCE || action == MOVE_CURSOR) {
2342 if (action == MOVE_ORIGIN || action == MOVE_ORIGIN_AND_SOURCE) {
2343 if (state->wrapping) {
2344 OFFSET(ui->org_x, ui->org_y, ui->org_x, ui->org_y, dir, state);
2345 } else return nullret; /* disallowed for non-wrapping grids */
2347 if (action == MOVE_SOURCE || action == MOVE_ORIGIN_AND_SOURCE) {
2348 OFFSET(ui->cx, ui->cy, ui->cx, ui->cy, dir, state);
2350 if (action == MOVE_CURSOR) {
2351 OFFSET(ui->cur_x, ui->cur_y, ui->cur_x, ui->cur_y, dir, state);
2352 ui->cur_visible = TRUE;
2360 static game_state *execute_move(const game_state *from, const char *move)
2363 int tx = -1, ty = -1, n, noanim, orig;
2365 ret = dup_game(from);
2367 if (move[0] == 'J' || move[0] == 'S') {
2369 ret->used_solve = TRUE;
2378 ret->last_rotate_dir = 0; /* suppress animation */
2379 ret->last_rotate_x = ret->last_rotate_y = 0;
2382 if ((move[0] == 'A' || move[0] == 'C' ||
2383 move[0] == 'F' || move[0] == 'L') &&
2384 sscanf(move+1, "%d,%d%n", &tx, &ty, &n) >= 2 &&
2385 tx >= 0 && tx < from->width && ty >= 0 && ty < from->height) {
2386 orig = tile(ret, tx, ty);
2387 if (move[0] == 'A') {
2388 tile(ret, tx, ty) = A(orig);
2390 ret->last_rotate_dir = +1;
2391 } else if (move[0] == 'F') {
2392 tile(ret, tx, ty) = F(orig);
2394 ret->last_rotate_dir = +2; /* + for sake of argument */
2395 } else if (move[0] == 'C') {
2396 tile(ret, tx, ty) = C(orig);
2398 ret->last_rotate_dir = -1;
2400 assert(move[0] == 'L');
2401 tile(ret, tx, ty) ^= LOCKED;
2405 if (*move == ';') move++;
2412 if (tx == -1 || ty == -1) { free_game(ret); return NULL; }
2413 ret->last_rotate_x = tx;
2414 ret->last_rotate_y = ty;
2418 * Check whether the game has been completed.
2420 * For this purpose it doesn't matter where the source square is,
2421 * because we can start from anywhere (or, at least, any square
2422 * that's non-empty!), and correctly determine whether the game is
2426 unsigned char *active;
2428 int complete = TRUE;
2430 for (pos = 0; pos < ret->width * ret->height; pos++)
2431 if (ret->tiles[pos] & 0xF)
2434 if (pos < ret->width * ret->height) {
2435 active = compute_active(ret, pos % ret->width, pos / ret->width);
2437 for (pos = 0; pos < ret->width * ret->height; pos++)
2438 if ((ret->tiles[pos] & 0xF) && !active[pos]) {
2447 ret->completed = TRUE;
2454 /* ----------------------------------------------------------------------
2455 * Routines for drawing the game position on the screen.
2458 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2460 game_drawstate *ds = snew(game_drawstate);
2463 ds->started = FALSE;
2464 ds->width = state->width;
2465 ds->height = state->height;
2466 ds->org_x = ds->org_y = -1;
2467 ds->visible = snewn(state->width * state->height, int);
2468 ds->tilesize = 0; /* undecided yet */
2469 for (i = 0; i < state->width * state->height; i++)
2470 ds->visible[i] = -1;
2475 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2481 static void game_compute_size(const game_params *params, int tilesize,
2484 *x = WINDOW_OFFSET * 2 + tilesize * params->width + TILE_BORDER;
2485 *y = WINDOW_OFFSET * 2 + tilesize * params->height + TILE_BORDER;
2488 static void game_set_size(drawing *dr, game_drawstate *ds,
2489 const game_params *params, int tilesize)
2491 ds->tilesize = tilesize;
2494 static float *game_colours(frontend *fe, int *ncolours)
2498 ret = snewn(NCOLOURS * 3, float);
2499 *ncolours = NCOLOURS;
2502 * Basic background colour is whatever the front end thinks is
2503 * a sensible default.
2505 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2510 ret[COL_WIRE * 3 + 0] = 0.0F;
2511 ret[COL_WIRE * 3 + 1] = 0.0F;
2512 ret[COL_WIRE * 3 + 2] = 0.0F;
2515 * Powered wires and powered endpoints are cyan.
2517 ret[COL_POWERED * 3 + 0] = 0.0F;
2518 ret[COL_POWERED * 3 + 1] = 1.0F;
2519 ret[COL_POWERED * 3 + 2] = 1.0F;
2524 ret[COL_BARRIER * 3 + 0] = 1.0F;
2525 ret[COL_BARRIER * 3 + 1] = 0.0F;
2526 ret[COL_BARRIER * 3 + 2] = 0.0F;
2529 * Highlighted loops are red as well.
2531 ret[COL_LOOP * 3 + 0] = 1.0F;
2532 ret[COL_LOOP * 3 + 1] = 0.0F;
2533 ret[COL_LOOP * 3 + 2] = 0.0F;
2536 * Unpowered endpoints are blue.
2538 ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2539 ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2540 ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2543 * Tile borders are a darker grey than the background.
2545 ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2546 ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2547 ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2550 * Locked tiles are a grey in between those two.
2552 ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2553 ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2554 ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2559 static void draw_filled_line(drawing *dr, int x1, int y1, int x2, int y2,
2562 draw_line(dr, x1-1, y1, x2-1, y2, COL_WIRE);
2563 draw_line(dr, x1+1, y1, x2+1, y2, COL_WIRE);
2564 draw_line(dr, x1, y1-1, x2, y2-1, COL_WIRE);
2565 draw_line(dr, x1, y1+1, x2, y2+1, COL_WIRE);
2566 draw_line(dr, x1, y1, x2, y2, colour);
2569 static void draw_rect_coords(drawing *dr, int x1, int y1, int x2, int y2,
2572 int mx = (x1 < x2 ? x1 : x2);
2573 int my = (y1 < y2 ? y1 : y2);
2574 int dx = (x2 + x1 - 2*mx + 1);
2575 int dy = (y2 + y1 - 2*my + 1);
2577 draw_rect(dr, mx, my, dx, dy, colour);
2581 * draw_barrier_corner() and draw_barrier() are passed physical coords
2583 static void draw_barrier_corner(drawing *dr, game_drawstate *ds,
2584 int x, int y, int dx, int dy, int phase)
2586 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2587 int by = WINDOW_OFFSET + TILE_SIZE * y;
2590 x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2591 y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2594 draw_rect_coords(dr, bx+x1+dx, by+y1,
2595 bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
2597 draw_rect_coords(dr, bx+x1, by+y1+dy,
2598 bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
2601 draw_rect_coords(dr, bx+x1, by+y1,
2602 bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
2607 static void draw_barrier(drawing *dr, game_drawstate *ds,
2608 int x, int y, int dir, int phase)
2610 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2611 int by = WINDOW_OFFSET + TILE_SIZE * y;
2614 x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
2615 y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
2616 w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2617 h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2620 draw_rect(dr, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
2622 draw_rect(dr, bx+x1, by+y1, w, h, COL_BARRIER);
2627 * draw_tile() is passed physical coordinates
2629 static void draw_tile(drawing *dr, const game_state *state, game_drawstate *ds,
2630 int x, int y, int tile, int src, float angle, int cursor)
2632 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2633 int by = WINDOW_OFFSET + TILE_SIZE * y;
2635 float cx, cy, ex, ey, tx, ty;
2636 int dir, col, phase;
2639 * When we draw a single tile, we must draw everything up to
2640 * and including the borders around the tile. This means that
2641 * if the neighbouring tiles have connections to those borders,
2642 * we must draw those connections on the borders themselves.
2645 clip(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2648 * So. First blank the tile out completely: draw a big
2649 * rectangle in border colour, and a smaller rectangle in
2650 * background colour to fill it in.
2652 draw_rect(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
2654 draw_rect(dr, bx+TILE_BORDER, by+TILE_BORDER,
2655 TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
2656 tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
2659 * Draw an inset outline rectangle as a cursor, in whichever of
2660 * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
2664 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2665 bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2666 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2667 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2668 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2669 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2670 draw_line(dr, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2671 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2672 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2673 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2674 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2675 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2679 * Set up the rotation matrix.
2681 matrix[0] = (float)cos(angle * PI / 180.0);
2682 matrix[1] = (float)-sin(angle * PI / 180.0);
2683 matrix[2] = (float)sin(angle * PI / 180.0);
2684 matrix[3] = (float)cos(angle * PI / 180.0);
2689 cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
2690 col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
2691 for (dir = 1; dir < 0x10; dir <<= 1) {
2693 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2694 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2695 MATMUL(tx, ty, matrix, ex, ey);
2696 draw_filled_line(dr, bx+(int)cx, by+(int)cy,
2697 bx+(int)(cx+tx), by+(int)(cy+ty),
2701 for (dir = 1; dir < 0x10; dir <<= 1) {
2703 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2704 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2705 MATMUL(tx, ty, matrix, ex, ey);
2706 draw_line(dr, bx+(int)cx, by+(int)cy,
2707 bx+(int)(cx+tx), by+(int)(cy+ty),
2708 (tile & LOOP(dir)) ? COL_LOOP : col);
2711 /* If we've drawn any loop-highlighted arms, make sure the centre
2712 * point is loop-coloured rather than a later arm overwriting it. */
2713 if (tile & (RLOOP | ULOOP | LLOOP | DLOOP))
2714 draw_rect(dr, bx+(int)cx, by+(int)cy, 1, 1, COL_LOOP);
2717 * Draw the box in the middle. We do this in blue if the tile
2718 * is an unpowered endpoint, in cyan if the tile is a powered
2719 * endpoint, in black if the tile is the centrepiece, and
2720 * otherwise not at all.
2725 else if (COUNT(tile) == 1) {
2726 col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
2731 points[0] = +1; points[1] = +1;
2732 points[2] = +1; points[3] = -1;
2733 points[4] = -1; points[5] = -1;
2734 points[6] = -1; points[7] = +1;
2736 for (i = 0; i < 8; i += 2) {
2737 ex = (TILE_SIZE * 0.24F) * points[i];
2738 ey = (TILE_SIZE * 0.24F) * points[i+1];
2739 MATMUL(tx, ty, matrix, ex, ey);
2740 points[i] = bx+(int)(cx+tx);
2741 points[i+1] = by+(int)(cy+ty);
2744 draw_polygon(dr, points, 4, col, COL_WIRE);
2748 * Draw the points on the border if other tiles are connected
2751 for (dir = 1; dir < 0x10; dir <<= 1) {
2752 int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
2760 if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
2763 if (!(tile(state, GX(ox), GY(oy)) & F(dir)))
2766 px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
2767 py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
2768 lx = dx * (TILE_BORDER-1);
2769 ly = dy * (TILE_BORDER-1);
2773 if (angle == 0.0 && (tile & dir)) {
2775 * If we are fully connected to the other tile, we must
2776 * draw right across the tile border. (We can use our
2777 * own ACTIVE state to determine what colour to do this
2778 * in: if we are fully connected to the other tile then
2779 * the two ACTIVE states will be the same.)
2781 draw_rect_coords(dr, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
2782 draw_rect_coords(dr, px, py, px+lx, py+ly,
2783 ((tile & LOOP(dir)) ? COL_LOOP :
2784 (tile & ACTIVE) ? COL_POWERED :
2788 * The other tile extends into our border, but isn't
2789 * actually connected to us. Just draw a single black
2792 draw_rect_coords(dr, px, py, px, py, COL_WIRE);
2797 * Draw barrier corners, and then barriers.
2799 for (phase = 0; phase < 2; phase++) {
2800 for (dir = 1; dir < 0x10; dir <<= 1) {
2801 int x1, y1, corner = FALSE;
2803 * If at least one barrier terminates at the corner
2804 * between dir and A(dir), draw a barrier corner.
2806 if (barrier(state, GX(x), GY(y)) & (dir | A(dir))) {
2810 * Only count barriers terminating at this corner
2811 * if they're physically next to the corner. (That
2812 * is, if they've wrapped round from the far side
2813 * of the screen, they don't count.)
2817 if (x1 >= 0 && x1 < state->width &&
2818 y1 >= 0 && y1 < state->height &&
2819 (barrier(state, GX(x1), GY(y1)) & A(dir))) {
2824 if (x1 >= 0 && x1 < state->width &&
2825 y1 >= 0 && y1 < state->height &&
2826 (barrier(state, GX(x1), GY(y1)) & dir))
2833 * At least one barrier terminates here. Draw a
2836 draw_barrier_corner(dr, ds, x, y,
2837 X(dir)+X(A(dir)), Y(dir)+Y(A(dir)),
2842 for (dir = 1; dir < 0x10; dir <<= 1)
2843 if (barrier(state, GX(x), GY(y)) & dir)
2844 draw_barrier(dr, ds, x, y, dir, phase);
2849 draw_update(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2852 static void game_redraw(drawing *dr, game_drawstate *ds,
2853 const game_state *oldstate, const game_state *state,
2854 int dir, const game_ui *ui,
2857 int x, y, tx, ty, frame, last_rotate_dir, moved_origin = FALSE;
2858 unsigned char *active;
2863 * Clear the screen, and draw the exterior barrier lines, if
2864 * this is our first call or if the origin has changed.
2866 if (!ds->started || ui->org_x != ds->org_x || ui->org_y != ds->org_y) {
2872 WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
2873 WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
2876 ds->org_x = ui->org_x;
2877 ds->org_y = ui->org_y;
2878 moved_origin = TRUE;
2880 draw_update(dr, 0, 0,
2881 WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
2882 WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
2884 for (phase = 0; phase < 2; phase++) {
2886 for (x = 0; x < ds->width; x++) {
2887 if (x+1 < ds->width) {
2888 if (barrier(state, GX(x), GY(0)) & R)
2889 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
2890 if (barrier(state, GX(x), GY(ds->height-1)) & R)
2891 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
2893 if (barrier(state, GX(x), GY(0)) & U) {
2894 draw_barrier_corner(dr, ds, x, -1, -1, +1, phase);
2895 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
2896 draw_barrier(dr, ds, x, -1, D, phase);
2898 if (barrier(state, GX(x), GY(ds->height-1)) & D) {
2899 draw_barrier_corner(dr, ds, x, ds->height, -1, -1, phase);
2900 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
2901 draw_barrier(dr, ds, x, ds->height, U, phase);
2905 for (y = 0; y < ds->height; y++) {
2906 if (y+1 < ds->height) {
2907 if (barrier(state, GX(0), GY(y)) & D)
2908 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
2909 if (barrier(state, GX(ds->width-1), GY(y)) & D)
2910 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
2912 if (barrier(state, GX(0), GY(y)) & L) {
2913 draw_barrier_corner(dr, ds, -1, y, +1, -1, phase);
2914 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
2915 draw_barrier(dr, ds, -1, y, R, phase);
2917 if (barrier(state, GX(ds->width-1), GY(y)) & R) {
2918 draw_barrier_corner(dr, ds, ds->width, y, -1, -1, phase);
2919 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
2920 draw_barrier(dr, ds, ds->width, y, L, phase);
2927 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2928 state->last_rotate_dir;
2929 if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2931 * We're animating a single tile rotation. Find the turning
2934 tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2935 ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2936 angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2943 * We're animating a completion flash. Find which frame
2946 frame = (int)(ft / FLASH_FRAME);
2950 * Draw any tile which differs from the way it was last drawn.
2952 active = compute_active(state, ui->cx, ui->cy);
2953 loops = compute_loops(state);
2955 for (x = 0; x < ds->width; x++)
2956 for (y = 0; y < ds->height; y++) {
2957 int c = tile(state, GX(x), GY(y)) |
2958 index(state, active, GX(x), GY(y)) |
2959 index(state, loops, GX(x), GY(y));
2960 int is_src = GX(x) == ui->cx && GY(y) == ui->cy;
2961 int is_anim = GX(x) == tx && GY(y) == ty;
2962 int is_cursor = ui->cur_visible &&
2963 GX(x) == ui->cur_x && GY(y) == ui->cur_y;
2966 * In a completion flash, we adjust the LOCKED bit
2967 * depending on our distance from the centre point and
2971 int rcx = RX(ui->cx), rcy = RY(ui->cy);
2972 int xdist, ydist, dist;
2973 xdist = (x < rcx ? rcx - x : x - rcx);
2974 ydist = (y < rcy ? rcy - y : y - rcy);
2975 dist = (xdist > ydist ? xdist : ydist);
2977 if (frame >= dist && frame < dist+4) {
2978 int lock = (frame - dist) & 1;
2979 lock = lock ? LOCKED : 0;
2980 c = (c &~ LOCKED) | lock;
2985 index(state, ds->visible, x, y) != c ||
2986 index(state, ds->visible, x, y) == -1 ||
2987 is_src || is_anim || is_cursor) {
2988 draw_tile(dr, state, ds, x, y, c,
2989 is_src, (is_anim ? angle : 0.0F), is_cursor);
2990 if (is_src || is_anim || is_cursor)
2991 index(state, ds->visible, x, y) = -1;
2993 index(state, ds->visible, x, y) = c;
2998 * Update the status bar.
3001 char statusbuf[256], *p;
3003 int complete = FALSE;
3006 *p = '\0'; /* ensure even an empty status string is terminated */
3008 if (state->used_solve) {
3009 p += sprintf(p, "Auto-solved. ");
3011 } else if (state->completed) {
3012 p += sprintf(p, "COMPLETED! ");
3017 * Omit the 'Active: n/N' counter completely if the source
3018 * tile is a completely empty one, because then the active
3019 * count can't help but read '1'.
3021 if (tile(state, ui->cx, ui->cy) & 0xF) {
3022 n = state->width * state->height;
3023 for (i = a = n2 = 0; i < n; i++) {
3026 if (state->tiles[i] & 0xF)
3031 * Also, if we're displaying a completion indicator and
3032 * the game is still in its completed state (i.e. every
3033 * tile is active), we might as well omit this too.
3035 if (!complete || a < n2)
3036 p += sprintf(p, "Active: %d/%d", a, n2);
3039 status_bar(dr, statusbuf);
3046 static float game_anim_length(const game_state *oldstate,
3047 const game_state *newstate, int dir, game_ui *ui)
3049 int last_rotate_dir;
3052 * Don't animate if last_rotate_dir is zero.
3054 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
3055 newstate->last_rotate_dir;
3056 if (last_rotate_dir)
3062 static float game_flash_length(const game_state *oldstate,
3063 const game_state *newstate, int dir, game_ui *ui)
3066 * If the game has just been completed, we display a completion
3069 if (!oldstate->completed && newstate->completed &&
3070 !oldstate->used_solve && !newstate->used_solve) {
3072 if (size < newstate->width)
3073 size = newstate->width;
3074 if (size < newstate->height)
3075 size = newstate->height;
3076 return FLASH_FRAME * (size+4);
3082 static int game_status(const game_state *state)
3084 return state->completed ? +1 : 0;
3087 static int game_timing_state(const game_state *state, game_ui *ui)
3092 static void game_print_size(const game_params *params, float *x, float *y)
3097 * I'll use 8mm squares by default.
3099 game_compute_size(params, 800, &pw, &ph);
3104 static void draw_diagram(drawing *dr, game_drawstate *ds, int x, int y,
3105 int topleft, int v, int drawlines, int ink)
3107 int tx, ty, cx, cy, r, br, k, thick;
3109 tx = WINDOW_OFFSET + TILE_SIZE * x;
3110 ty = WINDOW_OFFSET + TILE_SIZE * y;
3113 * Find our centre point.
3116 cx = tx + (v & L ? TILE_SIZE / 4 : TILE_SIZE / 6);
3117 cy = ty + (v & U ? TILE_SIZE / 4 : TILE_SIZE / 6);
3119 br = TILE_SIZE / 32;
3121 cx = tx + TILE_SIZE / 2;
3122 cy = ty + TILE_SIZE / 2;
3129 * Draw the square block if we have an endpoint.
3131 if (v == 1 || v == 2 || v == 4 || v == 8)
3132 draw_rect(dr, cx - br, cy - br, br*2, br*2, ink);
3135 * Draw each radial line.
3138 for (k = 1; k < 16; k *= 2)
3140 int x1 = min(cx, cx + (r-thick) * X(k));
3141 int x2 = max(cx, cx + (r-thick) * X(k));
3142 int y1 = min(cy, cy + (r-thick) * Y(k));
3143 int y2 = max(cy, cy + (r-thick) * Y(k));
3144 draw_rect(dr, x1 - thick, y1 - thick,
3145 (x2 - x1) + 2*thick, (y2 - y1) + 2*thick, ink);
3150 static void game_print(drawing *dr, const game_state *state, int tilesize)
3152 int w = state->width, h = state->height;
3153 int ink = print_mono_colour(dr, 0);
3156 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3157 game_drawstate ads, *ds = &ads;
3158 game_set_size(dr, ds, NULL, tilesize);
3163 print_line_width(dr, TILE_SIZE / (state->wrapping ? 128 : 12));
3164 draw_rect_outline(dr, WINDOW_OFFSET, WINDOW_OFFSET,
3165 TILE_SIZE * w, TILE_SIZE * h, ink);
3170 print_line_width(dr, TILE_SIZE / 128);
3171 for (x = 1; x < w; x++)
3172 draw_line(dr, WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET,
3173 WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET + TILE_SIZE * h,
3175 for (y = 1; y < h; y++)
3176 draw_line(dr, WINDOW_OFFSET, WINDOW_OFFSET + TILE_SIZE * y,
3177 WINDOW_OFFSET + TILE_SIZE * w, WINDOW_OFFSET + TILE_SIZE * y,
3183 for (y = 0; y <= h; y++)
3184 for (x = 0; x <= w; x++) {
3185 int b = barrier(state, x % w, y % h);
3186 if (x < w && (b & U))
3187 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3188 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3189 TILE_SIZE + TILE_SIZE/24 * 2, TILE_SIZE/24 * 2, ink);
3190 if (y < h && (b & L))
3191 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3192 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3193 TILE_SIZE/24 * 2, TILE_SIZE + TILE_SIZE/24 * 2, ink);
3199 for (y = 0; y < h; y++)
3200 for (x = 0; x < w; x++) {
3201 int vx, v = tile(state, x, y);
3202 int locked = v & LOCKED;
3207 * Rotate into a standard orientation for the top left
3211 while (vx != 0 && vx != 15 && vx != 1 && vx != 9 && vx != 13 &&
3216 * Draw the top left corner diagram.
3218 draw_diagram(dr, ds, x, y, TRUE, vx, TRUE, ink);
3221 * Draw the real solution diagram, if we're doing so.
3223 draw_diagram(dr, ds, x, y, FALSE, v, locked, ink);
3231 const struct game thegame = {
3232 "Net", "games.net", "net",
3234 game_fetch_preset, NULL,
3239 TRUE, game_configure, custom_params,
3247 FALSE, game_can_format_as_text_now, game_text_format,
3255 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3258 game_free_drawstate,
3263 TRUE, FALSE, game_print_size, game_print,
3264 TRUE, /* wants_statusbar */
3265 FALSE, game_timing_state,