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 /* Direction and other bitfields */
37 #define RLOOP (R << 6)
38 #define ULOOP (U << 6)
39 #define LLOOP (L << 6)
40 #define DLOOP (D << 6)
41 #define LOOP(dir) ((dir) << 6)
43 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
44 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
45 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
46 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
47 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
48 ((n)&3) == 1 ? A(x) : \
49 ((n)&3) == 2 ? F(x) : C(x) )
51 /* X and Y displacements */
52 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
53 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
56 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
57 (((x) & 0x02) >> 1) + ((x) & 0x01) )
59 #define PREFERRED_TILE_SIZE 32
60 #define TILE_SIZE (ds->tilesize)
61 #define LINE_THICK ((TILE_SIZE+47)/48)
63 #define WINDOW_OFFSET 4
65 #define WINDOW_OFFSET 16
68 #define ROTATE_TIME 0.13F
69 #define FLASH_FRAME 0.07F
88 float barrier_probability;
91 typedef struct game_immutable_state {
93 unsigned char *barriers;
94 } game_immutable_state;
97 int width, height, wrapping, completed;
98 int last_rotate_x, last_rotate_y, last_rotate_dir;
100 unsigned char *tiles;
101 struct game_immutable_state *imm;
104 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
105 ( (x2) = ((x1) + width + X((dir))) % width, \
106 (y2) = ((y1) + height + Y((dir))) % height)
108 #define OFFSET(x2,y2,x1,y1,dir,state) \
109 OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
111 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
112 #define tile(state, x, y) index(state, (state)->tiles, x, y)
113 #define barrier(state, x, y) index(state, (state)->imm->barriers, x, y)
119 static int xyd_cmp(const void *av, const void *bv) {
120 const struct xyd *a = (const struct xyd *)av;
121 const struct xyd *b = (const struct xyd *)bv;
130 if (a->direction < b->direction)
132 if (a->direction > b->direction)
137 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
139 static struct xyd *new_xyd(int x, int y, int direction)
141 struct xyd *xyd = snew(struct xyd);
144 xyd->direction = direction;
148 /* ----------------------------------------------------------------------
149 * Manage game parameters.
151 static game_params *default_params(void)
153 game_params *ret = snew(game_params);
157 ret->wrapping = FALSE;
159 ret->barrier_probability = 0.0;
164 static const struct game_params net_presets[] = {
165 {5, 5, FALSE, TRUE, 0.0},
166 {7, 7, FALSE, TRUE, 0.0},
167 {9, 9, FALSE, TRUE, 0.0},
168 {11, 11, FALSE, TRUE, 0.0},
170 {13, 11, FALSE, TRUE, 0.0},
172 {5, 5, TRUE, TRUE, 0.0},
173 {7, 7, TRUE, TRUE, 0.0},
174 {9, 9, TRUE, TRUE, 0.0},
175 {11, 11, TRUE, TRUE, 0.0},
177 {13, 11, TRUE, TRUE, 0.0},
181 static int game_fetch_preset(int i, char **name, game_params **params)
186 if (i < 0 || i >= lenof(net_presets))
189 ret = snew(game_params);
190 *ret = net_presets[i];
192 sprintf(str, "%dx%d%s", ret->width, ret->height,
193 ret->wrapping ? " wrapping" : "");
200 static void free_params(game_params *params)
205 static game_params *dup_params(const game_params *params)
207 game_params *ret = snew(game_params);
208 *ret = *params; /* structure copy */
212 static void decode_params(game_params *ret, char const *string)
214 char const *p = string;
216 ret->width = atoi(p);
217 while (*p && isdigit((unsigned char)*p)) p++;
220 ret->height = atoi(p);
221 while (*p && isdigit((unsigned char)*p)) p++;
223 ret->height = ret->width;
229 ret->wrapping = TRUE;
230 } else if (*p == 'b') {
232 ret->barrier_probability = (float)atof(p);
233 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
234 } else if (*p == 'a') {
238 p++; /* skip any other gunk */
242 static char *encode_params(const game_params *params, int full)
247 len = sprintf(ret, "%dx%d", params->width, params->height);
248 if (params->wrapping)
250 if (full && params->barrier_probability)
251 len += sprintf(ret+len, "b%g", params->barrier_probability);
252 if (full && !params->unique)
254 assert(len < lenof(ret));
260 static config_item *game_configure(const game_params *params)
265 ret = snewn(6, config_item);
267 ret[0].name = "Width";
268 ret[0].type = C_STRING;
269 sprintf(buf, "%d", params->width);
270 ret[0].u.string.sval = dupstr(buf);
272 ret[1].name = "Height";
273 ret[1].type = C_STRING;
274 sprintf(buf, "%d", params->height);
275 ret[1].u.string.sval = dupstr(buf);
277 ret[2].name = "Walls wrap around";
278 ret[2].type = C_BOOLEAN;
279 ret[2].u.boolean.bval = params->wrapping;
281 ret[3].name = "Barrier probability";
282 ret[3].type = C_STRING;
283 sprintf(buf, "%g", params->barrier_probability);
284 ret[3].u.string.sval = dupstr(buf);
286 ret[4].name = "Ensure unique solution";
287 ret[4].type = C_BOOLEAN;
288 ret[4].u.boolean.bval = params->unique;
296 static game_params *custom_params(const config_item *cfg)
298 game_params *ret = snew(game_params);
300 ret->width = atoi(cfg[0].u.string.sval);
301 ret->height = atoi(cfg[1].u.string.sval);
302 ret->wrapping = cfg[2].u.boolean.bval;
303 ret->barrier_probability = (float)atof(cfg[3].u.string.sval);
304 ret->unique = cfg[4].u.boolean.bval;
309 static const char *validate_params(const game_params *params, int full)
311 if (params->width <= 0 || params->height <= 0)
312 return "Width and height must both be greater than zero";
313 if (params->width <= 1 && params->height <= 1)
314 return "At least one of width and height must be greater than one";
315 if (params->barrier_probability < 0)
316 return "Barrier probability may not be negative";
317 if (params->barrier_probability > 1)
318 return "Barrier probability may not be greater than 1";
321 * Specifying either grid dimension as 2 in a wrapping puzzle
322 * makes it actually impossible to ensure a unique puzzle
327 * Without loss of generality, let us assume the puzzle _width_
328 * is 2, so we can conveniently discuss rows without having to
329 * say `rows/columns' all the time. (The height may be 2 as
330 * well, but that doesn't matter.)
332 * In each row, there are two edges between tiles: the inner
333 * edge (running down the centre of the grid) and the outer
334 * edge (the identified left and right edges of the grid).
336 * Lemma: In any valid 2xn puzzle there must be at least one
337 * row in which _exactly one_ of the inner edge and outer edge
340 * Proof: No row can have _both_ inner and outer edges
341 * connected, because this would yield a loop. So the only
342 * other way to falsify the lemma is for every row to have
343 * _neither_ the inner nor outer edge connected. But this
344 * means there is no connection at all between the left and
345 * right columns of the puzzle, so there are two disjoint
346 * subgraphs, which is also disallowed. []
348 * Given such a row, it is always possible to make the
349 * disconnected edge connected and the connected edge
350 * disconnected without changing the state of any other edge.
351 * (This is easily seen by case analysis on the various tiles:
352 * left-pointing and right-pointing endpoints can be exchanged,
353 * likewise T-pieces, and a corner piece can select its
354 * horizontal connectivity independently of its vertical.) This
355 * yields a distinct valid solution.
357 * Thus, for _every_ row in which exactly one of the inner and
358 * outer edge is connected, there are two valid states for that
359 * row, and hence the total number of solutions of the puzzle
360 * is at least 2^(number of such rows), and in particular is at
361 * least 2 since there must be at least one such row. []
363 if (full && params->unique && params->wrapping &&
364 (params->width == 2 || params->height == 2))
365 return "No wrapping puzzle with a width or height of 2 can have"
366 " a unique solution";
371 /* ----------------------------------------------------------------------
372 * Solver used to assure solution uniqueness during generation.
376 * Test cases I used while debugging all this were
378 * ./net --generate 1 13x11w#12300
379 * which expands under the non-unique grid generation rules to
380 * 13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
381 * and has two ambiguous areas.
383 * An even better one is
384 * 13x11w#507896411361192
386 * 13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
387 * and has an ambiguous area _and_ a situation where loop avoidance
388 * is a necessary deductive technique.
391 * 48x25w#820543338195187
393 * 48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
394 * which has a spot (far right) where slightly more complex loop
395 * avoidance is required.
399 unsigned char *marked;
405 static struct todo *todo_new(int maxsize)
407 struct todo *todo = snew(struct todo);
408 todo->marked = snewn(maxsize, unsigned char);
409 memset(todo->marked, 0, maxsize);
410 todo->buflen = maxsize + 1;
411 todo->buffer = snewn(todo->buflen, int);
412 todo->head = todo->tail = 0;
416 static void todo_free(struct todo *todo)
423 static void todo_add(struct todo *todo, int index)
425 if (todo->marked[index])
426 return; /* already on the list */
427 todo->marked[index] = TRUE;
428 todo->buffer[todo->tail++] = index;
429 if (todo->tail == todo->buflen)
433 static int todo_get(struct todo *todo) {
436 if (todo->head == todo->tail)
437 return -1; /* list is empty */
438 ret = todo->buffer[todo->head++];
439 if (todo->head == todo->buflen)
441 todo->marked[ret] = FALSE;
447 * Return values: -1 means puzzle was proved inconsistent, 0 means we
448 * failed to narrow down to a unique solution, +1 means we solved it
451 static int net_solver(int w, int h, unsigned char *tiles,
452 unsigned char *barriers, int wrapping)
454 unsigned char *tilestate;
455 unsigned char *edgestate;
464 * Set up the solver's data structures.
468 * tilestate stores the possible orientations of each tile.
469 * There are up to four of these, so we'll index the array in
470 * fours. tilestate[(y * w + x) * 4] and its three successive
471 * members give the possible orientations, clearing to 255 from
472 * the end as things are ruled out.
474 * In this loop we also count up the area of the grid (which is
475 * not _necessarily_ equal to w*h, because there might be one
476 * or more blank squares present. This will never happen in a
477 * grid generated _by_ this program, but it's worth keeping the
478 * solver as general as possible.)
480 tilestate = snewn(w * h * 4, unsigned char);
482 for (i = 0; i < w*h; i++) {
483 tilestate[i * 4] = tiles[i] & 0xF;
484 for (j = 1; j < 4; j++) {
485 if (tilestate[i * 4 + j - 1] == 255 ||
486 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
487 tilestate[i * 4 + j] = 255;
489 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
496 * edgestate stores the known state of each edge. It is 0 for
497 * unknown, 1 for open (connected) and 2 for closed (not
500 * In principle we need only worry about each edge once each,
501 * but in fact it's easier to track each edge twice so that we
502 * can reference it from either side conveniently. Also I'm
503 * going to allocate _five_ bytes per tile, rather than the
504 * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
505 * where d is 1,2,4,8 and they never overlap.
507 edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
508 memset(edgestate, 0, (w * h - 1) * 5 + 9);
511 * deadends tracks which edges have dead ends on them. It is
512 * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
513 * tells you whether heading out of tile (x,y) in direction d
514 * can reach a limited amount of the grid. Values are area+1
515 * (no dead end known) or less than that (can reach _at most_
516 * this many other tiles by heading this way out of this tile).
518 deadends = snewn((w * h - 1) * 5 + 9, int);
519 for (i = 0; i < (w * h - 1) * 5 + 9; i++)
520 deadends[i] = area+1;
523 * equivalence tracks which sets of tiles are known to be
524 * connected to one another, so we can avoid creating loops by
525 * linking together tiles which are already linked through
528 * This is a disjoint set forest structure: equivalence[i]
529 * contains the index of another member of the equivalence
530 * class containing i, or contains i itself for precisely one
531 * member in each such class. To find a representative member
532 * of the equivalence class containing i, you keep replacing i
533 * with equivalence[i] until it stops changing; then you go
534 * _back_ along the same path and point everything on it
535 * directly at the representative member so as to speed up
536 * future searches. Then you test equivalence between tiles by
537 * finding the representative of each tile and seeing if
538 * they're the same; and you create new equivalence (merge
539 * classes) by finding the representative of each tile and
540 * setting equivalence[one]=the_other.
542 equivalence = snew_dsf(w * h);
545 * On a non-wrapping grid, we instantly know that all the edges
546 * round the edge are closed.
549 for (i = 0; i < w; i++) {
550 edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
552 for (i = 0; i < h; i++) {
553 edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
558 * If we have barriers available, we can mark those edges as
562 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
564 for (d = 1; d <= 8; d += d) {
565 if (barriers[y*w+x] & d) {
568 * In principle the barrier list should already
569 * contain each barrier from each side, but
570 * let's not take chances with our internal
573 OFFSETWH(x2, y2, x, y, d, w, h);
574 edgestate[(y*w+x) * 5 + d] = 2;
575 edgestate[(y2*w+x2) * 5 + F(d)] = 2;
582 * Since most deductions made by this solver are local (the
583 * exception is loop avoidance, where joining two tiles
584 * together on one side of the grid can theoretically permit a
585 * fresh deduction on the other), we can address the scaling
586 * problem inherent in iterating repeatedly over the entire
587 * grid by instead working with a to-do list.
589 todo = todo_new(w * h);
592 * Main deductive loop.
594 done_something = TRUE; /* prevent instant termination! */
599 * Take a tile index off the todo list and process it.
601 index = todo_get(todo);
604 * If we have run out of immediate things to do, we
605 * have no choice but to scan the whole grid for
606 * longer-range things we've missed. Hence, I now add
607 * every square on the grid back on to the to-do list.
608 * I also set `done_something' to FALSE at this point;
609 * if we later come back here and find it still FALSE,
610 * we will know we've scanned the entire grid without
611 * finding anything new to do, and we can terminate.
615 for (i = 0; i < w*h; i++)
617 done_something = FALSE;
619 index = todo_get(todo);
625 int d, ourclass = dsf_canonify(equivalence, y*w+x);
628 deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
630 for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
632 int nnondeadends, nondeadends[4], deadendtotal;
633 int nequiv, equiv[5];
634 int val = tilestate[(y*w+x) * 4 + i];
637 nnondeadends = deadendtotal = 0;
640 for (d = 1; d <= 8; d += d) {
642 * Immediately rule out this orientation if it
643 * conflicts with any known edge.
645 if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
646 (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
651 * Count up the dead-end statistics.
653 if (deadends[(y*w+x) * 5 + d] <= area) {
654 deadendtotal += deadends[(y*w+x) * 5 + d];
656 nondeadends[nnondeadends++] = d;
660 * Ensure we aren't linking to any tiles,
661 * through edges not already known to be
662 * open, which create a loop.
664 if (edgestate[(y*w+x) * 5 + d] == 0) {
667 OFFSETWH(x2, y2, x, y, d, w, h);
668 c = dsf_canonify(equivalence, y2*w+x2);
669 for (k = 0; k < nequiv; k++)
680 if (nnondeadends == 0) {
682 * If this orientation links together dead-ends
683 * with a total area of less than the entire
684 * grid, it is invalid.
686 * (We add 1 to deadendtotal because of the
687 * tile itself, of course; one tile linking
688 * dead ends of size 2 and 3 forms a subnetwork
689 * with a total area of 6, not 5.)
691 if (deadendtotal > 0 && deadendtotal+1 < area)
693 } else if (nnondeadends == 1) {
695 * If this orientation links together one or
696 * more dead-ends with precisely one
697 * non-dead-end, then we may have to mark that
698 * non-dead-end as a dead end going the other
699 * way. However, it depends on whether all
700 * other orientations share the same property.
703 if (deadendmax[nondeadends[0]] < deadendtotal)
704 deadendmax[nondeadends[0]] = deadendtotal;
707 * If this orientation links together two or
708 * more non-dead-ends, then we can rule out the
709 * possibility of putting in new dead-end
710 * markings in those directions.
713 for (k = 0; k < nnondeadends; k++)
714 deadendmax[nondeadends[k]] = area+1;
718 tilestate[(y*w+x) * 4 + j++] = val;
719 #ifdef SOLVER_DIAGNOSTICS
721 printf("ruling out orientation %x at %d,%d\n", val, x, y);
726 /* If we've ruled out all possible orientations for a
727 * tile, then our puzzle has no solution at all. */
732 done_something = TRUE;
735 * We have ruled out at least one tile orientation.
736 * Make sure the rest are blanked.
739 tilestate[(y*w+x) * 4 + j++] = 255;
743 * Now go through the tile orientations again and see
744 * if we've deduced anything new about any edges.
750 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
751 a &= tilestate[(y*w+x) * 4 + i];
752 o |= tilestate[(y*w+x) * 4 + i];
754 for (d = 1; d <= 8; d += d)
755 if (edgestate[(y*w+x) * 5 + d] == 0) {
757 OFFSETWH(x2, y2, x, y, d, w, h);
760 /* This edge is open in all orientations. */
761 #ifdef SOLVER_DIAGNOSTICS
762 printf("marking edge %d,%d:%d open\n", x, y, d);
764 edgestate[(y*w+x) * 5 + d] = 1;
765 edgestate[(y2*w+x2) * 5 + d2] = 1;
766 dsf_merge(equivalence, y*w+x, y2*w+x2);
767 done_something = TRUE;
768 todo_add(todo, y2*w+x2);
769 } else if (!(o & d)) {
770 /* This edge is closed in all orientations. */
771 #ifdef SOLVER_DIAGNOSTICS
772 printf("marking edge %d,%d:%d closed\n", x, y, d);
774 edgestate[(y*w+x) * 5 + d] = 2;
775 edgestate[(y2*w+x2) * 5 + d2] = 2;
776 done_something = TRUE;
777 todo_add(todo, y2*w+x2);
784 * Now check the dead-end markers and see if any of
785 * them has lowered from the real ones.
787 for (d = 1; d <= 8; d += d) {
789 OFFSETWH(x2, y2, x, y, d, w, h);
791 if (deadendmax[d] > 0 &&
792 deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
793 #ifdef SOLVER_DIAGNOSTICS
794 printf("setting dead end value %d,%d:%d to %d\n",
795 x2, y2, d2, deadendmax[d]);
797 deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
798 done_something = TRUE;
799 todo_add(todo, y2*w+x2);
807 * Mark all completely determined tiles as locked.
810 for (i = 0; i < w*h; i++) {
811 if (tilestate[i * 4 + 1] == 255) {
812 assert(tilestate[i * 4 + 0] != 255);
813 tiles[i] = tilestate[i * 4] | LOCKED;
821 * Free up working space.
832 /* ----------------------------------------------------------------------
833 * Randomly select a new game description.
837 * Function to randomly perturb an ambiguous section in a grid, to
838 * attempt to ensure unique solvability.
840 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
841 random_state *rs, int startx, int starty, int startd)
843 struct xyd *perimeter, *perim2, *loop[2], looppos[2];
844 int nperim, perimsize, nloop[2], loopsize[2];
848 * We know that the tile at (startx,starty) is part of an
849 * ambiguous section, and we also know that its neighbour in
850 * direction startd is fully specified. We begin by tracing all
851 * the way round the ambiguous area.
853 nperim = perimsize = 0;
858 #ifdef PERTURB_DIAGNOSTICS
859 printf("perturb %d,%d:%d\n", x, y, d);
864 if (nperim >= perimsize) {
865 perimsize = perimsize * 3 / 2 + 32;
866 perimeter = sresize(perimeter, perimsize, struct xyd);
868 perimeter[nperim].x = x;
869 perimeter[nperim].y = y;
870 perimeter[nperim].direction = d;
872 #ifdef PERTURB_DIAGNOSTICS
873 printf("perimeter: %d,%d:%d\n", x, y, d);
877 * First, see if we can simply turn left from where we are
878 * and find another locked square.
881 OFFSETWH(x2, y2, x, y, d2, w, h);
882 if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
883 (tiles[y2*w+x2] & LOCKED)) {
887 * Failing that, step left into the new square and look
892 OFFSETWH(x2, y2, x, y, d, w, h);
893 if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
894 !(tiles[y2*w+x2] & LOCKED)) {
896 * And failing _that_, we're going to have to step
897 * forward into _that_ square and look right at the
898 * same locked square as we started with.
906 } while (x != startx || y != starty || d != startd);
909 * Our technique for perturbing this ambiguous area is to
910 * search round its edge for a join we can make: that is, an
911 * edge on the perimeter which is (a) not currently connected,
912 * and (b) connecting it would not yield a full cross on either
913 * side. Then we make that join, search round the network to
914 * find the loop thus constructed, and sever the loop at a
915 * randomly selected other point.
917 perim2 = snewn(nperim, struct xyd);
918 memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
919 /* Shuffle the perimeter, so as to search it without directional bias. */
920 shuffle(perim2, nperim, sizeof(*perim2), rs);
921 for (i = 0; i < nperim; i++) {
926 d = perim2[i].direction;
928 OFFSETWH(x2, y2, x, y, d, w, h);
929 if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
930 continue; /* can't link across non-wrapping border */
931 if (tiles[y*w+x] & d)
932 continue; /* already linked in this direction! */
933 if (((tiles[y*w+x] | d) & 15) == 15)
934 continue; /* can't turn this tile into a cross */
935 if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
936 continue; /* can't turn other tile into a cross */
939 * We've found the point at which we're going to make a new
942 #ifdef PERTURB_DIAGNOSTICS
943 printf("linking %d,%d:%d\n", x, y, d);
946 tiles[y2*w+x2] |= F(d);
954 return; /* nothing we can do! */
958 * Now we've constructed a new link, we need to find the entire
959 * loop of which it is a part.
961 * In principle, this involves doing a complete search round
962 * the network. However, I anticipate that in the vast majority
963 * of cases the loop will be quite small, so what I'm going to
964 * do is make _two_ searches round the network in parallel, one
965 * keeping its metaphorical hand on the left-hand wall while
966 * the other keeps its hand on the right. As soon as one of
967 * them gets back to its starting point, I abandon the other.
969 for (i = 0; i < 2; i++) {
970 loopsize[i] = nloop[i] = 0;
974 looppos[i].direction = d;
977 for (i = 0; i < 2; i++) {
982 d = looppos[i].direction;
984 OFFSETWH(x2, y2, x, y, d, w, h);
987 * Add this path segment to the loop, unless it exactly
988 * reverses the previous one on the loop in which case
989 * we take it away again.
991 #ifdef PERTURB_DIAGNOSTICS
992 printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
995 loop[i][nloop[i]-1].x == x2 &&
996 loop[i][nloop[i]-1].y == y2 &&
997 loop[i][nloop[i]-1].direction == F(d)) {
998 #ifdef PERTURB_DIAGNOSTICS
999 printf("removing path segment %d,%d:%d from loop[%d]\n",
1004 if (nloop[i] >= loopsize[i]) {
1005 loopsize[i] = loopsize[i] * 3 / 2 + 32;
1006 loop[i] = sresize(loop[i], loopsize[i], struct xyd);
1008 #ifdef PERTURB_DIAGNOSTICS
1009 printf("adding path segment %d,%d:%d to loop[%d]\n",
1012 loop[i][nloop[i]++] = looppos[i];
1015 #ifdef PERTURB_DIAGNOSTICS
1016 printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
1019 for (j = 0; j < 4; j++) {
1024 #ifdef PERTURB_DIAGNOSTICS
1025 printf("trying dir %d\n", d);
1027 if (tiles[y2*w+x2] & d) {
1030 looppos[i].direction = d;
1036 assert(nloop[i] > 0);
1038 if (looppos[i].x == loop[i][0].x &&
1039 looppos[i].y == loop[i][0].y &&
1040 looppos[i].direction == loop[i][0].direction) {
1041 #ifdef PERTURB_DIAGNOSTICS
1042 printf("loop %d finished tracking\n", i);
1046 * Having found our loop, we now sever it at a
1047 * randomly chosen point - absolutely any will do -
1048 * which is not the one we joined it at to begin
1049 * with. Conveniently, the one we joined it at is
1050 * loop[i][0], so we just avoid that one.
1052 j = random_upto(rs, nloop[i]-1) + 1;
1055 d = loop[i][j].direction;
1056 OFFSETWH(x2, y2, x, y, d, w, h);
1058 tiles[y2*w+x2] &= ~F(d);
1070 * Finally, we must mark the entire disputed section as locked,
1071 * to prevent the perturb function being called on it multiple
1074 * To do this, we _sort_ the perimeter of the area. The
1075 * existing xyd_cmp function will arrange things into columns
1076 * for us, in such a way that each column has the edges in
1077 * vertical order. Then we can work down each column and fill
1078 * in all the squares between an up edge and a down edge.
1080 qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1082 for (i = 0; i <= nperim; i++) {
1083 if (i == nperim || perimeter[i].x > x) {
1085 * Fill in everything from the last Up edge to the
1086 * bottom of the grid, if necessary.
1090 #ifdef PERTURB_DIAGNOSTICS
1091 printf("resolved: locking tile %d,%d\n", x, y);
1093 tiles[y * w + x] |= LOCKED;
1106 if (perimeter[i].direction == U) {
1109 } else if (perimeter[i].direction == D) {
1111 * Fill in everything from the last Up edge to here.
1113 assert(x == perimeter[i].x && y <= perimeter[i].y);
1114 while (y <= perimeter[i].y) {
1115 #ifdef PERTURB_DIAGNOSTICS
1116 printf("resolved: locking tile %d,%d\n", x, y);
1118 tiles[y * w + x] |= LOCKED;
1128 static int *compute_loops_inner(int w, int h, int wrapping,
1129 const unsigned char *tiles,
1130 const unsigned char *barriers);
1132 static char *new_game_desc(const game_params *params, random_state *rs,
1133 char **aux, int interactive)
1135 tree234 *possibilities, *barriertree;
1136 int w, h, x, y, cx, cy, nbarriers;
1137 unsigned char *tiles, *barriers;
1146 tiles = snewn(w * h, unsigned char);
1147 barriers = snewn(w * h, unsigned char);
1151 memset(tiles, 0, w * h);
1152 memset(barriers, 0, w * h);
1155 * Construct the unshuffled grid.
1157 * To do this, we simply start at the centre point, repeatedly
1158 * choose a random possibility out of the available ways to
1159 * extend a used square into an unused one, and do it. After
1160 * extending the third line out of a square, we remove the
1161 * fourth from the possibilities list to avoid any full-cross
1162 * squares (which would make the game too easy because they
1163 * only have one orientation).
1165 * The slightly worrying thing is the avoidance of full-cross
1166 * squares. Can this cause our unsophisticated construction
1167 * algorithm to paint itself into a corner, by getting into a
1168 * situation where there are some unreached squares and the
1169 * only way to reach any of them is to extend a T-piece into a
1172 * Answer: no it can't, and here's a proof.
1174 * Any contiguous group of such unreachable squares must be
1175 * surrounded on _all_ sides by T-pieces pointing away from the
1176 * group. (If not, then there is a square which can be extended
1177 * into one of the `unreachable' ones, and so it wasn't
1178 * unreachable after all.) In particular, this implies that
1179 * each contiguous group of unreachable squares must be
1180 * rectangular in shape (any deviation from that yields a
1181 * non-T-piece next to an `unreachable' square).
1183 * So we have a rectangle of unreachable squares, with T-pieces
1184 * forming a solid border around the rectangle. The corners of
1185 * that border must be connected (since every tile connects all
1186 * the lines arriving in it), and therefore the border must
1187 * form a closed loop around the rectangle.
1189 * But this can't have happened in the first place, since we
1190 * _know_ we've avoided creating closed loops! Hence, no such
1191 * situation can ever arise, and the naive grid construction
1192 * algorithm will guaranteeably result in a complete grid
1193 * containing no unreached squares, no full crosses _and_ no
1196 possibilities = newtree234(xyd_cmp_nc);
1199 add234(possibilities, new_xyd(cx, cy, R));
1201 add234(possibilities, new_xyd(cx, cy, U));
1203 add234(possibilities, new_xyd(cx, cy, L));
1205 add234(possibilities, new_xyd(cx, cy, D));
1207 while (count234(possibilities) > 0) {
1210 int x1, y1, d1, x2, y2, d2, d;
1213 * Extract a randomly chosen possibility from the list.
1215 i = random_upto(rs, count234(possibilities));
1216 xyd = delpos234(possibilities, i);
1219 d1 = xyd->direction;
1222 OFFSET(x2, y2, x1, y1, d1, params);
1224 #ifdef GENERATION_DIAGNOSTICS
1225 printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1226 x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1230 * Make the connection. (We should be moving to an as yet
1233 index(params, tiles, x1, y1) |= d1;
1234 assert(index(params, tiles, x2, y2) == 0);
1235 index(params, tiles, x2, y2) |= d2;
1238 * If we have created a T-piece, remove its last
1241 if (COUNT(index(params, tiles, x1, y1)) == 3) {
1242 struct xyd xyd1, *xydp;
1246 xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1248 xydp = find234(possibilities, &xyd1, NULL);
1251 #ifdef GENERATION_DIAGNOSTICS
1252 printf("T-piece; removing (%d,%d,%c)\n",
1253 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1255 del234(possibilities, xydp);
1261 * Remove all other possibilities that were pointing at the
1262 * tile we've just moved into.
1264 for (d = 1; d < 0x10; d <<= 1) {
1266 struct xyd xyd1, *xydp;
1268 OFFSET(x3, y3, x2, y2, d, params);
1273 xyd1.direction = d3;
1275 xydp = find234(possibilities, &xyd1, NULL);
1278 #ifdef GENERATION_DIAGNOSTICS
1279 printf("Loop avoidance; removing (%d,%d,%c)\n",
1280 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1282 del234(possibilities, xydp);
1288 * Add new possibilities to the list for moving _out_ of
1289 * the tile we have just moved into.
1291 for (d = 1; d < 0x10; d <<= 1) {
1295 continue; /* we've got this one already */
1297 if (!params->wrapping) {
1298 if (d == U && y2 == 0)
1300 if (d == D && y2 == h-1)
1302 if (d == L && x2 == 0)
1304 if (d == R && x2 == w-1)
1308 OFFSET(x3, y3, x2, y2, d, params);
1310 if (index(params, tiles, x3, y3))
1311 continue; /* this would create a loop */
1313 #ifdef GENERATION_DIAGNOSTICS
1314 printf("New frontier; adding (%d,%d,%c)\n",
1315 x2, y2, "0RU3L567D9abcdef"[d]);
1317 add234(possibilities, new_xyd(x2, y2, d));
1320 /* Having done that, we should have no possibilities remaining. */
1321 assert(count234(possibilities) == 0);
1322 freetree234(possibilities);
1324 if (params->unique) {
1328 * Run the solver to check unique solubility.
1330 while (net_solver(w, h, tiles, NULL, params->wrapping) != 1) {
1334 * We expect (in most cases) that most of the grid will
1335 * be uniquely specified already, and the remaining
1336 * ambiguous sections will be small and separate. So
1337 * our strategy is to find each individual such
1338 * section, and perform a perturbation on the network
1341 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1342 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1344 if (tiles[y*w+x] & LOCKED)
1345 perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1347 perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1349 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1351 if (tiles[y*w+x] & LOCKED)
1352 perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1354 perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1359 * Now n counts the number of ambiguous sections we
1360 * have fiddled with. If we haven't managed to decrease
1361 * it from the last time we ran the solver, give up and
1362 * regenerate the entire grid.
1364 if (prevn != -1 && prevn <= n)
1365 goto begin_generation; /* (sorry) */
1371 * The solver will have left a lot of LOCKED bits lying
1372 * around in the tiles array. Remove them.
1374 for (x = 0; x < w*h; x++)
1375 tiles[x] &= ~LOCKED;
1379 * Now compute a list of the possible barrier locations.
1381 barriertree = newtree234(xyd_cmp_nc);
1382 for (y = 0; y < h; y++) {
1383 for (x = 0; x < w; x++) {
1385 if (!(index(params, tiles, x, y) & R) &&
1386 (params->wrapping || x < w-1))
1387 add234(barriertree, new_xyd(x, y, R));
1388 if (!(index(params, tiles, x, y) & D) &&
1389 (params->wrapping || y < h-1))
1390 add234(barriertree, new_xyd(x, y, D));
1395 * Save the unshuffled grid in aux.
1401 solution = snewn(w * h + 1, char);
1402 for (i = 0; i < w * h; i++)
1403 solution[i] = "0123456789abcdef"[tiles[i] & 0xF];
1404 solution[w*h] = '\0';
1410 * Now shuffle the grid.
1412 * In order to avoid accidentally generating an already-solved
1413 * grid, we will reshuffle as necessary to ensure that at least
1414 * one edge has a mismatched connection.
1416 * This can always be done, since validate_params() enforces a
1417 * grid area of at least 2 and our generator never creates
1418 * either type of rotationally invariant tile (cross and
1419 * blank). Hence there must be at least one edge separating
1420 * distinct tiles, and it must be possible to find orientations
1421 * of those tiles such that one tile is trying to connect
1422 * through that edge and the other is not.
1424 * (We could be more subtle, and allow the shuffle to generate
1425 * a grid in which all tiles match up locally and the only
1426 * criterion preventing the grid from being already solved is
1427 * connectedness. However, that would take more effort, and
1428 * it's easier to simply make sure every grid is _obviously_
1431 * We also require that our shuffle produces no loops in the
1432 * initial grid state, because it's a bit rude to light up a 'HEY,
1433 * YOU DID SOMETHING WRONG!' indicator when the user hasn't even
1434 * had a chance to do _anything_ yet. This also is possible just
1435 * by retrying the whole shuffle on failure, because it's clear
1436 * that at least one non-solved shuffle with no loops must exist.
1437 * (Proof: take the _solved_ state of the puzzle, and rotate one
1441 int mismatches, prev_loopsquares, this_loopsquares, i;
1445 for (y = 0; y < h; y++) {
1446 for (x = 0; x < w; x++) {
1447 int orig = index(params, tiles, x, y);
1448 int rot = random_upto(rs, 4);
1449 index(params, tiles, x, y) = ROT(orig, rot);
1454 * Check for loops, and try to fix them by reshuffling just
1455 * the squares involved.
1457 prev_loopsquares = w*h+1;
1459 loops = compute_loops_inner(w, h, params->wrapping, tiles, NULL);
1460 this_loopsquares = 0;
1461 for (i = 0; i < w*h; i++) {
1463 int orig = tiles[i];
1464 int rot = random_upto(rs, 4);
1465 tiles[i] = ROT(orig, rot);
1470 if (this_loopsquares > prev_loopsquares) {
1472 * We're increasing rather than reducing the number of
1473 * loops. Give up and go back to the full shuffle.
1477 if (this_loopsquares == 0)
1479 prev_loopsquares = this_loopsquares;
1484 * I can't even be bothered to check for mismatches across
1485 * a wrapping edge, so I'm just going to enforce that there
1486 * must be a mismatch across a non-wrapping edge, which is
1487 * still always possible.
1489 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1490 if (x+1 < w && ((ROT(index(params, tiles, x, y), 2) ^
1491 index(params, tiles, x+1, y)) & L))
1493 if (y+1 < h && ((ROT(index(params, tiles, x, y), 2) ^
1494 index(params, tiles, x, y+1)) & U))
1498 if (mismatches == 0)
1506 * And now choose barrier locations. (We carefully do this
1507 * _after_ shuffling, so that changing the barrier rate in the
1508 * params while keeping the random seed the same will give the
1509 * same shuffled grid and _only_ change the barrier locations.
1510 * Also the way we choose barrier locations, by repeatedly
1511 * choosing one possibility from the list until we have enough,
1512 * is designed to ensure that raising the barrier rate while
1513 * keeping the seed the same will provide a superset of the
1514 * previous barrier set - i.e. if you ask for 10 barriers, and
1515 * then decide that's still too hard and ask for 20, you'll get
1516 * the original 10 plus 10 more, rather than getting 20 new
1517 * ones and the chance of remembering your first 10.)
1519 nbarriers = (int)(params->barrier_probability * count234(barriertree));
1520 assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1522 while (nbarriers > 0) {
1525 int x1, y1, d1, x2, y2, d2;
1528 * Extract a randomly chosen barrier from the list.
1530 i = random_upto(rs, count234(barriertree));
1531 xyd = delpos234(barriertree, i);
1533 assert(xyd != NULL);
1537 d1 = xyd->direction;
1540 OFFSET(x2, y2, x1, y1, d1, params);
1543 index(params, barriers, x1, y1) |= d1;
1544 index(params, barriers, x2, y2) |= d2;
1550 * Clean up the rest of the barrier list.
1555 while ( (xyd = delpos234(barriertree, 0)) != NULL)
1558 freetree234(barriertree);
1562 * Finally, encode the grid into a string game description.
1564 * My syntax is extremely simple: each square is encoded as a
1565 * hex digit in which bit 0 means a connection on the right,
1566 * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1567 * encoding as used internally). Each digit is followed by
1568 * optional barrier indicators: `v' means a vertical barrier to
1569 * the right of it, and `h' means a horizontal barrier below
1572 desc = snewn(w * h * 3 + 1, char);
1574 for (y = 0; y < h; y++) {
1575 for (x = 0; x < w; x++) {
1576 *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1577 if ((params->wrapping || x < w-1) &&
1578 (index(params, barriers, x, y) & R))
1580 if ((params->wrapping || y < h-1) &&
1581 (index(params, barriers, x, y) & D))
1585 assert(p - desc <= w*h*3);
1594 static const char *validate_desc(const game_params *params, const char *desc)
1596 int w = params->width, h = params->height;
1599 for (i = 0; i < w*h; i++) {
1600 if (*desc >= '0' && *desc <= '9')
1602 else if (*desc >= 'a' && *desc <= 'f')
1604 else if (*desc >= 'A' && *desc <= 'F')
1607 return "Game description shorter than expected";
1609 return "Game description contained unexpected character";
1611 while (*desc == 'h' || *desc == 'v')
1615 return "Game description longer than expected";
1620 /* ----------------------------------------------------------------------
1621 * Construct an initial game state, given a description and parameters.
1624 static game_state *new_game(midend *me, const game_params *params,
1630 assert(params->width > 0 && params->height > 0);
1631 assert(params->width > 1 || params->height > 1);
1634 * Create a blank game state.
1636 state = snew(game_state);
1637 w = state->width = params->width;
1638 h = state->height = params->height;
1639 state->wrapping = params->wrapping;
1640 state->imm = snew(game_immutable_state);
1641 state->imm->refcount = 1;
1642 state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1643 state->completed = state->used_solve = FALSE;
1644 state->tiles = snewn(state->width * state->height, unsigned char);
1645 memset(state->tiles, 0, state->width * state->height);
1646 state->imm->barriers = snewn(state->width * state->height, unsigned char);
1647 memset(state->imm->barriers, 0, state->width * state->height);
1650 * Parse the game description into the grid.
1652 for (y = 0; y < h; y++) {
1653 for (x = 0; x < w; x++) {
1654 if (*desc >= '0' && *desc <= '9')
1655 tile(state, x, y) = *desc - '0';
1656 else if (*desc >= 'a' && *desc <= 'f')
1657 tile(state, x, y) = *desc - 'a' + 10;
1658 else if (*desc >= 'A' && *desc <= 'F')
1659 tile(state, x, y) = *desc - 'A' + 10;
1662 while (*desc == 'h' || *desc == 'v') {
1669 OFFSET(x2, y2, x, y, d1, state);
1672 barrier(state, x, y) |= d1;
1673 barrier(state, x2, y2) |= d2;
1681 * Set up border barriers if this is a non-wrapping game.
1683 if (!state->wrapping) {
1684 for (x = 0; x < state->width; x++) {
1685 barrier(state, x, 0) |= U;
1686 barrier(state, x, state->height-1) |= D;
1688 for (y = 0; y < state->height; y++) {
1689 barrier(state, 0, y) |= L;
1690 barrier(state, state->width-1, y) |= R;
1694 * We check whether this is de-facto a non-wrapping game
1695 * despite the parameters, in case we were passed the
1696 * description of a non-wrapping game. This is so that we
1697 * can change some aspects of the UI behaviour.
1699 state->wrapping = FALSE;
1700 for (x = 0; x < state->width; x++)
1701 if (!(barrier(state, x, 0) & U) ||
1702 !(barrier(state, x, state->height-1) & D))
1703 state->wrapping = TRUE;
1704 for (y = 0; y < state->height; y++)
1705 if (!(barrier(state, 0, y) & L) ||
1706 !(barrier(state, state->width-1, y) & R))
1707 state->wrapping = TRUE;
1713 static game_state *dup_game(const game_state *state)
1717 ret = snew(game_state);
1718 ret->imm = state->imm;
1719 ret->imm->refcount++;
1720 ret->width = state->width;
1721 ret->height = state->height;
1722 ret->wrapping = state->wrapping;
1723 ret->completed = state->completed;
1724 ret->used_solve = state->used_solve;
1725 ret->last_rotate_dir = state->last_rotate_dir;
1726 ret->last_rotate_x = state->last_rotate_x;
1727 ret->last_rotate_y = state->last_rotate_y;
1728 ret->tiles = snewn(state->width * state->height, unsigned char);
1729 memcpy(ret->tiles, state->tiles, state->width * state->height);
1734 static void free_game(game_state *state)
1736 if (--state->imm->refcount == 0) {
1737 sfree(state->imm->barriers);
1740 sfree(state->tiles);
1744 static char *solve_game(const game_state *state, const game_state *currstate,
1745 const char *aux, const char **error)
1747 unsigned char *tiles;
1749 int retlen, retsize;
1752 tiles = snewn(state->width * state->height, unsigned char);
1756 * Run the internal solver on the provided grid. This might
1757 * not yield a complete solution.
1761 memcpy(tiles, state->tiles, state->width * state->height);
1762 solver_result = net_solver(state->width, state->height, tiles,
1763 state->imm->barriers, state->wrapping);
1765 if (solver_result < 0) {
1766 *error = "No solution exists for this puzzle";
1771 for (i = 0; i < state->width * state->height; i++) {
1774 if (c >= '0' && c <= '9')
1776 else if (c >= 'a' && c <= 'f')
1777 tiles[i] = c - 'a' + 10;
1778 else if (c >= 'A' && c <= 'F')
1779 tiles[i] = c - 'A' + 10;
1786 * Now construct a string which can be passed to execute_move()
1787 * to transform the current grid into the solved one.
1790 ret = snewn(retsize, char);
1792 ret[retlen++] = 'S';
1794 for (i = 0; i < state->width * state->height; i++) {
1795 int from = currstate->tiles[i], to = tiles[i];
1796 int ft = from & (R|L|U|D), tt = to & (R|L|U|D);
1797 int x = i % state->width, y = i / state->width;
1799 char buf[80], *p = buf;
1802 continue; /* nothing needs doing at all */
1805 * To transform this tile into the desired tile: first
1806 * unlock the tile if it's locked, then rotate it if
1807 * necessary, then lock it if necessary.
1810 p += sprintf(p, ";L%d,%d", x, y);
1814 else if (tt == C(ft))
1816 else if (tt == F(ft))
1823 p += sprintf(p, ";%c%d,%d", chr, x, y);
1826 p += sprintf(p, ";L%d,%d", x, y);
1829 if (retlen + (p - buf) >= retsize) {
1830 retsize = retlen + (p - buf) + 512;
1831 ret = sresize(ret, retsize, char);
1833 memcpy(ret+retlen, buf, p - buf);
1838 assert(retlen < retsize);
1840 ret = sresize(ret, retlen+1, char);
1847 static int game_can_format_as_text_now(const game_params *params)
1852 static char *game_text_format(const game_state *state)
1857 /* ----------------------------------------------------------------------
1862 * Compute which squares are reachable from the centre square, as a
1863 * quick visual aid to determining how close the game is to
1864 * completion. This is also a simple way to tell if the game _is_
1865 * completed - just call this function and see whether every square
1868 static unsigned char *compute_active(const game_state *state, int cx, int cy)
1870 unsigned char *active;
1874 active = snewn(state->width * state->height, unsigned char);
1875 memset(active, 0, state->width * state->height);
1878 * We only store (x,y) pairs in todo, but it's easier to reuse
1879 * xyd_cmp and just store direction 0 every time.
1881 todo = newtree234(xyd_cmp_nc);
1882 index(state, active, cx, cy) = ACTIVE;
1883 add234(todo, new_xyd(cx, cy, 0));
1885 while ( (xyd = delpos234(todo, 0)) != NULL) {
1886 int x1, y1, d1, x2, y2, d2;
1892 for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1893 OFFSET(x2, y2, x1, y1, d1, state);
1897 * If the next tile in this direction is connected to
1898 * us, and there isn't a barrier in the way, and it
1899 * isn't already marked active, then mark it active and
1900 * add it to the to-examine list.
1902 if ((tile(state, x1, y1) & d1) &&
1903 (tile(state, x2, y2) & d2) &&
1904 !(barrier(state, x1, y1) & d1) &&
1905 !index(state, active, x2, y2)) {
1906 index(state, active, x2, y2) = ACTIVE;
1907 add234(todo, new_xyd(x2, y2, 0));
1911 /* Now we expect the todo list to have shrunk to zero size. */
1912 assert(count234(todo) == 0);
1918 struct net_neighbour_ctx {
1920 const unsigned char *tiles, *barriers;
1921 int i, n, neighbours[4];
1923 static int net_neighbour(int vertex, void *vctx)
1925 struct net_neighbour_ctx *ctx = (struct net_neighbour_ctx *)vctx;
1928 int x = vertex % ctx->w, y = vertex / ctx->w;
1929 int tile, dir, x1, y1, v1;
1931 ctx->i = ctx->n = 0;
1933 tile = ctx->tiles[vertex];
1935 tile &= ~ctx->barriers[vertex];
1937 for (dir = 1; dir < 0x10; dir <<= 1) {
1940 OFFSETWH(x1, y1, x, y, dir, ctx->w, ctx->h);
1941 v1 = y1 * ctx->w + x1;
1942 if (ctx->tiles[v1] & F(dir))
1943 ctx->neighbours[ctx->n++] = v1;
1947 if (ctx->i < ctx->n)
1948 return ctx->neighbours[ctx->i++];
1953 static int *compute_loops_inner(int w, int h, int wrapping,
1954 const unsigned char *tiles,
1955 const unsigned char *barriers)
1957 struct net_neighbour_ctx ctx;
1958 struct findloopstate *fls;
1962 fls = findloop_new_state(w*h);
1966 ctx.barriers = barriers;
1967 findloop_run(fls, w*h, net_neighbour, &ctx);
1969 loops = snewn(w*h, int);
1971 for (y = 0; y < h; y++) {
1972 for (x = 0; x < w; x++) {
1976 for (dir = 1; dir < 0x10; dir <<= 1) {
1977 if ((tiles[y*w+x] & dir) &&
1978 !(barriers && (barriers[y*w+x] & dir))) {
1979 OFFSETWH(x1, y1, x, y, dir, w, h);
1980 if ((tiles[y1*w+x1] & F(dir)) &&
1981 findloop_is_loop_edge(fls, y*w+x, y1*w+x1))
1985 loops[y*w+x] = flags;
1989 findloop_free_state(fls);
1993 static int *compute_loops(const game_state *state)
1995 return compute_loops_inner(state->width, state->height, state->wrapping,
1996 state->tiles, state->imm->barriers);
2000 int org_x, org_y; /* origin */
2001 int cx, cy; /* source tile (game coordinates) */
2004 random_state *rs; /* used for jumbling */
2006 int dragtilex, dragtiley, dragstartx, dragstarty, dragged;
2010 static game_ui *new_ui(const game_state *state)
2014 game_ui *ui = snew(game_ui);
2015 ui->org_x = ui->org_y = 0;
2016 ui->cur_x = ui->cx = state->width / 2;
2017 ui->cur_y = ui->cy = state->height / 2;
2018 ui->cur_visible = FALSE;
2019 get_random_seed(&seed, &seedsize);
2020 ui->rs = random_new(seed, seedsize);
2026 static void free_ui(game_ui *ui)
2028 random_free(ui->rs);
2032 static char *encode_ui(const game_ui *ui)
2036 * We preserve the origin and centre-point coordinates over a
2039 sprintf(buf, "O%d,%d;C%d,%d", ui->org_x, ui->org_y, ui->cx, ui->cy);
2043 static void decode_ui(game_ui *ui, const char *encoding)
2045 sscanf(encoding, "O%d,%d;C%d,%d",
2046 &ui->org_x, &ui->org_y, &ui->cx, &ui->cy);
2049 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2050 const game_state *newstate)
2054 struct game_drawstate {
2058 unsigned long *visible, *to_draw;
2061 /* ----------------------------------------------------------------------
2064 static char *interpret_move(const game_state *state, game_ui *ui,
2065 const game_drawstate *ds,
2066 int x, int y, int button)
2069 int tx = -1, ty = -1, dir = 0;
2070 int shift = button & MOD_SHFT, ctrl = button & MOD_CTRL;
2072 NONE, ROTATE_LEFT, ROTATE_180, ROTATE_RIGHT, TOGGLE_LOCK, JUMBLE,
2073 MOVE_ORIGIN, MOVE_SOURCE, MOVE_ORIGIN_AND_SOURCE, MOVE_CURSOR
2076 button &= ~MOD_MASK;
2080 if (button == LEFT_BUTTON ||
2081 button == MIDDLE_BUTTON ||
2083 button == LEFT_DRAG ||
2084 button == LEFT_RELEASE ||
2085 button == RIGHT_DRAG ||
2086 button == RIGHT_RELEASE ||
2088 button == RIGHT_BUTTON) {
2090 if (ui->cur_visible) {
2091 ui->cur_visible = FALSE;
2092 nullret = UI_UPDATE;
2096 * The button must have been clicked on a valid tile.
2098 x -= WINDOW_OFFSET + LINE_THICK;
2099 y -= WINDOW_OFFSET + LINE_THICK;
2104 if (tx >= state->width || ty >= state->height)
2106 /* Transform from physical to game coords */
2107 tx = (tx + ui->org_x) % state->width;
2108 ty = (ty + ui->org_y) % state->height;
2109 if (x % TILE_SIZE >= TILE_SIZE - LINE_THICK ||
2110 y % TILE_SIZE >= TILE_SIZE - LINE_THICK)
2115 if (button == MIDDLE_BUTTON
2117 || button == RIGHT_BUTTON /* with a stylus, `right-click' locks */
2121 * Middle button never drags: it only toggles the lock.
2123 action = TOGGLE_LOCK;
2124 } else if (button == LEFT_BUTTON
2125 #ifndef STYLUS_BASED
2126 || button == RIGHT_BUTTON /* (see above) */
2130 * Otherwise, we note down the start point for a drag.
2134 ui->dragstartx = x % TILE_SIZE;
2135 ui->dragstarty = y % TILE_SIZE;
2136 ui->dragged = FALSE;
2137 return nullret; /* no actual action */
2138 } else if (button == LEFT_DRAG
2139 #ifndef STYLUS_BASED
2140 || button == RIGHT_DRAG
2144 * Find the new drag point and see if it necessitates a
2147 int x0,y0, xA,yA, xC,yC, xF,yF;
2149 int d0, dA, dC, dF, dmin;
2154 mx = x - (ui->dragtilex * TILE_SIZE);
2155 my = y - (ui->dragtiley * TILE_SIZE);
2157 x0 = ui->dragstartx;
2158 y0 = ui->dragstarty;
2159 xA = ui->dragstarty;
2160 yA = TILE_SIZE-1 - ui->dragstartx;
2161 xF = TILE_SIZE-1 - ui->dragstartx;
2162 yF = TILE_SIZE-1 - ui->dragstarty;
2163 xC = TILE_SIZE-1 - ui->dragstarty;
2164 yC = ui->dragstartx;
2166 d0 = (mx-x0)*(mx-x0) + (my-y0)*(my-y0);
2167 dA = (mx-xA)*(mx-xA) + (my-yA)*(my-yA);
2168 dF = (mx-xF)*(mx-xF) + (my-yF)*(my-yF);
2169 dC = (mx-xC)*(mx-xC) + (my-yC)*(my-yC);
2171 dmin = min(min(d0,dA),min(dF,dC));
2175 } else if (dF == dmin) {
2176 action = ROTATE_180;
2177 ui->dragstartx = xF;
2178 ui->dragstarty = yF;
2180 } else if (dA == dmin) {
2181 action = ROTATE_LEFT;
2182 ui->dragstartx = xA;
2183 ui->dragstarty = yA;
2185 } else /* dC == dmin */ {
2186 action = ROTATE_RIGHT;
2187 ui->dragstartx = xC;
2188 ui->dragstarty = yC;
2191 } else if (button == LEFT_RELEASE
2192 #ifndef STYLUS_BASED
2193 || button == RIGHT_RELEASE
2198 * There was a click but no perceptible drag:
2199 * revert to single-click behaviour.
2204 if (button == LEFT_RELEASE)
2205 action = ROTATE_LEFT;
2207 action = ROTATE_RIGHT;
2209 return nullret; /* no action */
2212 #else /* USE_DRAGGING */
2214 action = (button == LEFT_BUTTON ? ROTATE_LEFT :
2215 button == RIGHT_BUTTON ? ROTATE_RIGHT : TOGGLE_LOCK);
2217 #endif /* USE_DRAGGING */
2219 } else if (IS_CURSOR_MOVE(button)) {
2221 case CURSOR_UP: dir = U; break;
2222 case CURSOR_DOWN: dir = D; break;
2223 case CURSOR_LEFT: dir = L; break;
2224 case CURSOR_RIGHT: dir = R; break;
2225 default: return nullret;
2227 if (shift && ctrl) action = MOVE_ORIGIN_AND_SOURCE;
2228 else if (shift) action = MOVE_ORIGIN;
2229 else if (ctrl) action = MOVE_SOURCE;
2230 else action = MOVE_CURSOR;
2231 } else if (button == 'a' || button == 's' || button == 'd' ||
2232 button == 'A' || button == 'S' || button == 'D' ||
2233 button == 'f' || button == 'F' ||
2234 IS_CURSOR_SELECT(button)) {
2237 if (button == 'a' || button == 'A' || button == CURSOR_SELECT)
2238 action = ROTATE_LEFT;
2239 else if (button == 's' || button == 'S' || button == CURSOR_SELECT2)
2240 action = TOGGLE_LOCK;
2241 else if (button == 'd' || button == 'D')
2242 action = ROTATE_RIGHT;
2243 else if (button == 'f' || button == 'F')
2244 action = ROTATE_180;
2245 ui->cur_visible = TRUE;
2246 } else if (button == 'j' || button == 'J') {
2247 /* XXX should we have some mouse control for this? */
2253 * The middle button locks or unlocks a tile. (A locked tile
2254 * cannot be turned, and is visually marked as being locked.
2255 * This is a convenience for the player, so that once they are
2256 * sure which way round a tile goes, they can lock it and thus
2257 * avoid forgetting later on that they'd already done that one;
2258 * and the locking also prevents them turning the tile by
2259 * accident. If they change their mind, another middle click
2262 if (action == TOGGLE_LOCK) {
2264 sprintf(buf, "L%d,%d", tx, ty);
2266 } else if (action == ROTATE_LEFT || action == ROTATE_RIGHT ||
2267 action == ROTATE_180) {
2271 * The left and right buttons have no effect if clicked on a
2274 if (tile(state, tx, ty) & LOCKED)
2278 * Otherwise, turn the tile one way or the other. Left button
2279 * turns anticlockwise; right button turns clockwise.
2281 sprintf(buf, "%c%d,%d", (int)(action == ROTATE_LEFT ? 'A' :
2282 action == ROTATE_RIGHT ? 'C' : 'F'), tx, ty);
2284 } else if (action == JUMBLE) {
2286 * Jumble all unlocked tiles to random orientations.
2293 * Maximum string length assumes no int can be converted to
2294 * decimal and take more than 11 digits!
2296 maxlen = state->width * state->height * 25 + 3;
2298 ret = snewn(maxlen, char);
2302 for (jy = 0; jy < state->height; jy++) {
2303 for (jx = 0; jx < state->width; jx++) {
2304 if (!(tile(state, jx, jy) & LOCKED)) {
2305 int rot = random_upto(ui->rs, 4);
2307 p += sprintf(p, ";%c%d,%d", "AFC"[rot-1], jx, jy);
2313 assert(p - ret < maxlen);
2314 ret = sresize(ret, p - ret, char);
2317 } else if (action == MOVE_ORIGIN || action == MOVE_SOURCE ||
2318 action == MOVE_ORIGIN_AND_SOURCE || action == MOVE_CURSOR) {
2320 if (action == MOVE_ORIGIN || action == MOVE_ORIGIN_AND_SOURCE) {
2321 if (state->wrapping) {
2322 OFFSET(ui->org_x, ui->org_y, ui->org_x, ui->org_y, dir, state);
2323 } else return nullret; /* disallowed for non-wrapping grids */
2325 if (action == MOVE_SOURCE || action == MOVE_ORIGIN_AND_SOURCE) {
2326 OFFSET(ui->cx, ui->cy, ui->cx, ui->cy, dir, state);
2328 if (action == MOVE_CURSOR) {
2329 OFFSET(ui->cur_x, ui->cur_y, ui->cur_x, ui->cur_y, dir, state);
2330 ui->cur_visible = TRUE;
2338 static game_state *execute_move(const game_state *from, const char *move)
2341 int tx = -1, ty = -1, n, noanim, orig;
2343 ret = dup_game(from);
2345 if (move[0] == 'J' || move[0] == 'S') {
2347 ret->used_solve = TRUE;
2356 ret->last_rotate_dir = 0; /* suppress animation */
2357 ret->last_rotate_x = ret->last_rotate_y = 0;
2360 if ((move[0] == 'A' || move[0] == 'C' ||
2361 move[0] == 'F' || move[0] == 'L') &&
2362 sscanf(move+1, "%d,%d%n", &tx, &ty, &n) >= 2 &&
2363 tx >= 0 && tx < from->width && ty >= 0 && ty < from->height) {
2364 orig = tile(ret, tx, ty);
2365 if (move[0] == 'A') {
2366 tile(ret, tx, ty) = A(orig);
2368 ret->last_rotate_dir = +1;
2369 } else if (move[0] == 'F') {
2370 tile(ret, tx, ty) = F(orig);
2372 ret->last_rotate_dir = +2; /* + for sake of argument */
2373 } else if (move[0] == 'C') {
2374 tile(ret, tx, ty) = C(orig);
2376 ret->last_rotate_dir = -1;
2378 assert(move[0] == 'L');
2379 tile(ret, tx, ty) ^= LOCKED;
2383 if (*move == ';') move++;
2390 if (tx == -1 || ty == -1) { free_game(ret); return NULL; }
2391 ret->last_rotate_x = tx;
2392 ret->last_rotate_y = ty;
2396 * Check whether the game has been completed.
2398 * For this purpose it doesn't matter where the source square is,
2399 * because we can start from anywhere (or, at least, any square
2400 * that's non-empty!), and correctly determine whether the game is
2404 unsigned char *active;
2406 int complete = TRUE;
2408 for (pos = 0; pos < ret->width * ret->height; pos++)
2409 if (ret->tiles[pos] & 0xF)
2412 if (pos < ret->width * ret->height) {
2413 active = compute_active(ret, pos % ret->width, pos / ret->width);
2415 for (pos = 0; pos < ret->width * ret->height; pos++)
2416 if ((ret->tiles[pos] & 0xF) && !active[pos]) {
2425 ret->completed = TRUE;
2432 /* ----------------------------------------------------------------------
2433 * Routines for drawing the game position on the screen.
2436 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2438 game_drawstate *ds = snew(game_drawstate);
2441 ds->started = FALSE;
2442 ds->width = state->width;
2443 ds->height = state->height;
2444 ncells = (state->width+2) * (state->height+2);
2445 ds->visible = snewn(ncells, unsigned long);
2446 ds->to_draw = snewn(ncells, unsigned long);
2447 ds->tilesize = 0; /* undecided yet */
2448 for (i = 0; i < ncells; i++)
2449 ds->visible[i] = -1;
2454 #define dsindex(ds, field, x, y) ((ds)->field[((y)+1)*((ds)->width+2)+((x)+1)])
2455 #define visible(ds, x, y) dsindex(ds, visible, x, y)
2456 #define todraw(ds, x, y) dsindex(ds, to_draw, x, y)
2458 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2464 static void game_compute_size(const game_params *params, int tilesize,
2467 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2468 struct { int tilesize; } ads, *ds = &ads;
2469 ads.tilesize = tilesize;
2471 *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + LINE_THICK;
2472 *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + LINE_THICK;
2475 static void game_set_size(drawing *dr, game_drawstate *ds,
2476 const game_params *params, int tilesize)
2478 ds->tilesize = tilesize;
2481 static float *game_colours(frontend *fe, int *ncolours)
2485 ret = snewn(NCOLOURS * 3, float);
2486 *ncolours = NCOLOURS;
2489 * Basic background colour is whatever the front end thinks is
2490 * a sensible default.
2492 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2497 ret[COL_WIRE * 3 + 0] = 0.0F;
2498 ret[COL_WIRE * 3 + 1] = 0.0F;
2499 ret[COL_WIRE * 3 + 2] = 0.0F;
2502 * Powered wires and powered endpoints are cyan.
2504 ret[COL_POWERED * 3 + 0] = 0.0F;
2505 ret[COL_POWERED * 3 + 1] = 1.0F;
2506 ret[COL_POWERED * 3 + 2] = 1.0F;
2511 ret[COL_BARRIER * 3 + 0] = 1.0F;
2512 ret[COL_BARRIER * 3 + 1] = 0.0F;
2513 ret[COL_BARRIER * 3 + 2] = 0.0F;
2516 * Highlighted loops are red as well.
2518 ret[COL_LOOP * 3 + 0] = 1.0F;
2519 ret[COL_LOOP * 3 + 1] = 0.0F;
2520 ret[COL_LOOP * 3 + 2] = 0.0F;
2523 * Unpowered endpoints are blue.
2525 ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2526 ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2527 ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2530 * Tile borders are a darker grey than the background.
2532 ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2533 ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2534 ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2537 * Locked tiles are a grey in between those two.
2539 ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2540 ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2541 ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2546 static void rotated_coords(float *ox, float *oy, const float matrix[4],
2547 float cx, float cy, float ix, float iy)
2549 *ox = matrix[0] * ix + matrix[2] * iy + cx;
2550 *oy = matrix[1] * ix + matrix[3] * iy + cy;
2553 /* Flags describing the visible features of a tile. */
2554 #define TILE_BARRIER_SHIFT 0 /* 4 bits: R U L D */
2555 #define TILE_BARRIER_CORNER_SHIFT 4 /* 4 bits: RU UL LD DR */
2556 #define TILE_KEYBOARD_CURSOR (1<<8) /* 1 bit if cursor is here */
2557 #define TILE_WIRE_SHIFT 9 /* 8 bits: RR UU LL DD
2558 * Each pair: 0=no wire, 1=unpowered,
2559 * 2=powered, 3=loop err highlight */
2560 #define TILE_ENDPOINT_SHIFT 17 /* 2 bits: 0=no endpoint, 1=unpowered,
2561 * 2=powered, 3=power-source square */
2562 #define TILE_WIRE_ON_EDGE_SHIFT 19 /* 8 bits: RR UU LL DD,
2563 * same encoding as TILE_WIRE_SHIFT */
2564 #define TILE_ROTATING (1UL<<27) /* 1 bit if tile is rotating */
2565 #define TILE_LOCKED (1UL<<28) /* 1 bit if tile is locked */
2567 static void draw_wires(drawing *dr, int cx, int cy, int radius,
2568 unsigned long tile, int bitmap,
2569 int colour, int halfwidth, const float matrix[4])
2571 float fpoints[12*2];
2573 int npoints, d, dsh, i;
2574 int any_wire_this_colour = FALSE;
2578 for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2579 int wiretype = (tile >> (TILE_WIRE_SHIFT + 2*dsh)) & 3;
2581 fpoints[2*npoints+0] = halfwidth * (X(d) + X(C(d)));
2582 fpoints[2*npoints+1] = halfwidth * (Y(d) + Y(C(d)));
2585 if (bitmap & (1 << wiretype)) {
2586 fpoints[2*npoints+0] = radius * X(d) + halfwidth * X(C(d));
2587 fpoints[2*npoints+1] = radius * Y(d) + halfwidth * Y(C(d));
2589 fpoints[2*npoints+0] = radius * X(d) + halfwidth * X(A(d));
2590 fpoints[2*npoints+1] = radius * Y(d) + halfwidth * Y(A(d));
2593 any_wire_this_colour = TRUE;
2597 if (!any_wire_this_colour)
2600 for (i = 0; i < npoints; i++) {
2601 rotated_coords(&xf, &yf, matrix, cx, cy, fpoints[2*i], fpoints[2*i+1]);
2602 points[2*i] = 0.5 + xf;
2603 points[2*i+1] = 0.5 + yf;
2606 draw_polygon(dr, points, npoints, colour, colour);
2609 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y,
2610 unsigned long tile, float angle)
2613 int clipx, clipy, clipX, clipY, clipw, cliph;
2614 int border_br = LINE_THICK/2, border_tl = LINE_THICK - border_br;
2615 int barrier_outline_thick = (LINE_THICK+1)/2;
2616 int bg, d, dsh, pass;
2620 tx = WINDOW_OFFSET + TILE_SIZE * x + border_br;
2621 ty = WINDOW_OFFSET + TILE_SIZE * y + border_br;
2624 * Clip to the tile boundary, with adjustments if we're drawing
2625 * just outside the grid.
2627 clipx = tx; clipX = tx + TILE_SIZE;
2628 clipy = ty; clipY = ty + TILE_SIZE;
2630 clipx = clipX - border_br - barrier_outline_thick;
2631 } else if (x == ds->width) {
2632 clipX = clipx + border_tl + barrier_outline_thick;
2635 clipy = clipY - border_br - barrier_outline_thick;
2636 } else if (y == ds->height) {
2637 clipY = clipy + border_tl + barrier_outline_thick;
2639 clipw = clipX - clipx;
2640 cliph = clipY - clipy;
2641 clip(dr, clipx, clipy, clipw, cliph);
2644 * Clear the clip region.
2646 bg = (tile & TILE_LOCKED) ? COL_LOCKED : COL_BACKGROUND;
2647 draw_rect(dr, clipx, clipy, clipw, cliph, bg);
2650 * Draw the grid lines.
2653 int gridl = (x == -1 ? tx+TILE_SIZE-border_br : tx);
2654 int gridr = (x == ds->width ? tx+border_tl : tx+TILE_SIZE);
2655 int gridu = (y == -1 ? ty+TILE_SIZE-border_br : ty);
2656 int gridd = (y == ds->height ? ty+border_tl : ty+TILE_SIZE);
2658 draw_rect(dr, tx, gridu, border_tl, gridd-gridu, COL_BORDER);
2660 draw_rect(dr, gridl, ty, gridr-gridl, border_tl, COL_BORDER);
2662 draw_rect(dr, tx+TILE_SIZE-border_br, gridu,
2663 border_br, gridd-gridu, COL_BORDER);
2665 draw_rect(dr, gridl, ty+TILE_SIZE-border_br,
2666 gridr-gridl, border_br, COL_BORDER);
2670 * Draw the keyboard cursor.
2672 if (tile & TILE_KEYBOARD_CURSOR) {
2673 int cursorcol = (tile & TILE_LOCKED) ? COL_BACKGROUND : COL_LOCKED;
2674 int inset_outer = TILE_SIZE/8, inset_inner = inset_outer + LINE_THICK;
2675 draw_rect(dr, tx + inset_outer, ty + inset_outer,
2676 TILE_SIZE - 2*inset_outer, TILE_SIZE - 2*inset_outer,
2678 draw_rect(dr, tx + inset_inner, ty + inset_inner,
2679 TILE_SIZE - 2*inset_inner, TILE_SIZE - 2*inset_inner,
2683 radius = (TILE_SIZE+1)/2;
2689 * Draw protrusions into this cell's edges of wires in
2690 * neighbouring cells, as given by the TILE_WIRE_ON_EDGE_SHIFT
2691 * flags. We only draw each of these if there _isn't_ a wire of
2692 * our own that's going to overlap it, which means either the
2693 * corresponding TILE_WIRE_SHIFT flag is zero, or else the
2694 * TILE_ROTATING flag is set (so that our main wire won't be drawn
2695 * in quite that place anyway).
2697 for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2698 int edgetype = ((tile >> (TILE_WIRE_ON_EDGE_SHIFT + 2*dsh)) & 3);
2700 continue; /* there isn't a wire on the edge */
2701 if (!(tile & TILE_ROTATING) &&
2702 ((tile >> (TILE_WIRE_SHIFT + 2*dsh)) & 3) != 0)
2703 continue; /* wire on edge would be overdrawn anyway */
2705 for (pass = 0; pass < 2; pass++) {
2707 int col = (pass == 0 || edgetype == 1 ? COL_WIRE :
2708 edgetype == 2 ? COL_POWERED : COL_LOOP);
2709 int halfwidth = pass == 0 ? 2*LINE_THICK-1 : LINE_THICK-1;
2714 } else if (X(d) > 0) {
2715 x = tx + TILE_SIZE - border_br;
2719 w = 2 * halfwidth + 1;
2725 } else if (Y(d) > 0) {
2726 y = ty + TILE_SIZE - border_br;
2730 h = 2 * halfwidth + 1;
2733 draw_rect(dr, x, y, w, h, col);
2738 * Set up the rotation matrix for the main cell contents, i.e.
2739 * everything that is centred in the grid square and optionally
2740 * rotated by an arbitrary angle about that centre point.
2742 if (tile & TILE_ROTATING) {
2743 matrix[0] = (float)cos(angle * PI / 180.0);
2744 matrix[2] = (float)sin(angle * PI / 180.0);
2749 matrix[3] = matrix[0];
2750 matrix[1] = -matrix[2];
2755 draw_wires(dr, cx, cy, radius, tile,
2756 0xE, COL_WIRE, 2*LINE_THICK-1, matrix);
2757 draw_wires(dr, cx, cy, radius, tile,
2758 0x4, COL_POWERED, LINE_THICK-1, matrix);
2759 draw_wires(dr, cx, cy, radius, tile,
2760 0x8, COL_LOOP, LINE_THICK-1, matrix);
2763 * Draw the central box.
2765 for (pass = 0; pass < 2; pass++) {
2766 int endtype = (tile >> TILE_ENDPOINT_SHIFT) & 3;
2768 int i, points[8], col;
2769 float boxr = TILE_SIZE * 0.24F + (pass == 0 ? LINE_THICK-1 : 0);
2771 col = (pass == 0 || endtype == 3 ? COL_WIRE :
2772 endtype == 2 ? COL_POWERED : COL_ENDPOINT);
2774 points[0] = +1; points[1] = +1;
2775 points[2] = +1; points[3] = -1;
2776 points[4] = -1; points[5] = -1;
2777 points[6] = -1; points[7] = +1;
2779 for (i = 0; i < 8; i += 2) {
2781 rotated_coords(&x, &y, matrix, cx, cy,
2782 boxr * points[i], boxr * points[i+1]);
2783 points[i] = x + 0.5;
2784 points[i+1] = y + 0.5;
2787 draw_polygon(dr, points, 4, col, COL_WIRE);
2792 * Draw barriers along grid edges.
2794 for (pass = 0; pass < 2; pass++) {
2795 int btl = border_tl, bbr = border_br, col = COL_BARRIER;
2797 btl += barrier_outline_thick;
2798 bbr += barrier_outline_thick;
2802 if (tile & (L << TILE_BARRIER_SHIFT))
2803 draw_rect(dr, tx, ty, btl, TILE_SIZE, col);
2804 if (tile & (R << TILE_BARRIER_SHIFT))
2805 draw_rect(dr, tx+TILE_SIZE-bbr, ty, bbr, TILE_SIZE, col);
2806 if (tile & (U << TILE_BARRIER_SHIFT))
2807 draw_rect(dr, tx, ty, TILE_SIZE, btl, col);
2808 if (tile & (D << TILE_BARRIER_SHIFT))
2809 draw_rect(dr, tx, ty+TILE_SIZE-bbr, TILE_SIZE, bbr, col);
2811 if (tile & (R << TILE_BARRIER_CORNER_SHIFT))
2812 draw_rect(dr, tx+TILE_SIZE-bbr, ty, bbr, btl, col);
2813 if (tile & (U << TILE_BARRIER_CORNER_SHIFT))
2814 draw_rect(dr, tx, ty, btl, btl, col);
2815 if (tile & (L << TILE_BARRIER_CORNER_SHIFT))
2816 draw_rect(dr, tx, ty+TILE_SIZE-bbr, btl, bbr, col);
2817 if (tile & (D << TILE_BARRIER_CORNER_SHIFT))
2818 draw_rect(dr, tx+TILE_SIZE-bbr, ty+TILE_SIZE-bbr, bbr, bbr, col);
2822 * Unclip and draw update, to finish.
2825 draw_update(dr, clipx, clipy, clipw, cliph);
2828 static void game_redraw(drawing *dr, game_drawstate *ds,
2829 const game_state *oldstate, const game_state *state,
2830 int dir, const game_ui *ui,
2833 int tx, ty, dx, dy, d, dsh, last_rotate_dir, frame;
2834 unsigned char *active;
2839 * Clear the screen on our first call.
2847 params.width = ds->width;
2848 params.height = ds->height;
2849 game_compute_size(¶ms, TILE_SIZE, &w, &h);
2851 draw_rect(dr, 0, 0, w, h, COL_BACKGROUND);
2852 draw_update(dr, 0, 0, w, h);
2856 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2857 state->last_rotate_dir;
2858 if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2860 * We're animating a single tile rotation. Find the turning
2863 tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2864 ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2865 angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2871 * We're animating a completion flash. Find which frame
2874 frame = (int)(ft / FLASH_FRAME);
2880 * Build up a map of what we want every tile to look like. We
2881 * include tiles one square outside the grid, for the outer edges
2884 active = compute_active(state, ui->cx, ui->cy);
2885 loops = compute_loops(state);
2887 for (dy = -1; dy < ds->height+1; dy++) {
2888 for (dx = -1; dx < ds->width+1; dx++) {
2889 todraw(ds, dx, dy) = 0;
2893 for (dy = 0; dy < ds->height; dy++) {
2894 int gy = (dy + ui->org_y) % ds->height;
2895 for (dx = 0; dx < ds->width; dx++) {
2896 int gx = (dx + ui->org_x) % ds->width;
2897 int t = (tile(state, gx, gy) |
2898 index(state, loops, gx, gy) |
2899 index(state, active, gx, gy));
2901 for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2902 if (barrier(state, gx, gy) & d) {
2903 todraw(ds, dx, dy) |=
2904 d << TILE_BARRIER_SHIFT;
2905 todraw(ds, dx + X(d), dy + Y(d)) |=
2906 F(d) << TILE_BARRIER_SHIFT;
2907 todraw(ds, dx + X(A(d)), dy + Y(A(d))) |=
2908 C(d) << TILE_BARRIER_CORNER_SHIFT;
2909 todraw(ds, dx + X(A(d)) + X(d), dy + Y(A(d)) + Y(d)) |=
2910 F(d) << TILE_BARRIER_CORNER_SHIFT;
2911 todraw(ds, dx + X(C(d)), dy + Y(C(d))) |=
2912 d << TILE_BARRIER_CORNER_SHIFT;
2913 todraw(ds, dx + X(C(d)) + X(d), dy + Y(C(d)) + Y(d)) |=
2914 A(d) << TILE_BARRIER_CORNER_SHIFT;
2918 int edgeval = (t & LOOP(d) ? 3 : t & ACTIVE ? 2 : 1);
2919 todraw(ds, dx, dy) |= edgeval << (TILE_WIRE_SHIFT + dsh*2);
2920 if (!(gx == tx && gy == ty)) {
2921 todraw(ds, dx + X(d), dy + Y(d)) |=
2922 edgeval << (TILE_WIRE_ON_EDGE_SHIFT + (dsh ^ 2)*2);
2927 if (ui->cur_visible && gx == ui->cur_x && gy == ui->cur_y)
2928 todraw(ds, dx, dy) |= TILE_KEYBOARD_CURSOR;
2930 if (gx == tx && gy == ty)
2931 todraw(ds, dx, dy) |= TILE_ROTATING;
2933 if (gx == ui->cx && gy == ui->cy) {
2934 todraw(ds, dx, dy) |= 3 << TILE_ENDPOINT_SHIFT;
2935 } else if ((t & 0xF) != R && (t & 0xF) != U &&
2936 (t & 0xF) != L && (t & 0xF) != D) {
2937 /* this is not an endpoint tile */
2938 } else if (t & ACTIVE) {
2939 todraw(ds, dx, dy) |= 2 << TILE_ENDPOINT_SHIFT;
2941 todraw(ds, dx, dy) |= 1 << TILE_ENDPOINT_SHIFT;
2945 todraw(ds, dx, dy) |= TILE_LOCKED;
2948 * In a completion flash, we adjust the LOCKED bit
2949 * depending on our distance from the centre point and
2953 int rcx = (ui->cx + ds->width - ui->org_x) % ds->width;
2954 int rcy = (ui->cy + ds->height - ui->org_y) % ds->height;
2955 int xdist, ydist, dist;
2956 xdist = (dx < rcx ? rcx - dx : dx - rcx);
2957 ydist = (dy < rcy ? rcy - dy : dy - rcy);
2958 dist = (xdist > ydist ? xdist : ydist);
2960 if (frame >= dist && frame < dist+4 &&
2961 ((frame - dist) & 1))
2962 todraw(ds, dx, dy) ^= TILE_LOCKED;
2968 * Now draw any tile that differs from the way it was last drawn.
2969 * An exception is that if either the previous _or_ current state
2970 * has the TILE_ROTATING bit set, we must draw it regardless,
2971 * because it will have rotated to a different angle.q
2973 for (dy = -1; dy < ds->height+1; dy++) {
2974 for (dx = -1; dx < ds->width+1; dx++) {
2975 int prev = visible(ds, dx, dy);
2976 int curr = todraw(ds, dx, dy);
2977 if (prev != curr || ((prev | curr) & TILE_ROTATING) != 0) {
2978 draw_tile(dr, ds, dx, dy, curr, angle);
2979 visible(ds, dx, dy) = curr;
2985 * Update the status bar.
2988 char statusbuf[256], *p;
2990 int complete = FALSE;
2993 *p = '\0'; /* ensure even an empty status string is terminated */
2995 if (state->used_solve) {
2996 p += sprintf(p, "Auto-solved. ");
2998 } else if (state->completed) {
2999 p += sprintf(p, "COMPLETED! ");
3004 * Omit the 'Active: n/N' counter completely if the source
3005 * tile is a completely empty one, because then the active
3006 * count can't help but read '1'.
3008 if (tile(state, ui->cx, ui->cy) & 0xF) {
3009 n = state->width * state->height;
3010 for (i = a = n2 = 0; i < n; i++) {
3013 if (state->tiles[i] & 0xF)
3018 * Also, if we're displaying a completion indicator and
3019 * the game is still in its completed state (i.e. every
3020 * tile is active), we might as well omit this too.
3022 if (!complete || a < n2)
3023 p += sprintf(p, "Active: %d/%d", a, n2);
3026 status_bar(dr, statusbuf);
3033 static float game_anim_length(const game_state *oldstate,
3034 const game_state *newstate, int dir, game_ui *ui)
3036 int last_rotate_dir;
3039 * Don't animate if last_rotate_dir is zero.
3041 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
3042 newstate->last_rotate_dir;
3043 if (last_rotate_dir)
3049 static float game_flash_length(const game_state *oldstate,
3050 const game_state *newstate, int dir, game_ui *ui)
3053 * If the game has just been completed, we display a completion
3056 if (!oldstate->completed && newstate->completed &&
3057 !oldstate->used_solve && !newstate->used_solve) {
3059 if (size < newstate->width)
3060 size = newstate->width;
3061 if (size < newstate->height)
3062 size = newstate->height;
3063 return FLASH_FRAME * (size+4);
3069 static int game_status(const game_state *state)
3071 return state->completed ? +1 : 0;
3074 static int game_timing_state(const game_state *state, game_ui *ui)
3079 static void game_print_size(const game_params *params, float *x, float *y)
3084 * I'll use 8mm squares by default.
3086 game_compute_size(params, 800, &pw, &ph);
3091 static void draw_diagram(drawing *dr, game_drawstate *ds, int x, int y,
3092 int topleft, int v, int drawlines, int ink)
3094 int tx, ty, cx, cy, r, br, k, thick;
3096 tx = WINDOW_OFFSET + TILE_SIZE * x;
3097 ty = WINDOW_OFFSET + TILE_SIZE * y;
3100 * Find our centre point.
3103 cx = tx + (v & L ? TILE_SIZE / 4 : TILE_SIZE / 6);
3104 cy = ty + (v & U ? TILE_SIZE / 4 : TILE_SIZE / 6);
3106 br = TILE_SIZE / 32;
3108 cx = tx + TILE_SIZE / 2;
3109 cy = ty + TILE_SIZE / 2;
3116 * Draw the square block if we have an endpoint.
3118 if (v == 1 || v == 2 || v == 4 || v == 8)
3119 draw_rect(dr, cx - br, cy - br, br*2, br*2, ink);
3122 * Draw each radial line.
3125 for (k = 1; k < 16; k *= 2)
3127 int x1 = min(cx, cx + (r-thick) * X(k));
3128 int x2 = max(cx, cx + (r-thick) * X(k));
3129 int y1 = min(cy, cy + (r-thick) * Y(k));
3130 int y2 = max(cy, cy + (r-thick) * Y(k));
3131 draw_rect(dr, x1 - thick, y1 - thick,
3132 (x2 - x1) + 2*thick, (y2 - y1) + 2*thick, ink);
3137 static void game_print(drawing *dr, const game_state *state, int tilesize)
3139 int w = state->width, h = state->height;
3140 int ink = print_mono_colour(dr, 0);
3143 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3144 game_drawstate ads, *ds = &ads;
3145 game_set_size(dr, ds, NULL, tilesize);
3150 print_line_width(dr, TILE_SIZE / (state->wrapping ? 128 : 12));
3151 draw_rect_outline(dr, WINDOW_OFFSET, WINDOW_OFFSET,
3152 TILE_SIZE * w, TILE_SIZE * h, ink);
3157 print_line_width(dr, TILE_SIZE / 128);
3158 for (x = 1; x < w; x++)
3159 draw_line(dr, WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET,
3160 WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET + TILE_SIZE * h,
3162 for (y = 1; y < h; y++)
3163 draw_line(dr, WINDOW_OFFSET, WINDOW_OFFSET + TILE_SIZE * y,
3164 WINDOW_OFFSET + TILE_SIZE * w, WINDOW_OFFSET + TILE_SIZE * y,
3170 for (y = 0; y <= h; y++)
3171 for (x = 0; x <= w; x++) {
3172 int b = barrier(state, x % w, y % h);
3173 if (x < w && (b & U))
3174 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3175 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3176 TILE_SIZE + TILE_SIZE/24 * 2, TILE_SIZE/24 * 2, ink);
3177 if (y < h && (b & L))
3178 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3179 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3180 TILE_SIZE/24 * 2, TILE_SIZE + TILE_SIZE/24 * 2, ink);
3186 for (y = 0; y < h; y++)
3187 for (x = 0; x < w; x++) {
3188 int vx, v = tile(state, x, y);
3189 int locked = v & LOCKED;
3194 * Rotate into a standard orientation for the top left
3198 while (vx != 0 && vx != 15 && vx != 1 && vx != 9 && vx != 13 &&
3203 * Draw the top left corner diagram.
3205 draw_diagram(dr, ds, x, y, TRUE, vx, TRUE, ink);
3208 * Draw the real solution diagram, if we're doing so.
3210 draw_diagram(dr, ds, x, y, FALSE, v, locked, ink);
3218 const struct game thegame = {
3219 "Net", "games.net", "net",
3221 game_fetch_preset, NULL,
3226 TRUE, game_configure, custom_params,
3234 FALSE, game_can_format_as_text_now, game_text_format,
3242 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3245 game_free_drawstate,
3250 TRUE, FALSE, game_print_size, game_print,
3251 TRUE, /* wants_statusbar */
3252 FALSE, game_timing_state,