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 */
45 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
46 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
47 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
48 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
49 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
50 ((n)&3) == 1 ? A(x) : \
51 ((n)&3) == 2 ? F(x) : C(x) )
53 /* X and Y displacements */
54 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
55 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
58 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
59 (((x) & 0x02) >> 1) + ((x) & 0x01) )
61 #define PREFERRED_TILE_SIZE 32
62 #define TILE_SIZE (ds->tilesize)
65 #define WINDOW_OFFSET 4
67 #define WINDOW_OFFSET 16
70 #define ROTATE_TIME 0.13F
71 #define FLASH_FRAME 0.07F
73 /* Transform physical coords to game coords using game_drawstate ds */
74 #define GX(x) (((x) + ds->org_x) % ds->width)
75 #define GY(y) (((y) + ds->org_y) % ds->height)
76 /* ...and game coords to physical coords */
77 #define RX(x) (((x) + ds->width - ds->org_x) % ds->width)
78 #define RY(y) (((y) + ds->height - ds->org_y) % ds->height)
96 float barrier_probability;
100 int width, height, wrapping, completed;
101 int last_rotate_x, last_rotate_y, last_rotate_dir;
103 unsigned char *tiles;
104 unsigned char *barriers;
107 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
108 ( (x2) = ((x1) + width + X((dir))) % width, \
109 (y2) = ((y1) + height + Y((dir))) % height)
111 #define OFFSET(x2,y2,x1,y1,dir,state) \
112 OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
114 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
115 #define tile(state, x, y) index(state, (state)->tiles, x, y)
116 #define barrier(state, x, y) index(state, (state)->barriers, x, y)
122 static int xyd_cmp(const void *av, const void *bv) {
123 const struct xyd *a = (const struct xyd *)av;
124 const struct xyd *b = (const struct xyd *)bv;
133 if (a->direction < b->direction)
135 if (a->direction > b->direction)
140 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
142 static struct xyd *new_xyd(int x, int y, int direction)
144 struct xyd *xyd = snew(struct xyd);
147 xyd->direction = direction;
151 /* ----------------------------------------------------------------------
152 * Manage game parameters.
154 static game_params *default_params(void)
156 game_params *ret = snew(game_params);
160 ret->wrapping = FALSE;
162 ret->barrier_probability = 0.0;
167 static const struct game_params net_presets[] = {
168 {5, 5, FALSE, TRUE, 0.0},
169 {7, 7, FALSE, TRUE, 0.0},
170 {9, 9, FALSE, TRUE, 0.0},
171 {11, 11, FALSE, TRUE, 0.0},
173 {13, 11, FALSE, TRUE, 0.0},
175 {5, 5, TRUE, TRUE, 0.0},
176 {7, 7, TRUE, TRUE, 0.0},
177 {9, 9, TRUE, TRUE, 0.0},
178 {11, 11, TRUE, TRUE, 0.0},
180 {13, 11, TRUE, TRUE, 0.0},
184 static int game_fetch_preset(int i, char **name, game_params **params)
189 if (i < 0 || i >= lenof(net_presets))
192 ret = snew(game_params);
193 *ret = net_presets[i];
195 sprintf(str, "%dx%d%s", ret->width, ret->height,
196 ret->wrapping ? " wrapping" : "");
203 static void free_params(game_params *params)
208 static game_params *dup_params(game_params *params)
210 game_params *ret = snew(game_params);
211 *ret = *params; /* structure copy */
215 static void decode_params(game_params *ret, char const *string)
217 char const *p = string;
219 ret->width = atoi(p);
220 while (*p && isdigit((unsigned char)*p)) p++;
223 ret->height = atoi(p);
224 while (*p && isdigit((unsigned char)*p)) p++;
226 ret->height = ret->width;
232 ret->wrapping = TRUE;
233 } else if (*p == 'b') {
235 ret->barrier_probability = atof(p);
236 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
237 } else if (*p == 'a') {
241 p++; /* skip any other gunk */
245 static char *encode_params(game_params *params, int full)
250 len = sprintf(ret, "%dx%d", params->width, params->height);
251 if (params->wrapping)
253 if (full && params->barrier_probability)
254 len += sprintf(ret+len, "b%g", params->barrier_probability);
255 if (full && !params->unique)
257 assert(len < lenof(ret));
263 static config_item *game_configure(game_params *params)
268 ret = snewn(6, config_item);
270 ret[0].name = "Width";
271 ret[0].type = C_STRING;
272 sprintf(buf, "%d", params->width);
273 ret[0].sval = dupstr(buf);
276 ret[1].name = "Height";
277 ret[1].type = C_STRING;
278 sprintf(buf, "%d", params->height);
279 ret[1].sval = dupstr(buf);
282 ret[2].name = "Walls wrap around";
283 ret[2].type = C_BOOLEAN;
285 ret[2].ival = params->wrapping;
287 ret[3].name = "Barrier probability";
288 ret[3].type = C_STRING;
289 sprintf(buf, "%g", params->barrier_probability);
290 ret[3].sval = dupstr(buf);
293 ret[4].name = "Ensure unique solution";
294 ret[4].type = C_BOOLEAN;
296 ret[4].ival = params->unique;
306 static game_params *custom_params(config_item *cfg)
308 game_params *ret = snew(game_params);
310 ret->width = atoi(cfg[0].sval);
311 ret->height = atoi(cfg[1].sval);
312 ret->wrapping = cfg[2].ival;
313 ret->barrier_probability = (float)atof(cfg[3].sval);
314 ret->unique = cfg[4].ival;
319 static char *validate_params(game_params *params, int full)
321 if (params->width <= 0 || params->height <= 0)
322 return "Width and height must both be greater than zero";
323 if (params->width <= 1 && params->height <= 1)
324 return "At least one of width and height must be greater than one";
325 if (params->barrier_probability < 0)
326 return "Barrier probability may not be negative";
327 if (params->barrier_probability > 1)
328 return "Barrier probability may not be greater than 1";
331 * Specifying either grid dimension as 2 in a wrapping puzzle
332 * makes it actually impossible to ensure a unique puzzle
337 * Without loss of generality, let us assume the puzzle _width_
338 * is 2, so we can conveniently discuss rows without having to
339 * say `rows/columns' all the time. (The height may be 2 as
340 * well, but that doesn't matter.)
342 * In each row, there are two edges between tiles: the inner
343 * edge (running down the centre of the grid) and the outer
344 * edge (the identified left and right edges of the grid).
346 * Lemma: In any valid 2xn puzzle there must be at least one
347 * row in which _exactly one_ of the inner edge and outer edge
350 * Proof: No row can have _both_ inner and outer edges
351 * connected, because this would yield a loop. So the only
352 * other way to falsify the lemma is for every row to have
353 * _neither_ the inner nor outer edge connected. But this
354 * means there is no connection at all between the left and
355 * right columns of the puzzle, so there are two disjoint
356 * subgraphs, which is also disallowed. []
358 * Given such a row, it is always possible to make the
359 * disconnected edge connected and the connected edge
360 * disconnected without changing the state of any other edge.
361 * (This is easily seen by case analysis on the various tiles:
362 * left-pointing and right-pointing endpoints can be exchanged,
363 * likewise T-pieces, and a corner piece can select its
364 * horizontal connectivity independently of its vertical.) This
365 * yields a distinct valid solution.
367 * Thus, for _every_ row in which exactly one of the inner and
368 * outer edge is connected, there are two valid states for that
369 * row, and hence the total number of solutions of the puzzle
370 * is at least 2^(number of such rows), and in particular is at
371 * least 2 since there must be at least one such row. []
373 if (full && params->unique && params->wrapping &&
374 (params->width == 2 || params->height == 2))
375 return "No wrapping puzzle with a width or height of 2 can have"
376 " a unique solution";
381 /* ----------------------------------------------------------------------
382 * Solver used to assure solution uniqueness during generation.
386 * Test cases I used while debugging all this were
388 * ./net --generate 1 13x11w#12300
389 * which expands under the non-unique grid generation rules to
390 * 13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
391 * and has two ambiguous areas.
393 * An even better one is
394 * 13x11w#507896411361192
396 * 13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
397 * and has an ambiguous area _and_ a situation where loop avoidance
398 * is a necessary deductive technique.
401 * 48x25w#820543338195187
403 * 48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
404 * which has a spot (far right) where slightly more complex loop
405 * avoidance is required.
409 unsigned char *marked;
415 static struct todo *todo_new(int maxsize)
417 struct todo *todo = snew(struct todo);
418 todo->marked = snewn(maxsize, unsigned char);
419 memset(todo->marked, 0, maxsize);
420 todo->buflen = maxsize + 1;
421 todo->buffer = snewn(todo->buflen, int);
422 todo->head = todo->tail = 0;
426 static void todo_free(struct todo *todo)
433 static void todo_add(struct todo *todo, int index)
435 if (todo->marked[index])
436 return; /* already on the list */
437 todo->marked[index] = TRUE;
438 todo->buffer[todo->tail++] = index;
439 if (todo->tail == todo->buflen)
443 static int todo_get(struct todo *todo) {
446 if (todo->head == todo->tail)
447 return -1; /* list is empty */
448 ret = todo->buffer[todo->head++];
449 if (todo->head == todo->buflen)
451 todo->marked[ret] = FALSE;
456 static int net_solver(int w, int h, unsigned char *tiles,
457 unsigned char *barriers, int wrapping)
459 unsigned char *tilestate;
460 unsigned char *edgestate;
469 * Set up the solver's data structures.
473 * tilestate stores the possible orientations of each tile.
474 * There are up to four of these, so we'll index the array in
475 * fours. tilestate[(y * w + x) * 4] and its three successive
476 * members give the possible orientations, clearing to 255 from
477 * the end as things are ruled out.
479 * In this loop we also count up the area of the grid (which is
480 * not _necessarily_ equal to w*h, because there might be one
481 * or more blank squares present. This will never happen in a
482 * grid generated _by_ this program, but it's worth keeping the
483 * solver as general as possible.)
485 tilestate = snewn(w * h * 4, unsigned char);
487 for (i = 0; i < w*h; i++) {
488 tilestate[i * 4] = tiles[i] & 0xF;
489 for (j = 1; j < 4; j++) {
490 if (tilestate[i * 4 + j - 1] == 255 ||
491 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
492 tilestate[i * 4 + j] = 255;
494 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
501 * edgestate stores the known state of each edge. It is 0 for
502 * unknown, 1 for open (connected) and 2 for closed (not
505 * In principle we need only worry about each edge once each,
506 * but in fact it's easier to track each edge twice so that we
507 * can reference it from either side conveniently. Also I'm
508 * going to allocate _five_ bytes per tile, rather than the
509 * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
510 * where d is 1,2,4,8 and they never overlap.
512 edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
513 memset(edgestate, 0, (w * h - 1) * 5 + 9);
516 * deadends tracks which edges have dead ends on them. It is
517 * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
518 * tells you whether heading out of tile (x,y) in direction d
519 * can reach a limited amount of the grid. Values are area+1
520 * (no dead end known) or less than that (can reach _at most_
521 * this many other tiles by heading this way out of this tile).
523 deadends = snewn((w * h - 1) * 5 + 9, int);
524 for (i = 0; i < (w * h - 1) * 5 + 9; i++)
525 deadends[i] = area+1;
528 * equivalence tracks which sets of tiles are known to be
529 * connected to one another, so we can avoid creating loops by
530 * linking together tiles which are already linked through
533 * This is a disjoint set forest structure: equivalence[i]
534 * contains the index of another member of the equivalence
535 * class containing i, or contains i itself for precisely one
536 * member in each such class. To find a representative member
537 * of the equivalence class containing i, you keep replacing i
538 * with equivalence[i] until it stops changing; then you go
539 * _back_ along the same path and point everything on it
540 * directly at the representative member so as to speed up
541 * future searches. Then you test equivalence between tiles by
542 * finding the representative of each tile and seeing if
543 * they're the same; and you create new equivalence (merge
544 * classes) by finding the representative of each tile and
545 * setting equivalence[one]=the_other.
547 equivalence = snew_dsf(w * h);
550 * On a non-wrapping grid, we instantly know that all the edges
551 * round the edge are closed.
554 for (i = 0; i < w; i++) {
555 edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
557 for (i = 0; i < h; i++) {
558 edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
563 * If we have barriers available, we can mark those edges as
567 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
569 for (d = 1; d <= 8; d += d) {
570 if (barriers[y*w+x] & d) {
573 * In principle the barrier list should already
574 * contain each barrier from each side, but
575 * let's not take chances with our internal
578 OFFSETWH(x2, y2, x, y, d, w, h);
579 edgestate[(y*w+x) * 5 + d] = 2;
580 edgestate[(y2*w+x2) * 5 + F(d)] = 2;
587 * Since most deductions made by this solver are local (the
588 * exception is loop avoidance, where joining two tiles
589 * together on one side of the grid can theoretically permit a
590 * fresh deduction on the other), we can address the scaling
591 * problem inherent in iterating repeatedly over the entire
592 * grid by instead working with a to-do list.
594 todo = todo_new(w * h);
597 * Main deductive loop.
599 done_something = TRUE; /* prevent instant termination! */
604 * Take a tile index off the todo list and process it.
606 index = todo_get(todo);
609 * If we have run out of immediate things to do, we
610 * have no choice but to scan the whole grid for
611 * longer-range things we've missed. Hence, I now add
612 * every square on the grid back on to the to-do list.
613 * I also set `done_something' to FALSE at this point;
614 * if we later come back here and find it still FALSE,
615 * we will know we've scanned the entire grid without
616 * finding anything new to do, and we can terminate.
620 for (i = 0; i < w*h; i++)
622 done_something = FALSE;
624 index = todo_get(todo);
630 int d, ourclass = dsf_canonify(equivalence, y*w+x);
633 deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
635 for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
637 int nnondeadends, nondeadends[4], deadendtotal;
638 int nequiv, equiv[5];
639 int val = tilestate[(y*w+x) * 4 + i];
642 nnondeadends = deadendtotal = 0;
645 for (d = 1; d <= 8; d += d) {
647 * Immediately rule out this orientation if it
648 * conflicts with any known edge.
650 if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
651 (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
656 * Count up the dead-end statistics.
658 if (deadends[(y*w+x) * 5 + d] <= area) {
659 deadendtotal += deadends[(y*w+x) * 5 + d];
661 nondeadends[nnondeadends++] = d;
665 * Ensure we aren't linking to any tiles,
666 * through edges not already known to be
667 * open, which create a loop.
669 if (edgestate[(y*w+x) * 5 + d] == 0) {
672 OFFSETWH(x2, y2, x, y, d, w, h);
673 c = dsf_canonify(equivalence, y2*w+x2);
674 for (k = 0; k < nequiv; k++)
685 if (nnondeadends == 0) {
687 * If this orientation links together dead-ends
688 * with a total area of less than the entire
689 * grid, it is invalid.
691 * (We add 1 to deadendtotal because of the
692 * tile itself, of course; one tile linking
693 * dead ends of size 2 and 3 forms a subnetwork
694 * with a total area of 6, not 5.)
696 if (deadendtotal > 0 && deadendtotal+1 < area)
698 } else if (nnondeadends == 1) {
700 * If this orientation links together one or
701 * more dead-ends with precisely one
702 * non-dead-end, then we may have to mark that
703 * non-dead-end as a dead end going the other
704 * way. However, it depends on whether all
705 * other orientations share the same property.
708 if (deadendmax[nondeadends[0]] < deadendtotal)
709 deadendmax[nondeadends[0]] = deadendtotal;
712 * If this orientation links together two or
713 * more non-dead-ends, then we can rule out the
714 * possibility of putting in new dead-end
715 * markings in those directions.
718 for (k = 0; k < nnondeadends; k++)
719 deadendmax[nondeadends[k]] = area+1;
723 tilestate[(y*w+x) * 4 + j++] = val;
724 #ifdef SOLVER_DIAGNOSTICS
726 printf("ruling out orientation %x at %d,%d\n", val, x, y);
730 assert(j > 0); /* we can't lose _all_ possibilities! */
733 done_something = TRUE;
736 * We have ruled out at least one tile orientation.
737 * Make sure the rest are blanked.
740 tilestate[(y*w+x) * 4 + j++] = 255;
744 * Now go through the tile orientations again and see
745 * if we've deduced anything new about any edges.
751 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
752 a &= tilestate[(y*w+x) * 4 + i];
753 o |= tilestate[(y*w+x) * 4 + i];
755 for (d = 1; d <= 8; d += d)
756 if (edgestate[(y*w+x) * 5 + d] == 0) {
758 OFFSETWH(x2, y2, x, y, d, w, h);
761 /* This edge is open in all orientations. */
762 #ifdef SOLVER_DIAGNOSTICS
763 printf("marking edge %d,%d:%d open\n", x, y, d);
765 edgestate[(y*w+x) * 5 + d] = 1;
766 edgestate[(y2*w+x2) * 5 + d2] = 1;
767 dsf_merge(equivalence, y*w+x, y2*w+x2);
768 done_something = TRUE;
769 todo_add(todo, y2*w+x2);
770 } else if (!(o & d)) {
771 /* This edge is closed in all orientations. */
772 #ifdef SOLVER_DIAGNOSTICS
773 printf("marking edge %d,%d:%d closed\n", x, y, d);
775 edgestate[(y*w+x) * 5 + d] = 2;
776 edgestate[(y2*w+x2) * 5 + d2] = 2;
777 done_something = TRUE;
778 todo_add(todo, y2*w+x2);
785 * Now check the dead-end markers and see if any of
786 * them has lowered from the real ones.
788 for (d = 1; d <= 8; d += d) {
790 OFFSETWH(x2, y2, x, y, d, w, h);
792 if (deadendmax[d] > 0 &&
793 deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
794 #ifdef SOLVER_DIAGNOSTICS
795 printf("setting dead end value %d,%d:%d to %d\n",
796 x2, y2, d2, deadendmax[d]);
798 deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
799 done_something = TRUE;
800 todo_add(todo, y2*w+x2);
808 * Mark all completely determined tiles as locked.
811 for (i = 0; i < w*h; i++) {
812 if (tilestate[i * 4 + 1] == 255) {
813 assert(tilestate[i * 4 + 0] != 255);
814 tiles[i] = tilestate[i * 4] | LOCKED;
822 * Free up working space.
833 /* ----------------------------------------------------------------------
834 * Randomly select a new game description.
838 * Function to randomly perturb an ambiguous section in a grid, to
839 * attempt to ensure unique solvability.
841 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
842 random_state *rs, int startx, int starty, int startd)
844 struct xyd *perimeter, *perim2, *loop[2], looppos[2];
845 int nperim, perimsize, nloop[2], loopsize[2];
849 * We know that the tile at (startx,starty) is part of an
850 * ambiguous section, and we also know that its neighbour in
851 * direction startd is fully specified. We begin by tracing all
852 * the way round the ambiguous area.
854 nperim = perimsize = 0;
859 #ifdef PERTURB_DIAGNOSTICS
860 printf("perturb %d,%d:%d\n", x, y, d);
865 if (nperim >= perimsize) {
866 perimsize = perimsize * 3 / 2 + 32;
867 perimeter = sresize(perimeter, perimsize, struct xyd);
869 perimeter[nperim].x = x;
870 perimeter[nperim].y = y;
871 perimeter[nperim].direction = d;
873 #ifdef PERTURB_DIAGNOSTICS
874 printf("perimeter: %d,%d:%d\n", x, y, d);
878 * First, see if we can simply turn left from where we are
879 * and find another locked square.
882 OFFSETWH(x2, y2, x, y, d2, w, h);
883 if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
884 (tiles[y2*w+x2] & LOCKED)) {
888 * Failing that, step left into the new square and look
893 OFFSETWH(x2, y2, x, y, d, w, h);
894 if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
895 !(tiles[y2*w+x2] & LOCKED)) {
897 * And failing _that_, we're going to have to step
898 * forward into _that_ square and look right at the
899 * same locked square as we started with.
907 } while (x != startx || y != starty || d != startd);
910 * Our technique for perturbing this ambiguous area is to
911 * search round its edge for a join we can make: that is, an
912 * edge on the perimeter which is (a) not currently connected,
913 * and (b) connecting it would not yield a full cross on either
914 * side. Then we make that join, search round the network to
915 * find the loop thus constructed, and sever the loop at a
916 * randomly selected other point.
918 perim2 = snewn(nperim, struct xyd);
919 memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
920 /* Shuffle the perimeter, so as to search it without directional bias. */
921 shuffle(perim2, nperim, sizeof(*perim2), rs);
922 for (i = 0; i < nperim; i++) {
927 d = perim2[i].direction;
929 OFFSETWH(x2, y2, x, y, d, w, h);
930 if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
931 continue; /* can't link across non-wrapping border */
932 if (tiles[y*w+x] & d)
933 continue; /* already linked in this direction! */
934 if (((tiles[y*w+x] | d) & 15) == 15)
935 continue; /* can't turn this tile into a cross */
936 if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
937 continue; /* can't turn other tile into a cross */
940 * We've found the point at which we're going to make a new
943 #ifdef PERTURB_DIAGNOSTICS
944 printf("linking %d,%d:%d\n", x, y, d);
947 tiles[y2*w+x2] |= F(d);
954 return; /* nothing we can do! */
957 * Now we've constructed a new link, we need to find the entire
958 * loop of which it is a part.
960 * In principle, this involves doing a complete search round
961 * the network. However, I anticipate that in the vast majority
962 * of cases the loop will be quite small, so what I'm going to
963 * do is make _two_ searches round the network in parallel, one
964 * keeping its metaphorical hand on the left-hand wall while
965 * the other keeps its hand on the right. As soon as one of
966 * them gets back to its starting point, I abandon the other.
968 for (i = 0; i < 2; i++) {
969 loopsize[i] = nloop[i] = 0;
973 looppos[i].direction = d;
976 for (i = 0; i < 2; i++) {
981 d = looppos[i].direction;
983 OFFSETWH(x2, y2, x, y, d, w, h);
986 * Add this path segment to the loop, unless it exactly
987 * reverses the previous one on the loop in which case
988 * we take it away again.
990 #ifdef PERTURB_DIAGNOSTICS
991 printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
994 loop[i][nloop[i]-1].x == x2 &&
995 loop[i][nloop[i]-1].y == y2 &&
996 loop[i][nloop[i]-1].direction == F(d)) {
997 #ifdef PERTURB_DIAGNOSTICS
998 printf("removing path segment %d,%d:%d from loop[%d]\n",
1003 if (nloop[i] >= loopsize[i]) {
1004 loopsize[i] = loopsize[i] * 3 / 2 + 32;
1005 loop[i] = sresize(loop[i], loopsize[i], struct xyd);
1007 #ifdef PERTURB_DIAGNOSTICS
1008 printf("adding path segment %d,%d:%d to loop[%d]\n",
1011 loop[i][nloop[i]++] = looppos[i];
1014 #ifdef PERTURB_DIAGNOSTICS
1015 printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
1018 for (j = 0; j < 4; j++) {
1023 #ifdef PERTURB_DIAGNOSTICS
1024 printf("trying dir %d\n", d);
1026 if (tiles[y2*w+x2] & d) {
1029 looppos[i].direction = d;
1035 assert(nloop[i] > 0);
1037 if (looppos[i].x == loop[i][0].x &&
1038 looppos[i].y == loop[i][0].y &&
1039 looppos[i].direction == loop[i][0].direction) {
1040 #ifdef PERTURB_DIAGNOSTICS
1041 printf("loop %d finished tracking\n", i);
1045 * Having found our loop, we now sever it at a
1046 * randomly chosen point - absolutely any will do -
1047 * which is not the one we joined it at to begin
1048 * with. Conveniently, the one we joined it at is
1049 * loop[i][0], so we just avoid that one.
1051 j = random_upto(rs, nloop[i]-1) + 1;
1054 d = loop[i][j].direction;
1055 OFFSETWH(x2, y2, x, y, d, w, h);
1057 tiles[y2*w+x2] &= ~F(d);
1069 * Finally, we must mark the entire disputed section as locked,
1070 * to prevent the perturb function being called on it multiple
1073 * To do this, we _sort_ the perimeter of the area. The
1074 * existing xyd_cmp function will arrange things into columns
1075 * for us, in such a way that each column has the edges in
1076 * vertical order. Then we can work down each column and fill
1077 * in all the squares between an up edge and a down edge.
1079 qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1081 for (i = 0; i <= nperim; i++) {
1082 if (i == nperim || perimeter[i].x > x) {
1084 * Fill in everything from the last Up edge to the
1085 * bottom of the grid, if necessary.
1089 #ifdef PERTURB_DIAGNOSTICS
1090 printf("resolved: locking tile %d,%d\n", x, y);
1092 tiles[y * w + x] |= LOCKED;
1105 if (perimeter[i].direction == U) {
1108 } else if (perimeter[i].direction == D) {
1110 * Fill in everything from the last Up edge to here.
1112 assert(x == perimeter[i].x && y <= perimeter[i].y);
1113 while (y <= perimeter[i].y) {
1114 #ifdef PERTURB_DIAGNOSTICS
1115 printf("resolved: locking tile %d,%d\n", x, y);
1117 tiles[y * w + x] |= LOCKED;
1127 static char *new_game_desc(game_params *params, random_state *rs,
1128 char **aux, int interactive)
1130 tree234 *possibilities, *barriertree;
1131 int w, h, x, y, cx, cy, nbarriers;
1132 unsigned char *tiles, *barriers;
1141 tiles = snewn(w * h, unsigned char);
1142 barriers = snewn(w * h, unsigned char);
1146 memset(tiles, 0, w * h);
1147 memset(barriers, 0, w * h);
1150 * Construct the unshuffled grid.
1152 * To do this, we simply start at the centre point, repeatedly
1153 * choose a random possibility out of the available ways to
1154 * extend a used square into an unused one, and do it. After
1155 * extending the third line out of a square, we remove the
1156 * fourth from the possibilities list to avoid any full-cross
1157 * squares (which would make the game too easy because they
1158 * only have one orientation).
1160 * The slightly worrying thing is the avoidance of full-cross
1161 * squares. Can this cause our unsophisticated construction
1162 * algorithm to paint itself into a corner, by getting into a
1163 * situation where there are some unreached squares and the
1164 * only way to reach any of them is to extend a T-piece into a
1167 * Answer: no it can't, and here's a proof.
1169 * Any contiguous group of such unreachable squares must be
1170 * surrounded on _all_ sides by T-pieces pointing away from the
1171 * group. (If not, then there is a square which can be extended
1172 * into one of the `unreachable' ones, and so it wasn't
1173 * unreachable after all.) In particular, this implies that
1174 * each contiguous group of unreachable squares must be
1175 * rectangular in shape (any deviation from that yields a
1176 * non-T-piece next to an `unreachable' square).
1178 * So we have a rectangle of unreachable squares, with T-pieces
1179 * forming a solid border around the rectangle. The corners of
1180 * that border must be connected (since every tile connects all
1181 * the lines arriving in it), and therefore the border must
1182 * form a closed loop around the rectangle.
1184 * But this can't have happened in the first place, since we
1185 * _know_ we've avoided creating closed loops! Hence, no such
1186 * situation can ever arise, and the naive grid construction
1187 * algorithm will guaranteeably result in a complete grid
1188 * containing no unreached squares, no full crosses _and_ no
1191 possibilities = newtree234(xyd_cmp_nc);
1194 add234(possibilities, new_xyd(cx, cy, R));
1196 add234(possibilities, new_xyd(cx, cy, U));
1198 add234(possibilities, new_xyd(cx, cy, L));
1200 add234(possibilities, new_xyd(cx, cy, D));
1202 while (count234(possibilities) > 0) {
1205 int x1, y1, d1, x2, y2, d2, d;
1208 * Extract a randomly chosen possibility from the list.
1210 i = random_upto(rs, count234(possibilities));
1211 xyd = delpos234(possibilities, i);
1214 d1 = xyd->direction;
1217 OFFSET(x2, y2, x1, y1, d1, params);
1219 #ifdef GENERATION_DIAGNOSTICS
1220 printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1221 x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1225 * Make the connection. (We should be moving to an as yet
1228 index(params, tiles, x1, y1) |= d1;
1229 assert(index(params, tiles, x2, y2) == 0);
1230 index(params, tiles, x2, y2) |= d2;
1233 * If we have created a T-piece, remove its last
1236 if (COUNT(index(params, tiles, x1, y1)) == 3) {
1237 struct xyd xyd1, *xydp;
1241 xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1243 xydp = find234(possibilities, &xyd1, NULL);
1246 #ifdef GENERATION_DIAGNOSTICS
1247 printf("T-piece; removing (%d,%d,%c)\n",
1248 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1250 del234(possibilities, xydp);
1256 * Remove all other possibilities that were pointing at the
1257 * tile we've just moved into.
1259 for (d = 1; d < 0x10; d <<= 1) {
1261 struct xyd xyd1, *xydp;
1263 OFFSET(x3, y3, x2, y2, d, params);
1268 xyd1.direction = d3;
1270 xydp = find234(possibilities, &xyd1, NULL);
1273 #ifdef GENERATION_DIAGNOSTICS
1274 printf("Loop avoidance; removing (%d,%d,%c)\n",
1275 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1277 del234(possibilities, xydp);
1283 * Add new possibilities to the list for moving _out_ of
1284 * the tile we have just moved into.
1286 for (d = 1; d < 0x10; d <<= 1) {
1290 continue; /* we've got this one already */
1292 if (!params->wrapping) {
1293 if (d == U && y2 == 0)
1295 if (d == D && y2 == h-1)
1297 if (d == L && x2 == 0)
1299 if (d == R && x2 == w-1)
1303 OFFSET(x3, y3, x2, y2, d, params);
1305 if (index(params, tiles, x3, y3))
1306 continue; /* this would create a loop */
1308 #ifdef GENERATION_DIAGNOSTICS
1309 printf("New frontier; adding (%d,%d,%c)\n",
1310 x2, y2, "0RU3L567D9abcdef"[d]);
1312 add234(possibilities, new_xyd(x2, y2, d));
1315 /* Having done that, we should have no possibilities remaining. */
1316 assert(count234(possibilities) == 0);
1317 freetree234(possibilities);
1319 if (params->unique) {
1323 * Run the solver to check unique solubility.
1325 while (!net_solver(w, h, tiles, NULL, params->wrapping)) {
1329 * We expect (in most cases) that most of the grid will
1330 * be uniquely specified already, and the remaining
1331 * ambiguous sections will be small and separate. So
1332 * our strategy is to find each individual such
1333 * section, and perform a perturbation on the network
1336 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1337 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1339 if (tiles[y*w+x] & LOCKED)
1340 perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1342 perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1344 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1346 if (tiles[y*w+x] & LOCKED)
1347 perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1349 perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1354 * Now n counts the number of ambiguous sections we
1355 * have fiddled with. If we haven't managed to decrease
1356 * it from the last time we ran the solver, give up and
1357 * regenerate the entire grid.
1359 if (prevn != -1 && prevn <= n)
1360 goto begin_generation; /* (sorry) */
1366 * The solver will have left a lot of LOCKED bits lying
1367 * around in the tiles array. Remove them.
1369 for (x = 0; x < w*h; x++)
1370 tiles[x] &= ~LOCKED;
1374 * Now compute a list of the possible barrier locations.
1376 barriertree = newtree234(xyd_cmp_nc);
1377 for (y = 0; y < h; y++) {
1378 for (x = 0; x < w; x++) {
1380 if (!(index(params, tiles, x, y) & R) &&
1381 (params->wrapping || x < w-1))
1382 add234(barriertree, new_xyd(x, y, R));
1383 if (!(index(params, tiles, x, y) & D) &&
1384 (params->wrapping || y < h-1))
1385 add234(barriertree, new_xyd(x, y, D));
1390 * Save the unshuffled grid in aux.
1396 solution = snewn(w * h + 1, char);
1397 for (i = 0; i < w * h; i++)
1398 solution[i] = "0123456789abcdef"[tiles[i] & 0xF];
1399 solution[w*h] = '\0';
1405 * Now shuffle the grid.
1407 * In order to avoid accidentally generating an already-solved
1408 * grid, we will reshuffle as necessary to ensure that at least
1409 * one edge has a mismatched connection.
1411 * This can always be done, since validate_params() enforces a
1412 * grid area of at least 2 and our generator never creates
1413 * either type of rotationally invariant tile (cross and
1414 * blank). Hence there must be at least one edge separating
1415 * distinct tiles, and it must be possible to find orientations
1416 * of those tiles such that one tile is trying to connect
1417 * through that edge and the other is not.
1419 * (We could be more subtle, and allow the shuffle to generate
1420 * a grid in which all tiles match up locally and the only
1421 * criterion preventing the grid from being already solved is
1422 * connectedness. However, that would take more effort, and
1423 * it's easier to simply make sure every grid is _obviously_
1429 for (y = 0; y < h; y++) {
1430 for (x = 0; x < w; x++) {
1431 int orig = index(params, tiles, x, y);
1432 int rot = random_upto(rs, 4);
1433 index(params, tiles, x, y) = ROT(orig, rot);
1439 * I can't even be bothered to check for mismatches across
1440 * a wrapping edge, so I'm just going to enforce that there
1441 * must be a mismatch across a non-wrapping edge, which is
1442 * still always possible.
1444 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1445 if (x+1 < w && ((ROT(index(params, tiles, x, y), 2) ^
1446 index(params, tiles, x+1, y)) & L))
1448 if (y+1 < h && ((ROT(index(params, tiles, x, y), 2) ^
1449 index(params, tiles, x, y+1)) & U))
1458 * And now choose barrier locations. (We carefully do this
1459 * _after_ shuffling, so that changing the barrier rate in the
1460 * params while keeping the random seed the same will give the
1461 * same shuffled grid and _only_ change the barrier locations.
1462 * Also the way we choose barrier locations, by repeatedly
1463 * choosing one possibility from the list until we have enough,
1464 * is designed to ensure that raising the barrier rate while
1465 * keeping the seed the same will provide a superset of the
1466 * previous barrier set - i.e. if you ask for 10 barriers, and
1467 * then decide that's still too hard and ask for 20, you'll get
1468 * the original 10 plus 10 more, rather than getting 20 new
1469 * ones and the chance of remembering your first 10.)
1471 nbarriers = (int)(params->barrier_probability * count234(barriertree));
1472 assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1474 while (nbarriers > 0) {
1477 int x1, y1, d1, x2, y2, d2;
1480 * Extract a randomly chosen barrier from the list.
1482 i = random_upto(rs, count234(barriertree));
1483 xyd = delpos234(barriertree, i);
1485 assert(xyd != NULL);
1489 d1 = xyd->direction;
1492 OFFSET(x2, y2, x1, y1, d1, params);
1495 index(params, barriers, x1, y1) |= d1;
1496 index(params, barriers, x2, y2) |= d2;
1502 * Clean up the rest of the barrier list.
1507 while ( (xyd = delpos234(barriertree, 0)) != NULL)
1510 freetree234(barriertree);
1514 * Finally, encode the grid into a string game description.
1516 * My syntax is extremely simple: each square is encoded as a
1517 * hex digit in which bit 0 means a connection on the right,
1518 * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1519 * encoding as used internally). Each digit is followed by
1520 * optional barrier indicators: `v' means a vertical barrier to
1521 * the right of it, and `h' means a horizontal barrier below
1524 desc = snewn(w * h * 3 + 1, char);
1526 for (y = 0; y < h; y++) {
1527 for (x = 0; x < w; x++) {
1528 *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1529 if ((params->wrapping || x < w-1) &&
1530 (index(params, barriers, x, y) & R))
1532 if ((params->wrapping || y < h-1) &&
1533 (index(params, barriers, x, y) & D))
1537 assert(p - desc <= w*h*3);
1546 static char *validate_desc(game_params *params, char *desc)
1548 int w = params->width, h = params->height;
1551 for (i = 0; i < w*h; i++) {
1552 if (*desc >= '0' && *desc <= '9')
1554 else if (*desc >= 'a' && *desc <= 'f')
1556 else if (*desc >= 'A' && *desc <= 'F')
1559 return "Game description shorter than expected";
1561 return "Game description contained unexpected character";
1563 while (*desc == 'h' || *desc == 'v')
1567 return "Game description longer than expected";
1572 /* ----------------------------------------------------------------------
1573 * Construct an initial game state, given a description and parameters.
1576 static game_state *new_game(midend *me, game_params *params, char *desc)
1581 assert(params->width > 0 && params->height > 0);
1582 assert(params->width > 1 || params->height > 1);
1585 * Create a blank game state.
1587 state = snew(game_state);
1588 w = state->width = params->width;
1589 h = state->height = params->height;
1590 state->wrapping = params->wrapping;
1591 state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1592 state->completed = state->used_solve = FALSE;
1593 state->tiles = snewn(state->width * state->height, unsigned char);
1594 memset(state->tiles, 0, state->width * state->height);
1595 state->barriers = snewn(state->width * state->height, unsigned char);
1596 memset(state->barriers, 0, state->width * state->height);
1599 * Parse the game description into the grid.
1601 for (y = 0; y < h; y++) {
1602 for (x = 0; x < w; x++) {
1603 if (*desc >= '0' && *desc <= '9')
1604 tile(state, x, y) = *desc - '0';
1605 else if (*desc >= 'a' && *desc <= 'f')
1606 tile(state, x, y) = *desc - 'a' + 10;
1607 else if (*desc >= 'A' && *desc <= 'F')
1608 tile(state, x, y) = *desc - 'A' + 10;
1611 while (*desc == 'h' || *desc == 'v') {
1618 OFFSET(x2, y2, x, y, d1, state);
1621 barrier(state, x, y) |= d1;
1622 barrier(state, x2, y2) |= d2;
1630 * Set up border barriers if this is a non-wrapping game.
1632 if (!state->wrapping) {
1633 for (x = 0; x < state->width; x++) {
1634 barrier(state, x, 0) |= U;
1635 barrier(state, x, state->height-1) |= D;
1637 for (y = 0; y < state->height; y++) {
1638 barrier(state, 0, y) |= L;
1639 barrier(state, state->width-1, y) |= R;
1643 * We check whether this is de-facto a non-wrapping game
1644 * despite the parameters, in case we were passed the
1645 * description of a non-wrapping game. This is so that we
1646 * can change some aspects of the UI behaviour.
1648 state->wrapping = FALSE;
1649 for (x = 0; x < state->width; x++)
1650 if (!(barrier(state, x, 0) & U) ||
1651 !(barrier(state, x, state->height-1) & D))
1652 state->wrapping = TRUE;
1653 for (y = 0; y < state->width; y++)
1654 if (!(barrier(state, 0, y) & L) ||
1655 !(barrier(state, state->width-1, y) & R))
1656 state->wrapping = TRUE;
1662 static game_state *dup_game(game_state *state)
1666 ret = snew(game_state);
1667 ret->width = state->width;
1668 ret->height = state->height;
1669 ret->wrapping = state->wrapping;
1670 ret->completed = state->completed;
1671 ret->used_solve = state->used_solve;
1672 ret->last_rotate_dir = state->last_rotate_dir;
1673 ret->last_rotate_x = state->last_rotate_x;
1674 ret->last_rotate_y = state->last_rotate_y;
1675 ret->tiles = snewn(state->width * state->height, unsigned char);
1676 memcpy(ret->tiles, state->tiles, state->width * state->height);
1677 ret->barriers = snewn(state->width * state->height, unsigned char);
1678 memcpy(ret->barriers, state->barriers, state->width * state->height);
1683 static void free_game(game_state *state)
1685 sfree(state->tiles);
1686 sfree(state->barriers);
1690 static char *solve_game(game_state *state, game_state *currstate,
1691 char *aux, char **error)
1693 unsigned char *tiles;
1695 int retlen, retsize;
1698 tiles = snewn(state->width * state->height, unsigned char);
1702 * Run the internal solver on the provided grid. This might
1703 * not yield a complete solution.
1705 memcpy(tiles, state->tiles, state->width * state->height);
1706 net_solver(state->width, state->height, tiles,
1707 state->barriers, state->wrapping);
1709 for (i = 0; i < state->width * state->height; i++) {
1712 if (c >= '0' && c <= '9')
1714 else if (c >= 'a' && c <= 'f')
1715 tiles[i] = c - 'a' + 10;
1716 else if (c >= 'A' && c <= 'F')
1717 tiles[i] = c - 'A' + 10;
1724 * Now construct a string which can be passed to execute_move()
1725 * to transform the current grid into the solved one.
1728 ret = snewn(retsize, char);
1730 ret[retlen++] = 'S';
1732 for (i = 0; i < state->width * state->height; i++) {
1733 int from = currstate->tiles[i], to = tiles[i];
1734 int ft = from & (R|L|U|D), tt = to & (R|L|U|D);
1735 int x = i % state->width, y = i / state->width;
1737 char buf[80], *p = buf;
1740 continue; /* nothing needs doing at all */
1743 * To transform this tile into the desired tile: first
1744 * unlock the tile if it's locked, then rotate it if
1745 * necessary, then lock it if necessary.
1748 p += sprintf(p, ";L%d,%d", x, y);
1752 else if (tt == C(ft))
1754 else if (tt == F(ft))
1761 p += sprintf(p, ";%c%d,%d", chr, x, y);
1764 p += sprintf(p, ";L%d,%d", x, y);
1767 if (retlen + (p - buf) >= retsize) {
1768 retsize = retlen + (p - buf) + 512;
1769 ret = sresize(ret, retsize, char);
1771 memcpy(ret+retlen, buf, p - buf);
1776 assert(retlen < retsize);
1778 ret = sresize(ret, retlen+1, char);
1785 static char *game_text_format(game_state *state)
1790 /* ----------------------------------------------------------------------
1795 * Compute which squares are reachable from the centre square, as a
1796 * quick visual aid to determining how close the game is to
1797 * completion. This is also a simple way to tell if the game _is_
1798 * completed - just call this function and see whether every square
1801 static unsigned char *compute_active(game_state *state, int cx, int cy)
1803 unsigned char *active;
1807 active = snewn(state->width * state->height, unsigned char);
1808 memset(active, 0, state->width * state->height);
1811 * We only store (x,y) pairs in todo, but it's easier to reuse
1812 * xyd_cmp and just store direction 0 every time.
1814 todo = newtree234(xyd_cmp_nc);
1815 index(state, active, cx, cy) = ACTIVE;
1816 add234(todo, new_xyd(cx, cy, 0));
1818 while ( (xyd = delpos234(todo, 0)) != NULL) {
1819 int x1, y1, d1, x2, y2, d2;
1825 for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1826 OFFSET(x2, y2, x1, y1, d1, state);
1830 * If the next tile in this direction is connected to
1831 * us, and there isn't a barrier in the way, and it
1832 * isn't already marked active, then mark it active and
1833 * add it to the to-examine list.
1835 if ((tile(state, x1, y1) & d1) &&
1836 (tile(state, x2, y2) & d2) &&
1837 !(barrier(state, x1, y1) & d1) &&
1838 !index(state, active, x2, y2)) {
1839 index(state, active, x2, y2) = ACTIVE;
1840 add234(todo, new_xyd(x2, y2, 0));
1844 /* Now we expect the todo list to have shrunk to zero size. */
1845 assert(count234(todo) == 0);
1852 int org_x, org_y; /* origin */
1853 int cx, cy; /* source tile (game coordinates) */
1856 random_state *rs; /* used for jumbling */
1858 int dragtilex, dragtiley, dragstartx, dragstarty, dragged;
1862 static game_ui *new_ui(game_state *state)
1866 game_ui *ui = snew(game_ui);
1867 ui->org_x = ui->org_y = 0;
1868 ui->cur_x = ui->cx = state->width / 2;
1869 ui->cur_y = ui->cy = state->height / 2;
1870 ui->cur_visible = FALSE;
1871 get_random_seed(&seed, &seedsize);
1872 ui->rs = random_new(seed, seedsize);
1878 static void free_ui(game_ui *ui)
1880 random_free(ui->rs);
1884 static char *encode_ui(game_ui *ui)
1888 * We preserve the origin and centre-point coordinates over a
1891 sprintf(buf, "O%d,%d;C%d,%d", ui->org_x, ui->org_y, ui->cx, ui->cy);
1895 static void decode_ui(game_ui *ui, char *encoding)
1897 sscanf(encoding, "O%d,%d;C%d,%d",
1898 &ui->org_x, &ui->org_y, &ui->cx, &ui->cy);
1901 static void game_changed_state(game_ui *ui, game_state *oldstate,
1902 game_state *newstate)
1906 struct game_drawstate {
1911 unsigned char *visible;
1914 /* ----------------------------------------------------------------------
1917 static char *interpret_move(game_state *state, game_ui *ui,
1918 game_drawstate *ds, int x, int y, int button)
1921 int tx = -1, ty = -1, dir = 0;
1922 int shift = button & MOD_SHFT, ctrl = button & MOD_CTRL;
1924 NONE, ROTATE_LEFT, ROTATE_180, ROTATE_RIGHT, TOGGLE_LOCK, JUMBLE,
1925 MOVE_ORIGIN, MOVE_SOURCE, MOVE_ORIGIN_AND_SOURCE, MOVE_CURSOR
1928 button &= ~MOD_MASK;
1932 if (button == LEFT_BUTTON ||
1933 button == MIDDLE_BUTTON ||
1935 button == LEFT_DRAG ||
1936 button == LEFT_RELEASE ||
1937 button == RIGHT_DRAG ||
1938 button == RIGHT_RELEASE ||
1940 button == RIGHT_BUTTON) {
1942 if (ui->cur_visible) {
1943 ui->cur_visible = FALSE;
1948 * The button must have been clicked on a valid tile.
1950 x -= WINDOW_OFFSET + TILE_BORDER;
1951 y -= WINDOW_OFFSET + TILE_BORDER;
1956 if (tx >= state->width || ty >= state->height)
1958 /* Transform from physical to game coords */
1959 tx = (tx + ui->org_x) % state->width;
1960 ty = (ty + ui->org_y) % state->height;
1961 if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
1962 y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
1967 if (button == MIDDLE_BUTTON
1969 || button == RIGHT_BUTTON /* with a stylus, `right-click' locks */
1973 * Middle button never drags: it only toggles the lock.
1975 action = TOGGLE_LOCK;
1976 } else if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1978 * Otherwise, we note down the start point for a drag.
1982 ui->dragstartx = x % TILE_SIZE;
1983 ui->dragstarty = y % TILE_SIZE;
1984 ui->dragged = FALSE;
1985 return nullret; /* no actual action */
1986 } else if (button == LEFT_DRAG || button == RIGHT_DRAG) {
1988 * Find the new drag point and see if it necessitates a
1991 int x0,y0, xA,yA, xC,yC, xF,yF;
1993 int d0, dA, dC, dF, dmin;
1998 mx = x - (ui->dragtilex * TILE_SIZE);
1999 my = y - (ui->dragtiley * TILE_SIZE);
2001 x0 = ui->dragstartx;
2002 y0 = ui->dragstarty;
2003 xA = ui->dragstarty;
2004 yA = TILE_SIZE-1 - ui->dragstartx;
2005 xF = TILE_SIZE-1 - ui->dragstartx;
2006 yF = TILE_SIZE-1 - ui->dragstarty;
2007 xC = TILE_SIZE-1 - ui->dragstarty;
2008 yC = ui->dragstartx;
2010 d0 = (mx-x0)*(mx-x0) + (my-y0)*(my-y0);
2011 dA = (mx-xA)*(mx-xA) + (my-yA)*(my-yA);
2012 dF = (mx-xF)*(mx-xF) + (my-yF)*(my-yF);
2013 dC = (mx-xC)*(mx-xC) + (my-yC)*(my-yC);
2015 dmin = min(min(d0,dA),min(dF,dC));
2019 } else if (dF == dmin) {
2020 action = ROTATE_180;
2021 ui->dragstartx = xF;
2022 ui->dragstarty = yF;
2024 } else if (dA == dmin) {
2025 action = ROTATE_LEFT;
2026 ui->dragstartx = xA;
2027 ui->dragstarty = yA;
2029 } else /* dC == dmin */ {
2030 action = ROTATE_RIGHT;
2031 ui->dragstartx = xC;
2032 ui->dragstarty = yC;
2035 } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
2038 * There was a click but no perceptible drag:
2039 * revert to single-click behaviour.
2044 if (button == LEFT_RELEASE)
2045 action = ROTATE_LEFT;
2047 action = ROTATE_RIGHT;
2049 return nullret; /* no action */
2052 #else /* USE_DRAGGING */
2054 action = (button == LEFT_BUTTON ? ROTATE_LEFT :
2055 button == RIGHT_BUTTON ? ROTATE_RIGHT : TOGGLE_LOCK);
2057 #endif /* USE_DRAGGING */
2059 } else if (button == CURSOR_UP || button == CURSOR_DOWN ||
2060 button == CURSOR_RIGHT || button == CURSOR_LEFT) {
2062 case CURSOR_UP: dir = U; break;
2063 case CURSOR_DOWN: dir = D; break;
2064 case CURSOR_LEFT: dir = L; break;
2065 case CURSOR_RIGHT: dir = R; break;
2066 default: return nullret;
2068 if (shift && ctrl) action = MOVE_ORIGIN_AND_SOURCE;
2069 else if (shift) action = MOVE_ORIGIN;
2070 else if (ctrl) action = MOVE_SOURCE;
2071 else action = MOVE_CURSOR;
2072 } else if (button == 'a' || button == 's' || button == 'd' ||
2073 button == 'A' || button == 'S' || button == 'D' ||
2074 button == 'f' || button == 'F' ||
2075 button == CURSOR_SELECT) {
2078 if (button == 'a' || button == 'A' || button == CURSOR_SELECT)
2079 action = ROTATE_LEFT;
2080 else if (button == 's' || button == 'S')
2081 action = TOGGLE_LOCK;
2082 else if (button == 'd' || button == 'D')
2083 action = ROTATE_RIGHT;
2084 else if (button == 'f' || button == 'F')
2085 action = ROTATE_180;
2086 ui->cur_visible = TRUE;
2087 } else if (button == 'j' || button == 'J') {
2088 /* XXX should we have some mouse control for this? */
2094 * The middle button locks or unlocks a tile. (A locked tile
2095 * cannot be turned, and is visually marked as being locked.
2096 * This is a convenience for the player, so that once they are
2097 * sure which way round a tile goes, they can lock it and thus
2098 * avoid forgetting later on that they'd already done that one;
2099 * and the locking also prevents them turning the tile by
2100 * accident. If they change their mind, another middle click
2103 if (action == TOGGLE_LOCK) {
2105 sprintf(buf, "L%d,%d", tx, ty);
2107 } else if (action == ROTATE_LEFT || action == ROTATE_RIGHT ||
2108 action == ROTATE_180) {
2112 * The left and right buttons have no effect if clicked on a
2115 if (tile(state, tx, ty) & LOCKED)
2119 * Otherwise, turn the tile one way or the other. Left button
2120 * turns anticlockwise; right button turns clockwise.
2122 sprintf(buf, "%c%d,%d", (int)(action == ROTATE_LEFT ? 'A' :
2123 action == ROTATE_RIGHT ? 'C' : 'F'), tx, ty);
2125 } else if (action == JUMBLE) {
2127 * Jumble all unlocked tiles to random orientations.
2134 * Maximum string length assumes no int can be converted to
2135 * decimal and take more than 11 digits!
2137 maxlen = state->width * state->height * 25 + 3;
2139 ret = snewn(maxlen, char);
2143 for (jy = 0; jy < state->height; jy++) {
2144 for (jx = 0; jx < state->width; jx++) {
2145 if (!(tile(state, jx, jy) & LOCKED)) {
2146 int rot = random_upto(ui->rs, 4);
2148 p += sprintf(p, ";%c%d,%d", "AFC"[rot-1], jx, jy);
2154 assert(p - ret < maxlen);
2155 ret = sresize(ret, p - ret, char);
2158 } else if (action == MOVE_ORIGIN || action == MOVE_SOURCE ||
2159 action == MOVE_ORIGIN_AND_SOURCE || action == MOVE_CURSOR) {
2161 if (action == MOVE_ORIGIN || action == MOVE_ORIGIN_AND_SOURCE) {
2162 if (state->wrapping) {
2163 OFFSET(ui->org_x, ui->org_y, ui->org_x, ui->org_y, dir, state);
2164 } else return nullret; /* disallowed for non-wrapping grids */
2166 if (action == MOVE_SOURCE || action == MOVE_ORIGIN_AND_SOURCE) {
2167 OFFSET(ui->cx, ui->cy, ui->cx, ui->cy, dir, state);
2169 if (action == MOVE_CURSOR) {
2170 OFFSET(ui->cur_x, ui->cur_y, ui->cur_x, ui->cur_y, dir, state);
2171 ui->cur_visible = TRUE;
2179 static game_state *execute_move(game_state *from, char *move)
2182 int tx, ty, n, noanim, orig;
2184 ret = dup_game(from);
2186 if (move[0] == 'J' || move[0] == 'S') {
2188 ret->used_solve = TRUE;
2197 ret->last_rotate_dir = 0; /* suppress animation */
2198 ret->last_rotate_x = ret->last_rotate_y = 0;
2201 if ((move[0] == 'A' || move[0] == 'C' ||
2202 move[0] == 'F' || move[0] == 'L') &&
2203 sscanf(move+1, "%d,%d%n", &tx, &ty, &n) >= 2 &&
2204 tx >= 0 && tx < from->width && ty >= 0 && ty < from->height) {
2205 orig = tile(ret, tx, ty);
2206 if (move[0] == 'A') {
2207 tile(ret, tx, ty) = A(orig);
2209 ret->last_rotate_dir = +1;
2210 } else if (move[0] == 'F') {
2211 tile(ret, tx, ty) = F(orig);
2213 ret->last_rotate_dir = +2; /* + for sake of argument */
2214 } else if (move[0] == 'C') {
2215 tile(ret, tx, ty) = C(orig);
2217 ret->last_rotate_dir = -1;
2219 assert(move[0] == 'L');
2220 tile(ret, tx, ty) ^= LOCKED;
2224 if (*move == ';') move++;
2231 ret->last_rotate_x = tx;
2232 ret->last_rotate_y = ty;
2236 * Check whether the game has been completed.
2238 * For this purpose it doesn't matter where the source square
2239 * is, because we can start from anywhere and correctly
2240 * determine whether the game is completed.
2243 unsigned char *active = compute_active(ret, 0, 0);
2245 int complete = TRUE;
2247 for (x1 = 0; x1 < ret->width; x1++)
2248 for (y1 = 0; y1 < ret->height; y1++)
2249 if ((tile(ret, x1, y1) & 0xF) && !index(ret, active, x1, y1)) {
2251 goto break_label; /* break out of two loops at once */
2258 ret->completed = TRUE;
2265 /* ----------------------------------------------------------------------
2266 * Routines for drawing the game position on the screen.
2269 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2271 game_drawstate *ds = snew(game_drawstate);
2273 ds->started = FALSE;
2274 ds->width = state->width;
2275 ds->height = state->height;
2276 ds->org_x = ds->org_y = -1;
2277 ds->visible = snewn(state->width * state->height, unsigned char);
2278 ds->tilesize = 0; /* undecided yet */
2279 memset(ds->visible, 0xFF, state->width * state->height);
2284 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2290 static void game_compute_size(game_params *params, int tilesize,
2293 *x = WINDOW_OFFSET * 2 + tilesize * params->width + TILE_BORDER;
2294 *y = WINDOW_OFFSET * 2 + tilesize * params->height + TILE_BORDER;
2297 static void game_set_size(drawing *dr, game_drawstate *ds,
2298 game_params *params, int tilesize)
2300 ds->tilesize = tilesize;
2303 static float *game_colours(frontend *fe, int *ncolours)
2307 ret = snewn(NCOLOURS * 3, float);
2308 *ncolours = NCOLOURS;
2311 * Basic background colour is whatever the front end thinks is
2312 * a sensible default.
2314 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2319 ret[COL_WIRE * 3 + 0] = 0.0F;
2320 ret[COL_WIRE * 3 + 1] = 0.0F;
2321 ret[COL_WIRE * 3 + 2] = 0.0F;
2324 * Powered wires and powered endpoints are cyan.
2326 ret[COL_POWERED * 3 + 0] = 0.0F;
2327 ret[COL_POWERED * 3 + 1] = 1.0F;
2328 ret[COL_POWERED * 3 + 2] = 1.0F;
2333 ret[COL_BARRIER * 3 + 0] = 1.0F;
2334 ret[COL_BARRIER * 3 + 1] = 0.0F;
2335 ret[COL_BARRIER * 3 + 2] = 0.0F;
2338 * Unpowered endpoints are blue.
2340 ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2341 ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2342 ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2345 * Tile borders are a darker grey than the background.
2347 ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2348 ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2349 ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2352 * Locked tiles are a grey in between those two.
2354 ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2355 ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2356 ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2361 static void draw_thick_line(drawing *dr, int x1, int y1, int x2, int y2,
2364 draw_line(dr, x1-1, y1, x2-1, y2, COL_WIRE);
2365 draw_line(dr, x1+1, y1, x2+1, y2, COL_WIRE);
2366 draw_line(dr, x1, y1-1, x2, y2-1, COL_WIRE);
2367 draw_line(dr, x1, y1+1, x2, y2+1, COL_WIRE);
2368 draw_line(dr, x1, y1, x2, y2, colour);
2371 static void draw_rect_coords(drawing *dr, int x1, int y1, int x2, int y2,
2374 int mx = (x1 < x2 ? x1 : x2);
2375 int my = (y1 < y2 ? y1 : y2);
2376 int dx = (x2 + x1 - 2*mx + 1);
2377 int dy = (y2 + y1 - 2*my + 1);
2379 draw_rect(dr, mx, my, dx, dy, colour);
2383 * draw_barrier_corner() and draw_barrier() are passed physical coords
2385 static void draw_barrier_corner(drawing *dr, game_drawstate *ds,
2386 int x, int y, int dx, int dy, int phase)
2388 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2389 int by = WINDOW_OFFSET + TILE_SIZE * y;
2392 x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2393 y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2396 draw_rect_coords(dr, bx+x1+dx, by+y1,
2397 bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
2399 draw_rect_coords(dr, bx+x1, by+y1+dy,
2400 bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
2403 draw_rect_coords(dr, bx+x1, by+y1,
2404 bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
2409 static void draw_barrier(drawing *dr, game_drawstate *ds,
2410 int x, int y, int dir, int phase)
2412 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2413 int by = WINDOW_OFFSET + TILE_SIZE * y;
2416 x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
2417 y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
2418 w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2419 h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2422 draw_rect(dr, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
2424 draw_rect(dr, bx+x1, by+y1, w, h, COL_BARRIER);
2429 * draw_tile() is passed physical coordinates
2431 static void draw_tile(drawing *dr, game_state *state, game_drawstate *ds,
2432 int x, int y, int tile, int src, float angle, int cursor)
2434 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2435 int by = WINDOW_OFFSET + TILE_SIZE * y;
2437 float cx, cy, ex, ey, tx, ty;
2438 int dir, col, phase;
2441 * When we draw a single tile, we must draw everything up to
2442 * and including the borders around the tile. This means that
2443 * if the neighbouring tiles have connections to those borders,
2444 * we must draw those connections on the borders themselves.
2447 clip(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2450 * So. First blank the tile out completely: draw a big
2451 * rectangle in border colour, and a smaller rectangle in
2452 * background colour to fill it in.
2454 draw_rect(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
2456 draw_rect(dr, bx+TILE_BORDER, by+TILE_BORDER,
2457 TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
2458 tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
2461 * Draw an inset outline rectangle as a cursor, in whichever of
2462 * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
2466 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2467 bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2468 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2469 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2470 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2471 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2472 draw_line(dr, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2473 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2474 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2475 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2476 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2477 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2481 * Set up the rotation matrix.
2483 matrix[0] = (float)cos(angle * PI / 180.0);
2484 matrix[1] = (float)-sin(angle * PI / 180.0);
2485 matrix[2] = (float)sin(angle * PI / 180.0);
2486 matrix[3] = (float)cos(angle * PI / 180.0);
2491 cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
2492 col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
2493 for (dir = 1; dir < 0x10; dir <<= 1) {
2495 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2496 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2497 MATMUL(tx, ty, matrix, ex, ey);
2498 draw_thick_line(dr, bx+(int)cx, by+(int)cy,
2499 bx+(int)(cx+tx), by+(int)(cy+ty),
2503 for (dir = 1; dir < 0x10; dir <<= 1) {
2505 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2506 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2507 MATMUL(tx, ty, matrix, ex, ey);
2508 draw_line(dr, bx+(int)cx, by+(int)cy,
2509 bx+(int)(cx+tx), by+(int)(cy+ty), col);
2514 * Draw the box in the middle. We do this in blue if the tile
2515 * is an unpowered endpoint, in cyan if the tile is a powered
2516 * endpoint, in black if the tile is the centrepiece, and
2517 * otherwise not at all.
2522 else if (COUNT(tile) == 1) {
2523 col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
2528 points[0] = +1; points[1] = +1;
2529 points[2] = +1; points[3] = -1;
2530 points[4] = -1; points[5] = -1;
2531 points[6] = -1; points[7] = +1;
2533 for (i = 0; i < 8; i += 2) {
2534 ex = (TILE_SIZE * 0.24F) * points[i];
2535 ey = (TILE_SIZE * 0.24F) * points[i+1];
2536 MATMUL(tx, ty, matrix, ex, ey);
2537 points[i] = bx+(int)(cx+tx);
2538 points[i+1] = by+(int)(cy+ty);
2541 draw_polygon(dr, points, 4, col, COL_WIRE);
2545 * Draw the points on the border if other tiles are connected
2548 for (dir = 1; dir < 0x10; dir <<= 1) {
2549 int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
2557 if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
2560 if (!(tile(state, GX(ox), GY(oy)) & F(dir)))
2563 px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
2564 py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
2565 lx = dx * (TILE_BORDER-1);
2566 ly = dy * (TILE_BORDER-1);
2570 if (angle == 0.0 && (tile & dir)) {
2572 * If we are fully connected to the other tile, we must
2573 * draw right across the tile border. (We can use our
2574 * own ACTIVE state to determine what colour to do this
2575 * in: if we are fully connected to the other tile then
2576 * the two ACTIVE states will be the same.)
2578 draw_rect_coords(dr, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
2579 draw_rect_coords(dr, px, py, px+lx, py+ly,
2580 (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
2583 * The other tile extends into our border, but isn't
2584 * actually connected to us. Just draw a single black
2587 draw_rect_coords(dr, px, py, px, py, COL_WIRE);
2592 * Draw barrier corners, and then barriers.
2594 for (phase = 0; phase < 2; phase++) {
2595 for (dir = 1; dir < 0x10; dir <<= 1) {
2596 int x1, y1, corner = FALSE;
2598 * If at least one barrier terminates at the corner
2599 * between dir and A(dir), draw a barrier corner.
2601 if (barrier(state, GX(x), GY(y)) & (dir | A(dir))) {
2605 * Only count barriers terminating at this corner
2606 * if they're physically next to the corner. (That
2607 * is, if they've wrapped round from the far side
2608 * of the screen, they don't count.)
2612 if (x1 >= 0 && x1 < state->width &&
2613 y1 >= 0 && y1 < state->height &&
2614 (barrier(state, GX(x1), GY(y1)) & A(dir))) {
2619 if (x1 >= 0 && x1 < state->width &&
2620 y1 >= 0 && y1 < state->height &&
2621 (barrier(state, GX(x1), GY(y1)) & dir))
2628 * At least one barrier terminates here. Draw a
2631 draw_barrier_corner(dr, ds, x, y,
2632 X(dir)+X(A(dir)), Y(dir)+Y(A(dir)),
2637 for (dir = 1; dir < 0x10; dir <<= 1)
2638 if (barrier(state, GX(x), GY(y)) & dir)
2639 draw_barrier(dr, ds, x, y, dir, phase);
2644 draw_update(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2647 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2648 game_state *state, int dir, game_ui *ui, float t, float ft)
2650 int x, y, tx, ty, frame, last_rotate_dir, moved_origin = FALSE;
2651 unsigned char *active;
2655 * Clear the screen, and draw the exterior barrier lines, if
2656 * this is our first call or if the origin has changed.
2658 if (!ds->started || ui->org_x != ds->org_x || ui->org_y != ds->org_y) {
2664 WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
2665 WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
2668 ds->org_x = ui->org_x;
2669 ds->org_y = ui->org_y;
2670 moved_origin = TRUE;
2672 draw_update(dr, 0, 0,
2673 WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
2674 WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
2676 for (phase = 0; phase < 2; phase++) {
2678 for (x = 0; x < ds->width; x++) {
2679 if (x+1 < ds->width) {
2680 if (barrier(state, GX(x), GY(0)) & R)
2681 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
2682 if (barrier(state, GX(x), GY(ds->height-1)) & R)
2683 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
2685 if (barrier(state, GX(x), GY(0)) & U) {
2686 draw_barrier_corner(dr, ds, x, -1, -1, +1, phase);
2687 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
2688 draw_barrier(dr, ds, x, -1, D, phase);
2690 if (barrier(state, GX(x), GY(ds->height-1)) & D) {
2691 draw_barrier_corner(dr, ds, x, ds->height, -1, -1, phase);
2692 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
2693 draw_barrier(dr, ds, x, ds->height, U, phase);
2697 for (y = 0; y < ds->height; y++) {
2698 if (y+1 < ds->height) {
2699 if (barrier(state, GX(0), GY(y)) & D)
2700 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
2701 if (barrier(state, GX(ds->width-1), GY(y)) & D)
2702 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
2704 if (barrier(state, GX(0), GY(y)) & L) {
2705 draw_barrier_corner(dr, ds, -1, y, +1, -1, phase);
2706 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
2707 draw_barrier(dr, ds, -1, y, R, phase);
2709 if (barrier(state, GX(ds->width-1), GY(y)) & R) {
2710 draw_barrier_corner(dr, ds, ds->width, y, -1, -1, phase);
2711 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
2712 draw_barrier(dr, ds, ds->width, y, L, phase);
2719 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2720 state->last_rotate_dir;
2721 if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2723 * We're animating a single tile rotation. Find the turning
2726 tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2727 ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2728 angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2735 * We're animating a completion flash. Find which frame
2738 frame = (int)(ft / FLASH_FRAME);
2742 * Draw any tile which differs from the way it was last drawn.
2744 active = compute_active(state, ui->cx, ui->cy);
2746 for (x = 0; x < ds->width; x++)
2747 for (y = 0; y < ds->height; y++) {
2748 unsigned char c = tile(state, GX(x), GY(y)) |
2749 index(state, active, GX(x), GY(y));
2750 int is_src = GX(x) == ui->cx && GY(y) == ui->cy;
2751 int is_anim = GX(x) == tx && GY(y) == ty;
2752 int is_cursor = ui->cur_visible &&
2753 GX(x) == ui->cur_x && GY(y) == ui->cur_y;
2756 * In a completion flash, we adjust the LOCKED bit
2757 * depending on our distance from the centre point and
2761 int rcx = RX(ui->cx), rcy = RY(ui->cy);
2762 int xdist, ydist, dist;
2763 xdist = (x < rcx ? rcx - x : x - rcx);
2764 ydist = (y < rcy ? rcy - y : y - rcy);
2765 dist = (xdist > ydist ? xdist : ydist);
2767 if (frame >= dist && frame < dist+4) {
2768 int lock = (frame - dist) & 1;
2769 lock = lock ? LOCKED : 0;
2770 c = (c &~ LOCKED) | lock;
2775 index(state, ds->visible, x, y) != c ||
2776 index(state, ds->visible, x, y) == 0xFF ||
2777 is_src || is_anim || is_cursor) {
2778 draw_tile(dr, state, ds, x, y, c,
2779 is_src, (is_anim ? angle : 0.0F), is_cursor);
2780 if (is_src || is_anim || is_cursor)
2781 index(state, ds->visible, x, y) = 0xFF;
2783 index(state, ds->visible, x, y) = c;
2788 * Update the status bar.
2791 char statusbuf[256];
2794 n = state->width * state->height;
2795 for (i = a = n2 = 0; i < n; i++) {
2798 if (state->tiles[i] & 0xF)
2802 sprintf(statusbuf, "%sActive: %d/%d",
2803 (state->used_solve ? "Auto-solved. " :
2804 state->completed ? "COMPLETED! " : ""), a, n2);
2806 status_bar(dr, statusbuf);
2812 static float game_anim_length(game_state *oldstate,
2813 game_state *newstate, int dir, game_ui *ui)
2815 int last_rotate_dir;
2818 * Don't animate if last_rotate_dir is zero.
2820 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2821 newstate->last_rotate_dir;
2822 if (last_rotate_dir)
2828 static float game_flash_length(game_state *oldstate,
2829 game_state *newstate, int dir, game_ui *ui)
2832 * If the game has just been completed, we display a completion
2835 if (!oldstate->completed && newstate->completed &&
2836 !oldstate->used_solve && !newstate->used_solve) {
2838 if (size < newstate->width)
2839 size = newstate->width;
2840 if (size < newstate->height)
2841 size = newstate->height;
2842 return FLASH_FRAME * (size+4);
2848 static int game_timing_state(game_state *state, game_ui *ui)
2853 static void game_print_size(game_params *params, float *x, float *y)
2858 * I'll use 8mm squares by default.
2860 game_compute_size(params, 800, &pw, &ph);
2865 static void draw_diagram(drawing *dr, game_drawstate *ds, int x, int y,
2866 int topleft, int v, int drawlines, int ink)
2868 int tx, ty, cx, cy, r, br, k, thick;
2870 tx = WINDOW_OFFSET + TILE_SIZE * x;
2871 ty = WINDOW_OFFSET + TILE_SIZE * y;
2874 * Find our centre point.
2877 cx = tx + (v & L ? TILE_SIZE / 4 : TILE_SIZE / 6);
2878 cy = ty + (v & U ? TILE_SIZE / 4 : TILE_SIZE / 6);
2880 br = TILE_SIZE / 32;
2882 cx = tx + TILE_SIZE / 2;
2883 cy = ty + TILE_SIZE / 2;
2890 * Draw the square block if we have an endpoint.
2892 if (v == 1 || v == 2 || v == 4 || v == 8)
2893 draw_rect(dr, cx - br, cy - br, br*2, br*2, ink);
2896 * Draw each radial line.
2899 for (k = 1; k < 16; k *= 2)
2901 int x1 = min(cx, cx + (r-thick) * X(k));
2902 int x2 = max(cx, cx + (r-thick) * X(k));
2903 int y1 = min(cy, cy + (r-thick) * Y(k));
2904 int y2 = max(cy, cy + (r-thick) * Y(k));
2905 draw_rect(dr, x1 - thick, y1 - thick,
2906 (x2 - x1) + 2*thick, (y2 - y1) + 2*thick, ink);
2911 static void game_print(drawing *dr, game_state *state, int tilesize)
2913 int w = state->width, h = state->height;
2914 int ink = print_mono_colour(dr, 0);
2917 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2918 game_drawstate ads, *ds = &ads;
2919 game_set_size(dr, ds, NULL, tilesize);
2924 print_line_width(dr, TILE_SIZE / (state->wrapping ? 128 : 12));
2925 draw_rect_outline(dr, WINDOW_OFFSET, WINDOW_OFFSET,
2926 TILE_SIZE * w, TILE_SIZE * h, ink);
2931 print_line_width(dr, TILE_SIZE / 128);
2932 for (x = 1; x < w; x++)
2933 draw_line(dr, WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET,
2934 WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET + TILE_SIZE * h,
2936 for (y = 1; y < h; y++)
2937 draw_line(dr, WINDOW_OFFSET, WINDOW_OFFSET + TILE_SIZE * y,
2938 WINDOW_OFFSET + TILE_SIZE * w, WINDOW_OFFSET + TILE_SIZE * y,
2944 for (y = 0; y <= h; y++)
2945 for (x = 0; x <= w; x++) {
2946 int b = barrier(state, x % w, y % h);
2947 if (x < w && (b & U))
2948 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
2949 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
2950 TILE_SIZE + TILE_SIZE/24 * 2, TILE_SIZE/24 * 2, ink);
2951 if (y < h && (b & L))
2952 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
2953 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
2954 TILE_SIZE/24 * 2, TILE_SIZE + TILE_SIZE/24 * 2, ink);
2960 for (y = 0; y < h; y++)
2961 for (x = 0; x < w; x++) {
2962 int vx, v = tile(state, x, y);
2963 int locked = v & LOCKED;
2968 * Rotate into a standard orientation for the top left
2972 while (vx != 0 && vx != 15 && vx != 1 && vx != 9 && vx != 13 &&
2977 * Draw the top left corner diagram.
2979 draw_diagram(dr, ds, x, y, TRUE, vx, TRUE, ink);
2982 * Draw the real solution diagram, if we're doing so.
2984 draw_diagram(dr, ds, x, y, FALSE, v, locked, ink);
2992 const struct game thegame = {
2993 "Net", "games.net", "net",
3000 TRUE, game_configure, custom_params,
3008 FALSE, game_text_format,
3016 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3019 game_free_drawstate,
3023 TRUE, FALSE, game_print_size, game_print,
3024 TRUE, /* wants_statusbar */
3025 FALSE, game_timing_state,