Another thing to watch out for when adding new puzzles.
[sgt/puzzles] / net.c
CommitLineData
720a8fb7 1/*
2 * net.c: Net game.
3 */
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <assert.h>
b0e26073 9#include <ctype.h>
2ef96bd6 10#include <math.h>
720a8fb7 11
12#include "puzzles.h"
13#include "tree234.h"
14
2ef96bd6 15#define MATMUL(xr,yr,m,x,y) do { \
16 float rx, ry, xx = (x), yy = (y), *mat = (m); \
17 rx = mat[0] * xx + mat[2] * yy; \
18 ry = mat[1] * xx + mat[3] * yy; \
19 (xr) = rx; (yr) = ry; \
20} while (0)
21
22/* Direction and other bitfields */
720a8fb7 23#define R 0x01
24#define U 0x02
25#define L 0x04
26#define D 0x08
27#define LOCKED 0x10
2ef96bd6 28#define ACTIVE 0x20
720a8fb7 29
30/* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
31#define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
32#define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
33#define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
34#define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
35 ((n)&3) == 1 ? A(x) : \
36 ((n)&3) == 2 ? F(x) : C(x) )
37
38/* X and Y displacements */
39#define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
40#define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
41
42/* Bit count */
43#define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
44 (((x) & 0x02) >> 1) + ((x) & 0x01) )
45
1e3e152d 46#define PREFERRED_TILE_SIZE 32
47#define TILE_SIZE (ds->tilesize)
720a8fb7 48#define TILE_BORDER 1
cb0c7d4a 49#ifdef SMALL_SCREEN
50#define WINDOW_OFFSET 4
51#else
720a8fb7 52#define WINDOW_OFFSET 16
cb0c7d4a 53#endif
720a8fb7 54
8c1fd974 55#define ROTATE_TIME 0.13F
56#define FLASH_FRAME 0.07F
2ef96bd6 57
f0ee053c 58/* Transform physical coords to game coords using game_drawstate ds */
59#define GX(x) (((x) + ds->org_x) % ds->width)
60#define GY(y) (((y) + ds->org_y) % ds->height)
61/* ...and game coords to physical coords */
62#define RX(x) (((x) + ds->width - ds->org_x) % ds->width)
63#define RY(y) (((y) + ds->height - ds->org_y) % ds->height)
64
2ef96bd6 65enum {
66 COL_BACKGROUND,
67 COL_LOCKED,
68 COL_BORDER,
69 COL_WIRE,
70 COL_ENDPOINT,
71 COL_POWERED,
72 COL_BARRIER,
73 NCOLOURS
74};
75
720a8fb7 76struct game_params {
77 int width;
78 int height;
79 int wrapping;
c0edd11f 80 int unique;
720a8fb7 81 float barrier_probability;
82};
83
84struct game_state {
f0ee053c 85 int width, height, wrapping, completed;
1185e3c5 86 int last_rotate_x, last_rotate_y, last_rotate_dir;
a440f184 87 int used_solve;
720a8fb7 88 unsigned char *tiles;
89 unsigned char *barriers;
90};
91
c0edd11f 92#define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
93 ( (x2) = ((x1) + width + X((dir))) % width, \
94 (y2) = ((y1) + height + Y((dir))) % height)
95
720a8fb7 96#define OFFSET(x2,y2,x1,y1,dir,state) \
c0edd11f 97 OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
720a8fb7 98
99#define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
100#define tile(state, x, y) index(state, (state)->tiles, x, y)
101#define barrier(state, x, y) index(state, (state)->barriers, x, y)
102
103struct xyd {
104 int x, y, direction;
105};
106
c0edd11f 107static int xyd_cmp(const void *av, const void *bv) {
108 const struct xyd *a = (const struct xyd *)av;
109 const struct xyd *b = (const struct xyd *)bv;
720a8fb7 110 if (a->x < b->x)
111 return -1;
112 if (a->x > b->x)
113 return +1;
114 if (a->y < b->y)
115 return -1;
116 if (a->y > b->y)
117 return +1;
118 if (a->direction < b->direction)
119 return -1;
120 if (a->direction > b->direction)
121 return +1;
122 return 0;
23e8c9fd 123}
720a8fb7 124
c0edd11f 125static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
126
720a8fb7 127static struct xyd *new_xyd(int x, int y, int direction)
128{
129 struct xyd *xyd = snew(struct xyd);
130 xyd->x = x;
131 xyd->y = y;
132 xyd->direction = direction;
133 return xyd;
134}
135
136/* ----------------------------------------------------------------------
7f77ea24 137 * Manage game parameters.
138 */
be8d5aa1 139static game_params *default_params(void)
7f77ea24 140{
141 game_params *ret = snew(game_params);
142
eb2ad6f1 143 ret->width = 5;
144 ret->height = 5;
145 ret->wrapping = FALSE;
c0edd11f 146 ret->unique = TRUE;
eb2ad6f1 147 ret->barrier_probability = 0.0;
7f77ea24 148
149 return ret;
150}
151
ab53eb64 152static const struct game_params net_presets[] = {
153 {5, 5, FALSE, TRUE, 0.0},
154 {7, 7, FALSE, TRUE, 0.0},
155 {9, 9, FALSE, TRUE, 0.0},
156 {11, 11, FALSE, TRUE, 0.0},
cb0c7d4a 157#ifndef SMALL_SCREEN
ab53eb64 158 {13, 11, FALSE, TRUE, 0.0},
cb0c7d4a 159#endif
ab53eb64 160 {5, 5, TRUE, TRUE, 0.0},
161 {7, 7, TRUE, TRUE, 0.0},
162 {9, 9, TRUE, TRUE, 0.0},
163 {11, 11, TRUE, TRUE, 0.0},
cb0c7d4a 164#ifndef SMALL_SCREEN
ab53eb64 165 {13, 11, TRUE, TRUE, 0.0},
cb0c7d4a 166#endif
ab53eb64 167};
168
be8d5aa1 169static int game_fetch_preset(int i, char **name, game_params **params)
eb2ad6f1 170{
171 game_params *ret;
172 char str[80];
ab53eb64 173
174 if (i < 0 || i >= lenof(net_presets))
eb2ad6f1 175 return FALSE;
176
177 ret = snew(game_params);
ab53eb64 178 *ret = net_presets[i];
eb2ad6f1 179
180 sprintf(str, "%dx%d%s", ret->width, ret->height,
181 ret->wrapping ? " wrapping" : "");
182
183 *name = dupstr(str);
184 *params = ret;
185 return TRUE;
186}
187
be8d5aa1 188static void free_params(game_params *params)
7f77ea24 189{
190 sfree(params);
191}
192
be8d5aa1 193static game_params *dup_params(game_params *params)
eb2ad6f1 194{
195 game_params *ret = snew(game_params);
196 *ret = *params; /* structure copy */
197 return ret;
198}
199
1185e3c5 200static void decode_params(game_params *ret, char const *string)
b0e26073 201{
b0e26073 202 char const *p = string;
203
204 ret->width = atoi(p);
40fde884 205 while (*p && isdigit((unsigned char)*p)) p++;
b0e26073 206 if (*p == 'x') {
207 p++;
208 ret->height = atoi(p);
40fde884 209 while (*p && isdigit((unsigned char)*p)) p++;
b0e26073 210 } else {
211 ret->height = ret->width;
212 }
c0edd11f 213
214 while (*p) {
215 if (*p == 'w') {
216 p++;
217 ret->wrapping = TRUE;
218 } else if (*p == 'b') {
219 p++;
220 ret->barrier_probability = atof(p);
40fde884 221 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
c0edd11f 222 } else if (*p == 'a') {
223 p++;
224 ret->unique = FALSE;
40fde884 225 } else
226 p++; /* skip any other gunk */
c0edd11f 227 }
b0e26073 228}
229
1185e3c5 230static char *encode_params(game_params *params, int full)
b0e26073 231{
232 char ret[400];
233 int len;
234
235 len = sprintf(ret, "%dx%d", params->width, params->height);
236 if (params->wrapping)
237 ret[len++] = 'w';
1185e3c5 238 if (full && params->barrier_probability)
b0e26073 239 len += sprintf(ret+len, "b%g", params->barrier_probability);
40fde884 240 if (full && !params->unique)
c0edd11f 241 ret[len++] = 'a';
b0e26073 242 assert(len < lenof(ret));
243 ret[len] = '\0';
244
245 return dupstr(ret);
246}
247
be8d5aa1 248static config_item *game_configure(game_params *params)
c8230524 249{
250 config_item *ret;
251 char buf[80];
252
c0edd11f 253 ret = snewn(6, config_item);
c8230524 254
255 ret[0].name = "Width";
95709966 256 ret[0].type = C_STRING;
c8230524 257 sprintf(buf, "%d", params->width);
258 ret[0].sval = dupstr(buf);
259 ret[0].ival = 0;
260
261 ret[1].name = "Height";
95709966 262 ret[1].type = C_STRING;
c8230524 263 sprintf(buf, "%d", params->height);
264 ret[1].sval = dupstr(buf);
265 ret[1].ival = 0;
266
267 ret[2].name = "Walls wrap around";
95709966 268 ret[2].type = C_BOOLEAN;
c8230524 269 ret[2].sval = NULL;
270 ret[2].ival = params->wrapping;
271
272 ret[3].name = "Barrier probability";
95709966 273 ret[3].type = C_STRING;
c8230524 274 sprintf(buf, "%g", params->barrier_probability);
275 ret[3].sval = dupstr(buf);
276 ret[3].ival = 0;
277
c0edd11f 278 ret[4].name = "Ensure unique solution";
279 ret[4].type = C_BOOLEAN;
c8230524 280 ret[4].sval = NULL;
c0edd11f 281 ret[4].ival = params->unique;
282
283 ret[5].name = NULL;
284 ret[5].type = C_END;
285 ret[5].sval = NULL;
286 ret[5].ival = 0;
c8230524 287
288 return ret;
289}
290
be8d5aa1 291static game_params *custom_params(config_item *cfg)
c8230524 292{
293 game_params *ret = snew(game_params);
294
295 ret->width = atoi(cfg[0].sval);
296 ret->height = atoi(cfg[1].sval);
297 ret->wrapping = cfg[2].ival;
95709966 298 ret->barrier_probability = (float)atof(cfg[3].sval);
c0edd11f 299 ret->unique = cfg[4].ival;
c8230524 300
301 return ret;
302}
303
3ff276f2 304static char *validate_params(game_params *params, int full)
c8230524 305{
ab53eb64 306 if (params->width <= 0 || params->height <= 0)
c8230524 307 return "Width and height must both be greater than zero";
c8230524 308 if (params->width <= 1 && params->height <= 1)
309 return "At least one of width and height must be greater than one";
310 if (params->barrier_probability < 0)
311 return "Barrier probability may not be negative";
312 if (params->barrier_probability > 1)
313 return "Barrier probability may not be greater than 1";
e7c352f5 314
315 /*
316 * Specifying either grid dimension as 2 in a wrapping puzzle
317 * makes it actually impossible to ensure a unique puzzle
318 * solution.
319 *
320 * Proof:
321 *
322 * Without loss of generality, let us assume the puzzle _width_
323 * is 2, so we can conveniently discuss rows without having to
324 * say `rows/columns' all the time. (The height may be 2 as
325 * well, but that doesn't matter.)
326 *
327 * In each row, there are two edges between tiles: the inner
328 * edge (running down the centre of the grid) and the outer
329 * edge (the identified left and right edges of the grid).
330 *
331 * Lemma: In any valid 2xn puzzle there must be at least one
332 * row in which _exactly one_ of the inner edge and outer edge
333 * is connected.
334 *
335 * Proof: No row can have _both_ inner and outer edges
336 * connected, because this would yield a loop. So the only
337 * other way to falsify the lemma is for every row to have
338 * _neither_ the inner nor outer edge connected. But this
339 * means there is no connection at all between the left and
340 * right columns of the puzzle, so there are two disjoint
341 * subgraphs, which is also disallowed. []
342 *
343 * Given such a row, it is always possible to make the
344 * disconnected edge connected and the connected edge
345 * disconnected without changing the state of any other edge.
346 * (This is easily seen by case analysis on the various tiles:
347 * left-pointing and right-pointing endpoints can be exchanged,
348 * likewise T-pieces, and a corner piece can select its
349 * horizontal connectivity independently of its vertical.) This
350 * yields a distinct valid solution.
351 *
352 * Thus, for _every_ row in which exactly one of the inner and
353 * outer edge is connected, there are two valid states for that
354 * row, and hence the total number of solutions of the puzzle
355 * is at least 2^(number of such rows), and in particular is at
356 * least 2 since there must be at least one such row. []
357 */
3ff276f2 358 if (full && params->unique && params->wrapping &&
e7c352f5 359 (params->width == 2 || params->height == 2))
360 return "No wrapping puzzle with a width or height of 2 can have"
361 " a unique solution";
362
c8230524 363 return NULL;
364}
365
7f77ea24 366/* ----------------------------------------------------------------------
c0edd11f 367 * Solver used to assure solution uniqueness during generation.
368 */
369
370/*
371 * Test cases I used while debugging all this were
372 *
373 * ./net --generate 1 13x11w#12300
374 * which expands under the non-unique grid generation rules to
375 * 13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
376 * and has two ambiguous areas.
377 *
378 * An even better one is
379 * 13x11w#507896411361192
380 * which expands to
381 * 13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
382 * and has an ambiguous area _and_ a situation where loop avoidance
383 * is a necessary deductive technique.
384 *
385 * Then there's
386 * 48x25w#820543338195187
387 * becoming
388 * 48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
389 * which has a spot (far right) where slightly more complex loop
390 * avoidance is required.
391 */
392
c0edd11f 393struct todo {
394 unsigned char *marked;
395 int *buffer;
396 int buflen;
397 int head, tail;
398};
399
400static struct todo *todo_new(int maxsize)
401{
402 struct todo *todo = snew(struct todo);
403 todo->marked = snewn(maxsize, unsigned char);
404 memset(todo->marked, 0, maxsize);
405 todo->buflen = maxsize + 1;
406 todo->buffer = snewn(todo->buflen, int);
407 todo->head = todo->tail = 0;
408 return todo;
409}
410
411static void todo_free(struct todo *todo)
412{
413 sfree(todo->marked);
414 sfree(todo->buffer);
415 sfree(todo);
416}
417
418static void todo_add(struct todo *todo, int index)
419{
420 if (todo->marked[index])
421 return; /* already on the list */
422 todo->marked[index] = TRUE;
423 todo->buffer[todo->tail++] = index;
424 if (todo->tail == todo->buflen)
425 todo->tail = 0;
426}
427
428static int todo_get(struct todo *todo) {
429 int ret;
430
431 if (todo->head == todo->tail)
432 return -1; /* list is empty */
433 ret = todo->buffer[todo->head++];
434 if (todo->head == todo->buflen)
435 todo->head = 0;
436 todo->marked[ret] = FALSE;
437
438 return ret;
439}
440
84942c65 441static int net_solver(int w, int h, unsigned char *tiles,
442 unsigned char *barriers, int wrapping)
c0edd11f 443{
444 unsigned char *tilestate;
445 unsigned char *edgestate;
446 int *deadends;
447 int *equivalence;
448 struct todo *todo;
449 int i, j, x, y;
450 int area;
451 int done_something;
452
453 /*
454 * Set up the solver's data structures.
455 */
456
457 /*
458 * tilestate stores the possible orientations of each tile.
459 * There are up to four of these, so we'll index the array in
460 * fours. tilestate[(y * w + x) * 4] and its three successive
461 * members give the possible orientations, clearing to 255 from
462 * the end as things are ruled out.
463 *
464 * In this loop we also count up the area of the grid (which is
465 * not _necessarily_ equal to w*h, because there might be one
466 * or more blank squares present. This will never happen in a
467 * grid generated _by_ this program, but it's worth keeping the
468 * solver as general as possible.)
469 */
470 tilestate = snewn(w * h * 4, unsigned char);
471 area = 0;
472 for (i = 0; i < w*h; i++) {
473 tilestate[i * 4] = tiles[i] & 0xF;
474 for (j = 1; j < 4; j++) {
475 if (tilestate[i * 4 + j - 1] == 255 ||
476 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
477 tilestate[i * 4 + j] = 255;
478 else
479 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
480 }
481 if (tiles[i] != 0)
482 area++;
483 }
484
485 /*
486 * edgestate stores the known state of each edge. It is 0 for
487 * unknown, 1 for open (connected) and 2 for closed (not
488 * connected).
489 *
490 * In principle we need only worry about each edge once each,
491 * but in fact it's easier to track each edge twice so that we
492 * can reference it from either side conveniently. Also I'm
493 * going to allocate _five_ bytes per tile, rather than the
494 * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
495 * where d is 1,2,4,8 and they never overlap.
496 */
497 edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
498 memset(edgestate, 0, (w * h - 1) * 5 + 9);
499
500 /*
501 * deadends tracks which edges have dead ends on them. It is
502 * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
503 * tells you whether heading out of tile (x,y) in direction d
504 * can reach a limited amount of the grid. Values are area+1
505 * (no dead end known) or less than that (can reach _at most_
506 * this many other tiles by heading this way out of this tile).
507 */
508 deadends = snewn((w * h - 1) * 5 + 9, int);
509 for (i = 0; i < (w * h - 1) * 5 + 9; i++)
510 deadends[i] = area+1;
511
512 /*
513 * equivalence tracks which sets of tiles are known to be
514 * connected to one another, so we can avoid creating loops by
515 * linking together tiles which are already linked through
516 * another route.
517 *
518 * This is a disjoint set forest structure: equivalence[i]
519 * contains the index of another member of the equivalence
520 * class containing i, or contains i itself for precisely one
521 * member in each such class. To find a representative member
522 * of the equivalence class containing i, you keep replacing i
523 * with equivalence[i] until it stops changing; then you go
524 * _back_ along the same path and point everything on it
525 * directly at the representative member so as to speed up
526 * future searches. Then you test equivalence between tiles by
527 * finding the representative of each tile and seeing if
528 * they're the same; and you create new equivalence (merge
529 * classes) by finding the representative of each tile and
530 * setting equivalence[one]=the_other.
531 */
cd28b679 532 equivalence = snew_dsf(w * h);
c0edd11f 533
534 /*
535 * On a non-wrapping grid, we instantly know that all the edges
536 * round the edge are closed.
537 */
538 if (!wrapping) {
539 for (i = 0; i < w; i++) {
540 edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
541 }
542 for (i = 0; i < h; i++) {
543 edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
544 }
545 }
546
547 /*
84942c65 548 * If we have barriers available, we can mark those edges as
549 * closed too.
550 */
551 if (barriers) {
552 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
553 int d;
554 for (d = 1; d <= 8; d += d) {
555 if (barriers[y*w+x] & d) {
556 int x2, y2;
557 /*
558 * In principle the barrier list should already
559 * contain each barrier from each side, but
560 * let's not take chances with our internal
561 * consistency.
562 */
563 OFFSETWH(x2, y2, x, y, d, w, h);
564 edgestate[(y*w+x) * 5 + d] = 2;
565 edgestate[(y2*w+x2) * 5 + F(d)] = 2;
566 }
567 }
568 }
569 }
570
571 /*
c0edd11f 572 * Since most deductions made by this solver are local (the
573 * exception is loop avoidance, where joining two tiles
574 * together on one side of the grid can theoretically permit a
575 * fresh deduction on the other), we can address the scaling
576 * problem inherent in iterating repeatedly over the entire
577 * grid by instead working with a to-do list.
578 */
579 todo = todo_new(w * h);
580
581 /*
582 * Main deductive loop.
583 */
584 done_something = TRUE; /* prevent instant termination! */
585 while (1) {
586 int index;
587
588 /*
589 * Take a tile index off the todo list and process it.
590 */
591 index = todo_get(todo);
592 if (index == -1) {
593 /*
594 * If we have run out of immediate things to do, we
595 * have no choice but to scan the whole grid for
596 * longer-range things we've missed. Hence, I now add
597 * every square on the grid back on to the to-do list.
598 * I also set `done_something' to FALSE at this point;
599 * if we later come back here and find it still FALSE,
600 * we will know we've scanned the entire grid without
601 * finding anything new to do, and we can terminate.
602 */
603 if (!done_something)
604 break;
605 for (i = 0; i < w*h; i++)
606 todo_add(todo, i);
607 done_something = FALSE;
608
609 index = todo_get(todo);
610 }
611
612 y = index / w;
613 x = index % w;
614 {
615 int d, ourclass = dsf_canonify(equivalence, y*w+x);
616 int deadendmax[9];
617
618 deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
619
620 for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
621 int valid;
622 int nnondeadends, nondeadends[4], deadendtotal;
623 int nequiv, equiv[5];
624 int val = tilestate[(y*w+x) * 4 + i];
625
626 valid = TRUE;
627 nnondeadends = deadendtotal = 0;
628 equiv[0] = ourclass;
629 nequiv = 1;
630 for (d = 1; d <= 8; d += d) {
631 /*
632 * Immediately rule out this orientation if it
633 * conflicts with any known edge.
634 */
635 if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
636 (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
637 valid = FALSE;
638
639 if (val & d) {
640 /*
641 * Count up the dead-end statistics.
642 */
643 if (deadends[(y*w+x) * 5 + d] <= area) {
644 deadendtotal += deadends[(y*w+x) * 5 + d];
645 } else {
646 nondeadends[nnondeadends++] = d;
647 }
648
649 /*
650 * Ensure we aren't linking to any tiles,
651 * through edges not already known to be
652 * open, which create a loop.
653 */
654 if (edgestate[(y*w+x) * 5 + d] == 0) {
655 int c, k, x2, y2;
656
657 OFFSETWH(x2, y2, x, y, d, w, h);
658 c = dsf_canonify(equivalence, y2*w+x2);
659 for (k = 0; k < nequiv; k++)
660 if (c == equiv[k])
661 break;
662 if (k == nequiv)
663 equiv[nequiv++] = c;
664 else
665 valid = FALSE;
666 }
667 }
668 }
669
670 if (nnondeadends == 0) {
671 /*
672 * If this orientation links together dead-ends
673 * with a total area of less than the entire
674 * grid, it is invalid.
675 *
676 * (We add 1 to deadendtotal because of the
677 * tile itself, of course; one tile linking
678 * dead ends of size 2 and 3 forms a subnetwork
679 * with a total area of 6, not 5.)
680 */
9535138a 681 if (deadendtotal > 0 && deadendtotal+1 < area)
c0edd11f 682 valid = FALSE;
683 } else if (nnondeadends == 1) {
684 /*
685 * If this orientation links together one or
686 * more dead-ends with precisely one
687 * non-dead-end, then we may have to mark that
688 * non-dead-end as a dead end going the other
689 * way. However, it depends on whether all
690 * other orientations share the same property.
691 */
692 deadendtotal++;
693 if (deadendmax[nondeadends[0]] < deadendtotal)
694 deadendmax[nondeadends[0]] = deadendtotal;
695 } else {
696 /*
697 * If this orientation links together two or
698 * more non-dead-ends, then we can rule out the
699 * possibility of putting in new dead-end
700 * markings in those directions.
701 */
702 int k;
703 for (k = 0; k < nnondeadends; k++)
704 deadendmax[nondeadends[k]] = area+1;
705 }
706
707 if (valid)
708 tilestate[(y*w+x) * 4 + j++] = val;
709#ifdef SOLVER_DIAGNOSTICS
710 else
711 printf("ruling out orientation %x at %d,%d\n", val, x, y);
712#endif
713 }
714
715 assert(j > 0); /* we can't lose _all_ possibilities! */
716
717 if (j < i) {
c0edd11f 718 done_something = TRUE;
719
720 /*
721 * We have ruled out at least one tile orientation.
722 * Make sure the rest are blanked.
723 */
724 while (j < 4)
725 tilestate[(y*w+x) * 4 + j++] = 255;
3af1c093 726 }
c0edd11f 727
3af1c093 728 /*
729 * Now go through the tile orientations again and see
730 * if we've deduced anything new about any edges.
731 */
732 {
733 int a, o;
c0edd11f 734 a = 0xF; o = 0;
3af1c093 735
c0edd11f 736 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
737 a &= tilestate[(y*w+x) * 4 + i];
738 o |= tilestate[(y*w+x) * 4 + i];
739 }
740 for (d = 1; d <= 8; d += d)
741 if (edgestate[(y*w+x) * 5 + d] == 0) {
742 int x2, y2, d2;
743 OFFSETWH(x2, y2, x, y, d, w, h);
744 d2 = F(d);
745 if (a & d) {
746 /* This edge is open in all orientations. */
747#ifdef SOLVER_DIAGNOSTICS
748 printf("marking edge %d,%d:%d open\n", x, y, d);
749#endif
750 edgestate[(y*w+x) * 5 + d] = 1;
751 edgestate[(y2*w+x2) * 5 + d2] = 1;
752 dsf_merge(equivalence, y*w+x, y2*w+x2);
753 done_something = TRUE;
754 todo_add(todo, y2*w+x2);
755 } else if (!(o & d)) {
756 /* This edge is closed in all orientations. */
757#ifdef SOLVER_DIAGNOSTICS
758 printf("marking edge %d,%d:%d closed\n", x, y, d);
759#endif
760 edgestate[(y*w+x) * 5 + d] = 2;
761 edgestate[(y2*w+x2) * 5 + d2] = 2;
762 done_something = TRUE;
763 todo_add(todo, y2*w+x2);
764 }
765 }
766
767 }
768
769 /*
770 * Now check the dead-end markers and see if any of
771 * them has lowered from the real ones.
772 */
773 for (d = 1; d <= 8; d += d) {
774 int x2, y2, d2;
775 OFFSETWH(x2, y2, x, y, d, w, h);
776 d2 = F(d);
777 if (deadendmax[d] > 0 &&
778 deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
779#ifdef SOLVER_DIAGNOSTICS
780 printf("setting dead end value %d,%d:%d to %d\n",
781 x2, y2, d2, deadendmax[d]);
782#endif
783 deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
784 done_something = TRUE;
785 todo_add(todo, y2*w+x2);
786 }
787 }
788
789 }
790 }
791
792 /*
793 * Mark all completely determined tiles as locked.
794 */
795 j = TRUE;
796 for (i = 0; i < w*h; i++) {
797 if (tilestate[i * 4 + 1] == 255) {
798 assert(tilestate[i * 4 + 0] != 255);
799 tiles[i] = tilestate[i * 4] | LOCKED;
800 } else {
801 tiles[i] &= ~LOCKED;
802 j = FALSE;
803 }
804 }
805
806 /*
807 * Free up working space.
808 */
809 todo_free(todo);
810 sfree(tilestate);
811 sfree(edgestate);
812 sfree(deadends);
813 sfree(equivalence);
814
815 return j;
816}
817
818/* ----------------------------------------------------------------------
1185e3c5 819 * Randomly select a new game description.
720a8fb7 820 */
821
c0edd11f 822/*
823 * Function to randomly perturb an ambiguous section in a grid, to
824 * attempt to ensure unique solvability.
825 */
826static void perturb(int w, int h, unsigned char *tiles, int wrapping,
827 random_state *rs, int startx, int starty, int startd)
828{
829 struct xyd *perimeter, *perim2, *loop[2], looppos[2];
830 int nperim, perimsize, nloop[2], loopsize[2];
831 int x, y, d, i;
832
833 /*
834 * We know that the tile at (startx,starty) is part of an
835 * ambiguous section, and we also know that its neighbour in
836 * direction startd is fully specified. We begin by tracing all
837 * the way round the ambiguous area.
838 */
839 nperim = perimsize = 0;
840 perimeter = NULL;
841 x = startx;
842 y = starty;
843 d = startd;
844#ifdef PERTURB_DIAGNOSTICS
845 printf("perturb %d,%d:%d\n", x, y, d);
846#endif
847 do {
848 int x2, y2, d2;
849
850 if (nperim >= perimsize) {
851 perimsize = perimsize * 3 / 2 + 32;
852 perimeter = sresize(perimeter, perimsize, struct xyd);
853 }
854 perimeter[nperim].x = x;
855 perimeter[nperim].y = y;
856 perimeter[nperim].direction = d;
857 nperim++;
858#ifdef PERTURB_DIAGNOSTICS
859 printf("perimeter: %d,%d:%d\n", x, y, d);
860#endif
861
862 /*
863 * First, see if we can simply turn left from where we are
864 * and find another locked square.
865 */
866 d2 = A(d);
867 OFFSETWH(x2, y2, x, y, d2, w, h);
868 if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
869 (tiles[y2*w+x2] & LOCKED)) {
870 d = d2;
871 } else {
872 /*
873 * Failing that, step left into the new square and look
874 * in front of us.
875 */
876 x = x2;
877 y = y2;
878 OFFSETWH(x2, y2, x, y, d, w, h);
879 if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
880 !(tiles[y2*w+x2] & LOCKED)) {
881 /*
882 * And failing _that_, we're going to have to step
883 * forward into _that_ square and look right at the
884 * same locked square as we started with.
885 */
886 x = x2;
887 y = y2;
888 d = C(d);
889 }
890 }
891
892 } while (x != startx || y != starty || d != startd);
893
894 /*
895 * Our technique for perturbing this ambiguous area is to
896 * search round its edge for a join we can make: that is, an
897 * edge on the perimeter which is (a) not currently connected,
898 * and (b) connecting it would not yield a full cross on either
899 * side. Then we make that join, search round the network to
900 * find the loop thus constructed, and sever the loop at a
901 * randomly selected other point.
902 */
903 perim2 = snewn(nperim, struct xyd);
904 memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
905 /* Shuffle the perimeter, so as to search it without directional bias. */
e3edcacd 906 shuffle(perim2, nperim, sizeof(*perim2), rs);
c0edd11f 907 for (i = 0; i < nperim; i++) {
908 int x2, y2;
909
910 x = perim2[i].x;
911 y = perim2[i].y;
912 d = perim2[i].direction;
913
914 OFFSETWH(x2, y2, x, y, d, w, h);
915 if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
916 continue; /* can't link across non-wrapping border */
917 if (tiles[y*w+x] & d)
918 continue; /* already linked in this direction! */
919 if (((tiles[y*w+x] | d) & 15) == 15)
920 continue; /* can't turn this tile into a cross */
921 if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
922 continue; /* can't turn other tile into a cross */
923
924 /*
925 * We've found the point at which we're going to make a new
926 * link.
927 */
928#ifdef PERTURB_DIAGNOSTICS
929 printf("linking %d,%d:%d\n", x, y, d);
930#endif
931 tiles[y*w+x] |= d;
932 tiles[y2*w+x2] |= F(d);
933
934 break;
935 }
ab53eb64 936 sfree(perim2);
c0edd11f 937
938 if (i == nperim)
939 return; /* nothing we can do! */
940
941 /*
942 * Now we've constructed a new link, we need to find the entire
943 * loop of which it is a part.
944 *
945 * In principle, this involves doing a complete search round
946 * the network. However, I anticipate that in the vast majority
947 * of cases the loop will be quite small, so what I'm going to
948 * do is make _two_ searches round the network in parallel, one
949 * keeping its metaphorical hand on the left-hand wall while
950 * the other keeps its hand on the right. As soon as one of
951 * them gets back to its starting point, I abandon the other.
952 */
953 for (i = 0; i < 2; i++) {
954 loopsize[i] = nloop[i] = 0;
955 loop[i] = NULL;
956 looppos[i].x = x;
957 looppos[i].y = y;
958 looppos[i].direction = d;
959 }
960 while (1) {
961 for (i = 0; i < 2; i++) {
962 int x2, y2, j;
963
964 x = looppos[i].x;
965 y = looppos[i].y;
966 d = looppos[i].direction;
967
968 OFFSETWH(x2, y2, x, y, d, w, h);
969
970 /*
971 * Add this path segment to the loop, unless it exactly
972 * reverses the previous one on the loop in which case
973 * we take it away again.
974 */
975#ifdef PERTURB_DIAGNOSTICS
976 printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
977#endif
978 if (nloop[i] > 0 &&
979 loop[i][nloop[i]-1].x == x2 &&
980 loop[i][nloop[i]-1].y == y2 &&
981 loop[i][nloop[i]-1].direction == F(d)) {
982#ifdef PERTURB_DIAGNOSTICS
983 printf("removing path segment %d,%d:%d from loop[%d]\n",
984 x2, y2, F(d), i);
985#endif
986 nloop[i]--;
987 } else {
988 if (nloop[i] >= loopsize[i]) {
989 loopsize[i] = loopsize[i] * 3 / 2 + 32;
990 loop[i] = sresize(loop[i], loopsize[i], struct xyd);
991 }
992#ifdef PERTURB_DIAGNOSTICS
993 printf("adding path segment %d,%d:%d to loop[%d]\n",
994 x, y, d, i);
995#endif
996 loop[i][nloop[i]++] = looppos[i];
997 }
998
999#ifdef PERTURB_DIAGNOSTICS
1000 printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
1001#endif
1002 d = F(d);
1003 for (j = 0; j < 4; j++) {
1004 if (i == 0)
1005 d = A(d);
1006 else
1007 d = C(d);
1008#ifdef PERTURB_DIAGNOSTICS
1009 printf("trying dir %d\n", d);
1010#endif
1011 if (tiles[y2*w+x2] & d) {
1012 looppos[i].x = x2;
1013 looppos[i].y = y2;
1014 looppos[i].direction = d;
1015 break;
1016 }
1017 }
1018
1019 assert(j < 4);
1020 assert(nloop[i] > 0);
1021
1022 if (looppos[i].x == loop[i][0].x &&
1023 looppos[i].y == loop[i][0].y &&
1024 looppos[i].direction == loop[i][0].direction) {
1025#ifdef PERTURB_DIAGNOSTICS
1026 printf("loop %d finished tracking\n", i);
1027#endif
1028
1029 /*
1030 * Having found our loop, we now sever it at a
1031 * randomly chosen point - absolutely any will do -
1032 * which is not the one we joined it at to begin
1033 * with. Conveniently, the one we joined it at is
1034 * loop[i][0], so we just avoid that one.
1035 */
1036 j = random_upto(rs, nloop[i]-1) + 1;
1037 x = loop[i][j].x;
1038 y = loop[i][j].y;
1039 d = loop[i][j].direction;
1040 OFFSETWH(x2, y2, x, y, d, w, h);
1041 tiles[y*w+x] &= ~d;
1042 tiles[y2*w+x2] &= ~F(d);
1043
1044 break;
1045 }
1046 }
1047 if (i < 2)
1048 break;
1049 }
1050 sfree(loop[0]);
1051 sfree(loop[1]);
1052
1053 /*
1054 * Finally, we must mark the entire disputed section as locked,
1055 * to prevent the perturb function being called on it multiple
1056 * times.
1057 *
1058 * To do this, we _sort_ the perimeter of the area. The
1059 * existing xyd_cmp function will arrange things into columns
1060 * for us, in such a way that each column has the edges in
1061 * vertical order. Then we can work down each column and fill
1062 * in all the squares between an up edge and a down edge.
1063 */
1064 qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1065 x = y = -1;
1066 for (i = 0; i <= nperim; i++) {
1067 if (i == nperim || perimeter[i].x > x) {
1068 /*
1069 * Fill in everything from the last Up edge to the
1070 * bottom of the grid, if necessary.
1071 */
1072 if (x != -1) {
1073 while (y < h) {
1074#ifdef PERTURB_DIAGNOSTICS
1075 printf("resolved: locking tile %d,%d\n", x, y);
1076#endif
1077 tiles[y * w + x] |= LOCKED;
1078 y++;
1079 }
1080 x = y = -1;
1081 }
1082
1083 if (i == nperim)
1084 break;
1085
1086 x = perimeter[i].x;
1087 y = 0;
1088 }
1089
1090 if (perimeter[i].direction == U) {
1091 x = perimeter[i].x;
1092 y = perimeter[i].y;
1093 } else if (perimeter[i].direction == D) {
1094 /*
1095 * Fill in everything from the last Up edge to here.
1096 */
1097 assert(x == perimeter[i].x && y <= perimeter[i].y);
1098 while (y <= perimeter[i].y) {
1099#ifdef PERTURB_DIAGNOSTICS
1100 printf("resolved: locking tile %d,%d\n", x, y);
1101#endif
1102 tiles[y * w + x] |= LOCKED;
1103 y++;
1104 }
1105 x = y = -1;
1106 }
1107 }
1108
1109 sfree(perimeter);
1110}
1111
1185e3c5 1112static char *new_game_desc(game_params *params, random_state *rs,
c566778e 1113 char **aux, int interactive)
720a8fb7 1114{
1185e3c5 1115 tree234 *possibilities, *barriertree;
1116 int w, h, x, y, cx, cy, nbarriers;
1117 unsigned char *tiles, *barriers;
1118 char *desc, *p;
6f2d8d7c 1119
1185e3c5 1120 w = params->width;
1121 h = params->height;
720a8fb7 1122
c0edd11f 1123 cx = w / 2;
1124 cy = h / 2;
1125
1185e3c5 1126 tiles = snewn(w * h, unsigned char);
1185e3c5 1127 barriers = snewn(w * h, unsigned char);
720a8fb7 1128
c0edd11f 1129 begin_generation:
1130
1131 memset(tiles, 0, w * h);
1132 memset(barriers, 0, w * h);
720a8fb7 1133
1134 /*
1135 * Construct the unshuffled grid.
1136 *
1137 * To do this, we simply start at the centre point, repeatedly
1138 * choose a random possibility out of the available ways to
1139 * extend a used square into an unused one, and do it. After
1140 * extending the third line out of a square, we remove the
1141 * fourth from the possibilities list to avoid any full-cross
1142 * squares (which would make the game too easy because they
1143 * only have one orientation).
1144 *
1145 * The slightly worrying thing is the avoidance of full-cross
1146 * squares. Can this cause our unsophisticated construction
1147 * algorithm to paint itself into a corner, by getting into a
1148 * situation where there are some unreached squares and the
1149 * only way to reach any of them is to extend a T-piece into a
1150 * full cross?
1151 *
1152 * Answer: no it can't, and here's a proof.
1153 *
1154 * Any contiguous group of such unreachable squares must be
1155 * surrounded on _all_ sides by T-pieces pointing away from the
1156 * group. (If not, then there is a square which can be extended
1157 * into one of the `unreachable' ones, and so it wasn't
1158 * unreachable after all.) In particular, this implies that
1159 * each contiguous group of unreachable squares must be
1160 * rectangular in shape (any deviation from that yields a
1161 * non-T-piece next to an `unreachable' square).
1162 *
1163 * So we have a rectangle of unreachable squares, with T-pieces
1164 * forming a solid border around the rectangle. The corners of
1165 * that border must be connected (since every tile connects all
1166 * the lines arriving in it), and therefore the border must
1167 * form a closed loop around the rectangle.
1168 *
1169 * But this can't have happened in the first place, since we
1170 * _know_ we've avoided creating closed loops! Hence, no such
1171 * situation can ever arise, and the naive grid construction
1172 * algorithm will guaranteeably result in a complete grid
1173 * containing no unreached squares, no full crosses _and_ no
1174 * closed loops. []
1175 */
c0edd11f 1176 possibilities = newtree234(xyd_cmp_nc);
ecadce0d 1177
1185e3c5 1178 if (cx+1 < w)
1179 add234(possibilities, new_xyd(cx, cy, R));
1180 if (cy-1 >= 0)
1181 add234(possibilities, new_xyd(cx, cy, U));
1182 if (cx-1 >= 0)
1183 add234(possibilities, new_xyd(cx, cy, L));
1184 if (cy+1 < h)
1185 add234(possibilities, new_xyd(cx, cy, D));
720a8fb7 1186
1187 while (count234(possibilities) > 0) {
1188 int i;
1189 struct xyd *xyd;
1190 int x1, y1, d1, x2, y2, d2, d;
1191
1192 /*
1193 * Extract a randomly chosen possibility from the list.
1194 */
1195 i = random_upto(rs, count234(possibilities));
1196 xyd = delpos234(possibilities, i);
1197 x1 = xyd->x;
1198 y1 = xyd->y;
1199 d1 = xyd->direction;
1200 sfree(xyd);
1201
1185e3c5 1202 OFFSET(x2, y2, x1, y1, d1, params);
720a8fb7 1203 d2 = F(d1);
95854b53 1204#ifdef GENERATION_DIAGNOSTICS
720a8fb7 1205 printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1206 x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1207#endif
1208
1209 /*
1210 * Make the connection. (We should be moving to an as yet
1211 * unused tile.)
1212 */
1185e3c5 1213 index(params, tiles, x1, y1) |= d1;
1214 assert(index(params, tiles, x2, y2) == 0);
1215 index(params, tiles, x2, y2) |= d2;
720a8fb7 1216
1217 /*
1218 * If we have created a T-piece, remove its last
1219 * possibility.
1220 */
1185e3c5 1221 if (COUNT(index(params, tiles, x1, y1)) == 3) {
720a8fb7 1222 struct xyd xyd1, *xydp;
1223
1224 xyd1.x = x1;
1225 xyd1.y = y1;
1185e3c5 1226 xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
720a8fb7 1227
1228 xydp = find234(possibilities, &xyd1, NULL);
1229
1230 if (xydp) {
95854b53 1231#ifdef GENERATION_DIAGNOSTICS
720a8fb7 1232 printf("T-piece; removing (%d,%d,%c)\n",
1233 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1234#endif
1235 del234(possibilities, xydp);
1236 sfree(xydp);
1237 }
1238 }
1239
1240 /*
1241 * Remove all other possibilities that were pointing at the
1242 * tile we've just moved into.
1243 */
1244 for (d = 1; d < 0x10; d <<= 1) {
1245 int x3, y3, d3;
1246 struct xyd xyd1, *xydp;
1247
1185e3c5 1248 OFFSET(x3, y3, x2, y2, d, params);
720a8fb7 1249 d3 = F(d);
1250
1251 xyd1.x = x3;
1252 xyd1.y = y3;
1253 xyd1.direction = d3;
1254
1255 xydp = find234(possibilities, &xyd1, NULL);
1256
1257 if (xydp) {
95854b53 1258#ifdef GENERATION_DIAGNOSTICS
720a8fb7 1259 printf("Loop avoidance; removing (%d,%d,%c)\n",
1260 xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1261#endif
1262 del234(possibilities, xydp);
1263 sfree(xydp);
1264 }
1265 }
1266
1267 /*
1268 * Add new possibilities to the list for moving _out_ of
1269 * the tile we have just moved into.
1270 */
1271 for (d = 1; d < 0x10; d <<= 1) {
1272 int x3, y3;
1273
1274 if (d == d2)
1275 continue; /* we've got this one already */
1276
1185e3c5 1277 if (!params->wrapping) {
720a8fb7 1278 if (d == U && y2 == 0)
1279 continue;
1185e3c5 1280 if (d == D && y2 == h-1)
720a8fb7 1281 continue;
1282 if (d == L && x2 == 0)
1283 continue;
1185e3c5 1284 if (d == R && x2 == w-1)
720a8fb7 1285 continue;
1286 }
1287
1185e3c5 1288 OFFSET(x3, y3, x2, y2, d, params);
720a8fb7 1289
1185e3c5 1290 if (index(params, tiles, x3, y3))
720a8fb7 1291 continue; /* this would create a loop */
1292
95854b53 1293#ifdef GENERATION_DIAGNOSTICS
720a8fb7 1294 printf("New frontier; adding (%d,%d,%c)\n",
1295 x2, y2, "0RU3L567D9abcdef"[d]);
1296#endif
1297 add234(possibilities, new_xyd(x2, y2, d));
1298 }
1299 }
1300 /* Having done that, we should have no possibilities remaining. */
1301 assert(count234(possibilities) == 0);
1302 freetree234(possibilities);
1303
c0edd11f 1304 if (params->unique) {
1305 int prevn = -1;
1306
1307 /*
1308 * Run the solver to check unique solubility.
1309 */
84942c65 1310 while (!net_solver(w, h, tiles, NULL, params->wrapping)) {
c0edd11f 1311 int n = 0;
1312
1313 /*
1314 * We expect (in most cases) that most of the grid will
1315 * be uniquely specified already, and the remaining
1316 * ambiguous sections will be small and separate. So
1317 * our strategy is to find each individual such
1318 * section, and perform a perturbation on the network
1319 * in that area.
1320 */
1321 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1322 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1323 n++;
1324 if (tiles[y*w+x] & LOCKED)
1325 perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1326 else
1327 perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1328 }
1329 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1330 n++;
1331 if (tiles[y*w+x] & LOCKED)
1332 perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1333 else
1334 perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1335 }
1336 }
1337
1338 /*
1339 * Now n counts the number of ambiguous sections we
1340 * have fiddled with. If we haven't managed to decrease
1341 * it from the last time we ran the solver, give up and
1342 * regenerate the entire grid.
1343 */
1344 if (prevn != -1 && prevn <= n)
1345 goto begin_generation; /* (sorry) */
1346
1347 prevn = n;
1348 }
1349
1350 /*
1351 * The solver will have left a lot of LOCKED bits lying
1352 * around in the tiles array. Remove them.
1353 */
1354 for (x = 0; x < w*h; x++)
1355 tiles[x] &= ~LOCKED;
1356 }
1357
720a8fb7 1358 /*
1359 * Now compute a list of the possible barrier locations.
1360 */
c0edd11f 1361 barriertree = newtree234(xyd_cmp_nc);
1185e3c5 1362 for (y = 0; y < h; y++) {
1363 for (x = 0; x < w; x++) {
1364
1365 if (!(index(params, tiles, x, y) & R) &&
1366 (params->wrapping || x < w-1))
1367 add234(barriertree, new_xyd(x, y, R));
1368 if (!(index(params, tiles, x, y) & D) &&
1369 (params->wrapping || y < h-1))
1370 add234(barriertree, new_xyd(x, y, D));
720a8fb7 1371 }
1372 }
1373
1374 /*
c566778e 1375 * Save the unshuffled grid in aux.
2ac6d24e 1376 */
1377 {
c566778e 1378 char *solution;
1379 int i;
2ac6d24e 1380
c566778e 1381 solution = snewn(w * h + 1, char);
1382 for (i = 0; i < w * h; i++)
1383 solution[i] = "0123456789abcdef"[tiles[i] & 0xF];
1384 solution[w*h] = '\0';
2ac6d24e 1385
1185e3c5 1386 *aux = solution;
2ac6d24e 1387 }
1388
1389 /*
720a8fb7 1390 * Now shuffle the grid.
1391 */
1185e3c5 1392 for (y = 0; y < h; y++) {
1393 for (x = 0; x < w; x++) {
1394 int orig = index(params, tiles, x, y);
720a8fb7 1395 int rot = random_upto(rs, 4);
1185e3c5 1396 index(params, tiles, x, y) = ROT(orig, rot);
720a8fb7 1397 }
1398 }
1399
1400 /*
1401 * And now choose barrier locations. (We carefully do this
1402 * _after_ shuffling, so that changing the barrier rate in the
1185e3c5 1403 * params while keeping the random seed the same will give the
720a8fb7 1404 * same shuffled grid and _only_ change the barrier locations.
1405 * Also the way we choose barrier locations, by repeatedly
1406 * choosing one possibility from the list until we have enough,
1407 * is designed to ensure that raising the barrier rate while
1408 * keeping the seed the same will provide a superset of the
1409 * previous barrier set - i.e. if you ask for 10 barriers, and
1410 * then decide that's still too hard and ask for 20, you'll get
1411 * the original 10 plus 10 more, rather than getting 20 new
1412 * ones and the chance of remembering your first 10.)
1413 */
1185e3c5 1414 nbarriers = (int)(params->barrier_probability * count234(barriertree));
1415 assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
720a8fb7 1416
1417 while (nbarriers > 0) {
1418 int i;
1419 struct xyd *xyd;
1420 int x1, y1, d1, x2, y2, d2;
1421
1422 /*
1423 * Extract a randomly chosen barrier from the list.
1424 */
1185e3c5 1425 i = random_upto(rs, count234(barriertree));
1426 xyd = delpos234(barriertree, i);
720a8fb7 1427
1428 assert(xyd != NULL);
1429
1430 x1 = xyd->x;
1431 y1 = xyd->y;
1432 d1 = xyd->direction;
1433 sfree(xyd);
1434
1185e3c5 1435 OFFSET(x2, y2, x1, y1, d1, params);
720a8fb7 1436 d2 = F(d1);
1437
1185e3c5 1438 index(params, barriers, x1, y1) |= d1;
1439 index(params, barriers, x2, y2) |= d2;
720a8fb7 1440
1441 nbarriers--;
1442 }
1443
1444 /*
1445 * Clean up the rest of the barrier list.
1446 */
1447 {
1448 struct xyd *xyd;
1449
1185e3c5 1450 while ( (xyd = delpos234(barriertree, 0)) != NULL)
720a8fb7 1451 sfree(xyd);
1452
1185e3c5 1453 freetree234(barriertree);
1454 }
1455
1456 /*
1457 * Finally, encode the grid into a string game description.
1458 *
1459 * My syntax is extremely simple: each square is encoded as a
1460 * hex digit in which bit 0 means a connection on the right,
1461 * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1462 * encoding as used internally). Each digit is followed by
1463 * optional barrier indicators: `v' means a vertical barrier to
1464 * the right of it, and `h' means a horizontal barrier below
1465 * it.
1466 */
1467 desc = snewn(w * h * 3 + 1, char);
1468 p = desc;
1469 for (y = 0; y < h; y++) {
1470 for (x = 0; x < w; x++) {
1471 *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1472 if ((params->wrapping || x < w-1) &&
1473 (index(params, barriers, x, y) & R))
1474 *p++ = 'v';
1475 if ((params->wrapping || y < h-1) &&
1476 (index(params, barriers, x, y) & D))
1477 *p++ = 'h';
1478 }
1479 }
1480 assert(p - desc <= w*h*3);
366d045b 1481 *p = '\0';
1185e3c5 1482
1483 sfree(tiles);
1484 sfree(barriers);
1485
1486 return desc;
1487}
1488
1185e3c5 1489static char *validate_desc(game_params *params, char *desc)
1490{
1491 int w = params->width, h = params->height;
1492 int i;
1493
1494 for (i = 0; i < w*h; i++) {
1495 if (*desc >= '0' && *desc <= '9')
1496 /* OK */;
1497 else if (*desc >= 'a' && *desc <= 'f')
1498 /* OK */;
1499 else if (*desc >= 'A' && *desc <= 'F')
1500 /* OK */;
1501 else if (!*desc)
1502 return "Game description shorter than expected";
1503 else
1504 return "Game description contained unexpected character";
1505 desc++;
1506 while (*desc == 'h' || *desc == 'v')
1507 desc++;
1508 }
1509 if (*desc)
1510 return "Game description longer than expected";
1511
1512 return NULL;
1513}
1514
1515/* ----------------------------------------------------------------------
1516 * Construct an initial game state, given a description and parameters.
1517 */
1518
dafd6cf6 1519static game_state *new_game(midend *me, game_params *params, char *desc)
1185e3c5 1520{
1521 game_state *state;
1522 int w, h, x, y;
1523
1524 assert(params->width > 0 && params->height > 0);
1525 assert(params->width > 1 || params->height > 1);
1526
1527 /*
1528 * Create a blank game state.
1529 */
1530 state = snew(game_state);
1531 w = state->width = params->width;
1532 h = state->height = params->height;
1185e3c5 1533 state->wrapping = params->wrapping;
1534 state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
a440f184 1535 state->completed = state->used_solve = FALSE;
1185e3c5 1536 state->tiles = snewn(state->width * state->height, unsigned char);
1537 memset(state->tiles, 0, state->width * state->height);
1538 state->barriers = snewn(state->width * state->height, unsigned char);
1539 memset(state->barriers, 0, state->width * state->height);
1540
1541 /*
1542 * Parse the game description into the grid.
1543 */
1544 for (y = 0; y < h; y++) {
1545 for (x = 0; x < w; x++) {
1546 if (*desc >= '0' && *desc <= '9')
1547 tile(state, x, y) = *desc - '0';
1548 else if (*desc >= 'a' && *desc <= 'f')
1549 tile(state, x, y) = *desc - 'a' + 10;
1550 else if (*desc >= 'A' && *desc <= 'F')
1551 tile(state, x, y) = *desc - 'A' + 10;
1552 if (*desc)
1553 desc++;
1554 while (*desc == 'h' || *desc == 'v') {
1555 int x2, y2, d1, d2;
1556 if (*desc == 'v')
1557 d1 = R;
1558 else
1559 d1 = D;
1560
1561 OFFSET(x2, y2, x, y, d1, state);
1562 d2 = F(d1);
1563
1564 barrier(state, x, y) |= d1;
1565 barrier(state, x2, y2) |= d2;
1566
1567 desc++;
1568 }
1569 }
1570 }
1571
1572 /*
1573 * Set up border barriers if this is a non-wrapping game.
1574 */
1575 if (!state->wrapping) {
1576 for (x = 0; x < state->width; x++) {
1577 barrier(state, x, 0) |= U;
1578 barrier(state, x, state->height-1) |= D;
1579 }
1580 for (y = 0; y < state->height; y++) {
1581 barrier(state, 0, y) |= L;
1582 barrier(state, state->width-1, y) |= R;
1583 }
f0ee053c 1584 } else {
1585 /*
1586 * We check whether this is de-facto a non-wrapping game
1587 * despite the parameters, in case we were passed the
1588 * description of a non-wrapping game. This is so that we
1589 * can change some aspects of the UI behaviour.
1590 */
1591 state->wrapping = FALSE;
1592 for (x = 0; x < state->width; x++)
1593 if (!(barrier(state, x, 0) & U) ||
1594 !(barrier(state, x, state->height-1) & D))
1595 state->wrapping = TRUE;
1596 for (y = 0; y < state->width; y++)
1597 if (!(barrier(state, 0, y) & L) ||
1598 !(barrier(state, state->width-1, y) & R))
1599 state->wrapping = TRUE;
720a8fb7 1600 }
1601
720a8fb7 1602 return state;
1603}
1604
be8d5aa1 1605static game_state *dup_game(game_state *state)
720a8fb7 1606{
1607 game_state *ret;
1608
1609 ret = snew(game_state);
1610 ret->width = state->width;
1611 ret->height = state->height;
1612 ret->wrapping = state->wrapping;
1613 ret->completed = state->completed;
2ac6d24e 1614 ret->used_solve = state->used_solve;
2ef96bd6 1615 ret->last_rotate_dir = state->last_rotate_dir;
1185e3c5 1616 ret->last_rotate_x = state->last_rotate_x;
1617 ret->last_rotate_y = state->last_rotate_y;
720a8fb7 1618 ret->tiles = snewn(state->width * state->height, unsigned char);
1619 memcpy(ret->tiles, state->tiles, state->width * state->height);
1620 ret->barriers = snewn(state->width * state->height, unsigned char);
1621 memcpy(ret->barriers, state->barriers, state->width * state->height);
1622
1623 return ret;
1624}
1625
be8d5aa1 1626static void free_game(game_state *state)
720a8fb7 1627{
1628 sfree(state->tiles);
1629 sfree(state->barriers);
1630 sfree(state);
1631}
1632
df11cd4e 1633static char *solve_game(game_state *state, game_state *currstate,
c566778e 1634 char *aux, char **error)
2ac6d24e 1635{
df11cd4e 1636 unsigned char *tiles;
1637 char *ret;
1638 int retlen, retsize;
1639 int i;
c566778e 1640
1641 tiles = snewn(state->width * state->height, unsigned char);
2ac6d24e 1642
1185e3c5 1643 if (!aux) {
c0edd11f 1644 /*
1645 * Run the internal solver on the provided grid. This might
1646 * not yield a complete solution.
1647 */
df11cd4e 1648 memcpy(tiles, state->tiles, state->width * state->height);
1649 net_solver(state->width, state->height, tiles,
1650 state->barriers, state->wrapping);
c0edd11f 1651 } else {
c566778e 1652 for (i = 0; i < state->width * state->height; i++) {
1653 int c = aux[i];
1654
1655 if (c >= '0' && c <= '9')
1656 tiles[i] = c - '0';
1657 else if (c >= 'a' && c <= 'f')
1658 tiles[i] = c - 'a' + 10;
1659 else if (c >= 'A' && c <= 'F')
1660 tiles[i] = c - 'A' + 10;
dafd6cf6 1661
1662 tiles[i] |= LOCKED;
c566778e 1663 }
df11cd4e 1664 }
1665
1666 /*
1667 * Now construct a string which can be passed to execute_move()
1668 * to transform the current grid into the solved one.
1669 */
1670 retsize = 256;
1671 ret = snewn(retsize, char);
1672 retlen = 0;
1673 ret[retlen++] = 'S';
1674
1675 for (i = 0; i < state->width * state->height; i++) {
1676 int from = currstate->tiles[i], to = tiles[i];
1677 int ft = from & (R|L|U|D), tt = to & (R|L|U|D);
1678 int x = i % state->width, y = i / state->width;
1679 int chr = '\0';
1680 char buf[80], *p = buf;
1681
1682 if (from == to)
1683 continue; /* nothing needs doing at all */
1684
1685 /*
1686 * To transform this tile into the desired tile: first
1687 * unlock the tile if it's locked, then rotate it if
1688 * necessary, then lock it if necessary.
1689 */
1690 if (from & LOCKED)
1691 p += sprintf(p, ";L%d,%d", x, y);
1692
1693 if (tt == A(ft))
1694 chr = 'A';
1695 else if (tt == C(ft))
1696 chr = 'C';
1697 else if (tt == F(ft))
1698 chr = 'F';
1699 else {
1700 assert(tt == ft);
1701 chr = '\0';
1702 }
1703 if (chr)
1704 p += sprintf(p, ";%c%d,%d", chr, x, y);
1705
1706 if (to & LOCKED)
1707 p += sprintf(p, ";L%d,%d", x, y);
1708
1709 if (p > buf) {
1710 if (retlen + (p - buf) >= retsize) {
1711 retsize = retlen + (p - buf) + 512;
1712 ret = sresize(ret, retsize, char);
1713 }
1714 memcpy(ret+retlen, buf, p - buf);
1715 retlen += p - buf;
1716 }
2ac6d24e 1717 }
1718
df11cd4e 1719 assert(retlen < retsize);
1720 ret[retlen] = '\0';
1721 ret = sresize(ret, retlen+1, char);
1722
c566778e 1723 sfree(tiles);
1724
2ac6d24e 1725 return ret;
1726}
1727
9b4b03d3 1728static char *game_text_format(game_state *state)
1729{
1730 return NULL;
1731}
1732
720a8fb7 1733/* ----------------------------------------------------------------------
1734 * Utility routine.
1735 */
1736
1737/*
1738 * Compute which squares are reachable from the centre square, as a
1739 * quick visual aid to determining how close the game is to
1740 * completion. This is also a simple way to tell if the game _is_
1741 * completed - just call this function and see whether every square
1742 * is marked active.
1743 */
f0ee053c 1744static unsigned char *compute_active(game_state *state, int cx, int cy)
720a8fb7 1745{
1746 unsigned char *active;
1747 tree234 *todo;
1748 struct xyd *xyd;
1749
1750 active = snewn(state->width * state->height, unsigned char);
1751 memset(active, 0, state->width * state->height);
1752
1753 /*
1754 * We only store (x,y) pairs in todo, but it's easier to reuse
1755 * xyd_cmp and just store direction 0 every time.
1756 */
c0edd11f 1757 todo = newtree234(xyd_cmp_nc);
f0ee053c 1758 index(state, active, cx, cy) = ACTIVE;
1759 add234(todo, new_xyd(cx, cy, 0));
720a8fb7 1760
1761 while ( (xyd = delpos234(todo, 0)) != NULL) {
1762 int x1, y1, d1, x2, y2, d2;
1763
1764 x1 = xyd->x;
1765 y1 = xyd->y;
1766 sfree(xyd);
1767
1768 for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1769 OFFSET(x2, y2, x1, y1, d1, state);
1770 d2 = F(d1);
1771
1772 /*
1773 * If the next tile in this direction is connected to
1774 * us, and there isn't a barrier in the way, and it
1775 * isn't already marked active, then mark it active and
1776 * add it to the to-examine list.
1777 */
1778 if ((tile(state, x1, y1) & d1) &&
1779 (tile(state, x2, y2) & d2) &&
1780 !(barrier(state, x1, y1) & d1) &&
1781 !index(state, active, x2, y2)) {
2ef96bd6 1782 index(state, active, x2, y2) = ACTIVE;
720a8fb7 1783 add234(todo, new_xyd(x2, y2, 0));
1784 }
1785 }
1786 }
1787 /* Now we expect the todo list to have shrunk to zero size. */
1788 assert(count234(todo) == 0);
1789 freetree234(todo);
1790
1791 return active;
1792}
1793
66164171 1794struct game_ui {
f0ee053c 1795 int org_x, org_y; /* origin */
1796 int cx, cy; /* source tile (game coordinates) */
66164171 1797 int cur_x, cur_y;
1798 int cur_visible;
cbb5549e 1799 random_state *rs; /* used for jumbling */
66164171 1800};
1801
be8d5aa1 1802static game_ui *new_ui(game_state *state)
74a4e547 1803{
cbb5549e 1804 void *seed;
1805 int seedsize;
66164171 1806 game_ui *ui = snew(game_ui);
f0ee053c 1807 ui->org_x = ui->org_y = 0;
1808 ui->cur_x = ui->cx = state->width / 2;
1809 ui->cur_y = ui->cy = state->height / 2;
66164171 1810 ui->cur_visible = FALSE;
cbb5549e 1811 get_random_seed(&seed, &seedsize);
1fbb0680 1812 ui->rs = random_new(seed, seedsize);
cbb5549e 1813 sfree(seed);
66164171 1814
1815 return ui;
74a4e547 1816}
1817
be8d5aa1 1818static void free_ui(game_ui *ui)
74a4e547 1819{
cbb5549e 1820 random_free(ui->rs);
66164171 1821 sfree(ui);
74a4e547 1822}
1823
844f605f 1824static char *encode_ui(game_ui *ui)
ae8290c6 1825{
1826 char buf[120];
1827 /*
1828 * We preserve the origin and centre-point coordinates over a
1829 * serialise.
1830 */
1831 sprintf(buf, "O%d,%d;C%d,%d", ui->org_x, ui->org_y, ui->cx, ui->cy);
1832 return dupstr(buf);
1833}
1834
844f605f 1835static void decode_ui(game_ui *ui, char *encoding)
ae8290c6 1836{
1837 sscanf(encoding, "O%d,%d;C%d,%d",
1838 &ui->org_x, &ui->org_y, &ui->cx, &ui->cy);
1839}
1840
07dfb697 1841static void game_changed_state(game_ui *ui, game_state *oldstate,
1842 game_state *newstate)
1843{
1844}
1845
1e3e152d 1846struct game_drawstate {
1847 int started;
1848 int width, height;
1849 int org_x, org_y;
1850 int tilesize;
1851 unsigned char *visible;
1852};
1853
720a8fb7 1854/* ----------------------------------------------------------------------
1855 * Process a move.
1856 */
df11cd4e 1857static char *interpret_move(game_state *state, game_ui *ui,
1858 game_drawstate *ds, int x, int y, int button)
1859{
1860 char *nullret;
118473f5 1861 int tx = -1, ty = -1, dir = 0;
f0ee053c 1862 int shift = button & MOD_SHFT, ctrl = button & MOD_CTRL;
118473f5 1863 enum {
1864 NONE, ROTATE_LEFT, ROTATE_180, ROTATE_RIGHT, TOGGLE_LOCK, JUMBLE,
1865 MOVE_ORIGIN, MOVE_SOURCE, MOVE_ORIGIN_AND_SOURCE, MOVE_CURSOR
1866 } action;
720a8fb7 1867
f0ee053c 1868 button &= ~MOD_MASK;
66164171 1869 nullret = NULL;
118473f5 1870 action = NONE;
720a8fb7 1871
66164171 1872 if (button == LEFT_BUTTON ||
1873 button == MIDDLE_BUTTON ||
1874 button == RIGHT_BUTTON) {
1875
1876 if (ui->cur_visible) {
1877 ui->cur_visible = FALSE;
df11cd4e 1878 nullret = "";
66164171 1879 }
1880
1881 /*
1882 * The button must have been clicked on a valid tile.
1883 */
1884 x -= WINDOW_OFFSET + TILE_BORDER;
1885 y -= WINDOW_OFFSET + TILE_BORDER;
1886 if (x < 0 || y < 0)
1887 return nullret;
1888 tx = x / TILE_SIZE;
1889 ty = y / TILE_SIZE;
1890 if (tx >= state->width || ty >= state->height)
1891 return nullret;
f0ee053c 1892 /* Transform from physical to game coords */
1893 tx = (tx + ui->org_x) % state->width;
1894 ty = (ty + ui->org_y) % state->height;
66164171 1895 if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
1896 y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
1897 return nullret;
118473f5 1898
1899 action = button == LEFT_BUTTON ? ROTATE_LEFT :
1900 button == RIGHT_BUTTON ? ROTATE_RIGHT : TOGGLE_LOCK;
66164171 1901 } else if (button == CURSOR_UP || button == CURSOR_DOWN ||
1902 button == CURSOR_RIGHT || button == CURSOR_LEFT) {
f0ee053c 1903 switch (button) {
1904 case CURSOR_UP: dir = U; break;
1905 case CURSOR_DOWN: dir = D; break;
1906 case CURSOR_LEFT: dir = L; break;
1907 case CURSOR_RIGHT: dir = R; break;
1908 default: return nullret;
1909 }
118473f5 1910 if (shift && ctrl) action = MOVE_ORIGIN_AND_SOURCE;
1911 else if (shift) action = MOVE_ORIGIN;
1912 else if (ctrl) action = MOVE_SOURCE;
1913 else action = MOVE_CURSOR;
66164171 1914 } else if (button == 'a' || button == 's' || button == 'd' ||
4cd25760 1915 button == 'A' || button == 'S' || button == 'D' ||
118473f5 1916 button == 'f' || button == 'F' ||
4cd25760 1917 button == CURSOR_SELECT) {
66164171 1918 tx = ui->cur_x;
1919 ty = ui->cur_y;
4cd25760 1920 if (button == 'a' || button == 'A' || button == CURSOR_SELECT)
118473f5 1921 action = ROTATE_LEFT;
66164171 1922 else if (button == 's' || button == 'S')
118473f5 1923 action = TOGGLE_LOCK;
66164171 1924 else if (button == 'd' || button == 'D')
118473f5 1925 action = ROTATE_RIGHT;
1926 else if (button == 'f' || button == 'F')
1927 action = ROTATE_180;
0671fa51 1928 ui->cur_visible = TRUE;
cbb5549e 1929 } else if (button == 'j' || button == 'J') {
1930 /* XXX should we have some mouse control for this? */
118473f5 1931 action = JUMBLE;
66164171 1932 } else
1933 return nullret;
720a8fb7 1934
1935 /*
1936 * The middle button locks or unlocks a tile. (A locked tile
1937 * cannot be turned, and is visually marked as being locked.
1938 * This is a convenience for the player, so that once they are
1939 * sure which way round a tile goes, they can lock it and thus
1940 * avoid forgetting later on that they'd already done that one;
1941 * and the locking also prevents them turning the tile by
1942 * accident. If they change their mind, another middle click
1943 * unlocks it.)
1944 */
118473f5 1945 if (action == TOGGLE_LOCK) {
df11cd4e 1946 char buf[80];
1947 sprintf(buf, "L%d,%d", tx, ty);
1948 return dupstr(buf);
118473f5 1949 } else if (action == ROTATE_LEFT || action == ROTATE_RIGHT ||
1950 action == ROTATE_180) {
216147c0 1951 char buf[80];
720a8fb7 1952
cbb5549e 1953 /*
1954 * The left and right buttons have no effect if clicked on a
1955 * locked tile.
1956 */
1957 if (tile(state, tx, ty) & LOCKED)
1958 return nullret;
1959
1960 /*
1961 * Otherwise, turn the tile one way or the other. Left button
1962 * turns anticlockwise; right button turns clockwise.
1963 */
118473f5 1964 sprintf(buf, "%c%d,%d", (int)(action == ROTATE_LEFT ? 'A' :
1965 action == ROTATE_RIGHT ? 'C' : 'F'), tx, ty);
df11cd4e 1966 return dupstr(buf);
118473f5 1967 } else if (action == JUMBLE) {
cbb5549e 1968 /*
1969 * Jumble all unlocked tiles to random orientations.
1970 */
df11cd4e 1971
1972 int jx, jy, maxlen;
1973 char *ret, *p;
1974
1975 /*
1976 * Maximum string length assumes no int can be converted to
1977 * decimal and take more than 11 digits!
1978 */
1979 maxlen = state->width * state->height * 25 + 3;
1980
1981 ret = snewn(maxlen, char);
1982 p = ret;
1983 *p++ = 'J';
1984
1985 for (jy = 0; jy < state->height; jy++) {
1986 for (jx = 0; jx < state->width; jx++) {
1987 if (!(tile(state, jx, jy) & LOCKED)) {
cbb5549e 1988 int rot = random_upto(ui->rs, 4);
df11cd4e 1989 if (rot) {
1990 p += sprintf(p, ";%c%d,%d", "AFC"[rot-1], jx, jy);
1991 }
cbb5549e 1992 }
1993 }
1994 }
df11cd4e 1995 *p++ = '\0';
1996 assert(p - ret < maxlen);
1997 ret = sresize(ret, p - ret, char);
cbb5549e 1998
df11cd4e 1999 return ret;
118473f5 2000 } else if (action == MOVE_ORIGIN || action == MOVE_SOURCE ||
2001 action == MOVE_ORIGIN_AND_SOURCE || action == MOVE_CURSOR) {
2002 assert(dir != 0);
2003 if (action == MOVE_ORIGIN || action == MOVE_ORIGIN_AND_SOURCE) {
2004 if (state->wrapping) {
2005 OFFSET(ui->org_x, ui->org_y, ui->org_x, ui->org_y, dir, state);
2006 } else return nullret; /* disallowed for non-wrapping grids */
2007 }
2008 if (action == MOVE_SOURCE || action == MOVE_ORIGIN_AND_SOURCE) {
2009 OFFSET(ui->cx, ui->cy, ui->cx, ui->cy, dir, state);
2010 }
2011 if (action == MOVE_CURSOR) {
2012 OFFSET(ui->cur_x, ui->cur_y, ui->cur_x, ui->cur_y, dir, state);
2013 ui->cur_visible = TRUE;
2014 }
2015 return "";
ab53eb64 2016 } else {
df11cd4e 2017 return NULL;
2018 }
2019}
2020
2021static game_state *execute_move(game_state *from, char *move)
2022{
2023 game_state *ret;
2024 int tx, ty, n, noanim, orig;
2025
2026 ret = dup_game(from);
df11cd4e 2027
2028 if (move[0] == 'J' || move[0] == 'S') {
2029 if (move[0] == 'S')
a440f184 2030 ret->used_solve = TRUE;
df11cd4e 2031
2032 move++;
2033 if (*move == ';')
2034 move++;
2035 noanim = TRUE;
2036 } else
2037 noanim = FALSE;
2038
2039 ret->last_rotate_dir = 0; /* suppress animation */
2040 ret->last_rotate_x = ret->last_rotate_y = 0;
2041
2042 while (*move) {
2043 if ((move[0] == 'A' || move[0] == 'C' ||
2044 move[0] == 'F' || move[0] == 'L') &&
2045 sscanf(move+1, "%d,%d%n", &tx, &ty, &n) >= 2 &&
2046 tx >= 0 && tx < from->width && ty >= 0 && ty < from->height) {
2047 orig = tile(ret, tx, ty);
2048 if (move[0] == 'A') {
2049 tile(ret, tx, ty) = A(orig);
2050 if (!noanim)
2051 ret->last_rotate_dir = +1;
2052 } else if (move[0] == 'F') {
2053 tile(ret, tx, ty) = F(orig);
118473f5 2054 if (!noanim)
2055 ret->last_rotate_dir = +2; /* + for sake of argument */
df11cd4e 2056 } else if (move[0] == 'C') {
2057 tile(ret, tx, ty) = C(orig);
2058 if (!noanim)
2059 ret->last_rotate_dir = -1;
2060 } else {
2061 assert(move[0] == 'L');
2062 tile(ret, tx, ty) ^= LOCKED;
2063 }
2064
2065 move += 1 + n;
2066 if (*move == ';') move++;
2067 } else {
2068 free_game(ret);
2069 return NULL;
2070 }
2071 }
2072 if (!noanim) {
2073 ret->last_rotate_x = tx;
2074 ret->last_rotate_y = ty;
ab53eb64 2075 }
720a8fb7 2076
2077 /*
2078 * Check whether the game has been completed.
df11cd4e 2079 *
2080 * For this purpose it doesn't matter where the source square
2081 * is, because we can start from anywhere and correctly
2082 * determine whether the game is completed.
720a8fb7 2083 */
2084 {
df11cd4e 2085 unsigned char *active = compute_active(ret, 0, 0);
720a8fb7 2086 int x1, y1;
2087 int complete = TRUE;
2088
2089 for (x1 = 0; x1 < ret->width; x1++)
2090 for (y1 = 0; y1 < ret->height; y1++)
1185e3c5 2091 if ((tile(ret, x1, y1) & 0xF) && !index(ret, active, x1, y1)) {
720a8fb7 2092 complete = FALSE;
2093 goto break_label; /* break out of two loops at once */
2094 }
2095 break_label:
2096
2097 sfree(active);
2098
2099 if (complete)
2100 ret->completed = TRUE;
2101 }
2102
2103 return ret;
2104}
2105
df11cd4e 2106
720a8fb7 2107/* ----------------------------------------------------------------------
2108 * Routines for drawing the game position on the screen.
2109 */
2110
dafd6cf6 2111static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2ef96bd6 2112{
2113 game_drawstate *ds = snew(game_drawstate);
2114
2115 ds->started = FALSE;
2116 ds->width = state->width;
2117 ds->height = state->height;
f0ee053c 2118 ds->org_x = ds->org_y = -1;
2ef96bd6 2119 ds->visible = snewn(state->width * state->height, unsigned char);
1e3e152d 2120 ds->tilesize = 0; /* undecided yet */
2ef96bd6 2121 memset(ds->visible, 0xFF, state->width * state->height);
2122
2123 return ds;
2124}
2125
dafd6cf6 2126static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2ef96bd6 2127{
2128 sfree(ds->visible);
2129 sfree(ds);
2130}
2131
1f3ee4ee 2132static void game_compute_size(game_params *params, int tilesize,
2133 int *x, int *y)
7f77ea24 2134{
1f3ee4ee 2135 *x = WINDOW_OFFSET * 2 + tilesize * params->width + TILE_BORDER;
2136 *y = WINDOW_OFFSET * 2 + tilesize * params->height + TILE_BORDER;
2137}
1e3e152d 2138
dafd6cf6 2139static void game_set_size(drawing *dr, game_drawstate *ds,
2140 game_params *params, int tilesize)
1f3ee4ee 2141{
2142 ds->tilesize = tilesize;
7f77ea24 2143}
2144
8266f3fc 2145static float *game_colours(frontend *fe, int *ncolours)
2ef96bd6 2146{
2147 float *ret;
83680571 2148
2ef96bd6 2149 ret = snewn(NCOLOURS * 3, float);
2150 *ncolours = NCOLOURS;
720a8fb7 2151
2ef96bd6 2152 /*
2153 * Basic background colour is whatever the front end thinks is
2154 * a sensible default.
2155 */
2156 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2157
2158 /*
2159 * Wires are black.
2160 */
03f856c4 2161 ret[COL_WIRE * 3 + 0] = 0.0F;
2162 ret[COL_WIRE * 3 + 1] = 0.0F;
2163 ret[COL_WIRE * 3 + 2] = 0.0F;
2ef96bd6 2164
2165 /*
2166 * Powered wires and powered endpoints are cyan.
2167 */
03f856c4 2168 ret[COL_POWERED * 3 + 0] = 0.0F;
2169 ret[COL_POWERED * 3 + 1] = 1.0F;
2170 ret[COL_POWERED * 3 + 2] = 1.0F;
2ef96bd6 2171
2172 /*
2173 * Barriers are red.
2174 */
03f856c4 2175 ret[COL_BARRIER * 3 + 0] = 1.0F;
2176 ret[COL_BARRIER * 3 + 1] = 0.0F;
2177 ret[COL_BARRIER * 3 + 2] = 0.0F;
2ef96bd6 2178
2179 /*
2180 * Unpowered endpoints are blue.
2181 */
03f856c4 2182 ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2183 ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2184 ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2ef96bd6 2185
2186 /*
2187 * Tile borders are a darker grey than the background.
2188 */
03f856c4 2189 ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2190 ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2191 ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2ef96bd6 2192
2193 /*
2194 * Locked tiles are a grey in between those two.
2195 */
03f856c4 2196 ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2197 ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2198 ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2ef96bd6 2199
2200 return ret;
2201}
2202
dafd6cf6 2203static void draw_thick_line(drawing *dr, int x1, int y1, int x2, int y2,
2ef96bd6 2204 int colour)
720a8fb7 2205{
dafd6cf6 2206 draw_line(dr, x1-1, y1, x2-1, y2, COL_WIRE);
2207 draw_line(dr, x1+1, y1, x2+1, y2, COL_WIRE);
2208 draw_line(dr, x1, y1-1, x2, y2-1, COL_WIRE);
2209 draw_line(dr, x1, y1+1, x2, y2+1, COL_WIRE);
2210 draw_line(dr, x1, y1, x2, y2, colour);
2ef96bd6 2211}
720a8fb7 2212
dafd6cf6 2213static void draw_rect_coords(drawing *dr, int x1, int y1, int x2, int y2,
2ef96bd6 2214 int colour)
2215{
2216 int mx = (x1 < x2 ? x1 : x2);
2217 int my = (y1 < y2 ? y1 : y2);
2218 int dx = (x2 + x1 - 2*mx + 1);
2219 int dy = (y2 + y1 - 2*my + 1);
720a8fb7 2220
dafd6cf6 2221 draw_rect(dr, mx, my, dx, dy, colour);
2ef96bd6 2222}
720a8fb7 2223
f0ee053c 2224/*
2225 * draw_barrier_corner() and draw_barrier() are passed physical coords
2226 */
dafd6cf6 2227static void draw_barrier_corner(drawing *dr, game_drawstate *ds,
1e3e152d 2228 int x, int y, int dx, int dy, int phase)
2ef96bd6 2229{
2230 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2231 int by = WINDOW_OFFSET + TILE_SIZE * y;
6c333866 2232 int x1, y1;
2ef96bd6 2233
2ef96bd6 2234 x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2235 y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2236
2237 if (phase == 0) {
dafd6cf6 2238 draw_rect_coords(dr, bx+x1+dx, by+y1,
2ef96bd6 2239 bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
6c333866 2240 COL_WIRE);
dafd6cf6 2241 draw_rect_coords(dr, bx+x1, by+y1+dy,
2ef96bd6 2242 bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
6c333866 2243 COL_WIRE);
2ef96bd6 2244 } else {
dafd6cf6 2245 draw_rect_coords(dr, bx+x1, by+y1,
2ef96bd6 2246 bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
6c333866 2247 COL_BARRIER);
720a8fb7 2248 }
2ef96bd6 2249}
2250
dafd6cf6 2251static void draw_barrier(drawing *dr, game_drawstate *ds,
1e3e152d 2252 int x, int y, int dir, int phase)
2ef96bd6 2253{
2254 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2255 int by = WINDOW_OFFSET + TILE_SIZE * y;
2256 int x1, y1, w, h;
2257
2258 x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
2259 y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
2260 w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2261 h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2262
2263 if (phase == 0) {
dafd6cf6 2264 draw_rect(dr, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
2ef96bd6 2265 } else {
dafd6cf6 2266 draw_rect(dr, bx+x1, by+y1, w, h, COL_BARRIER);
2ef96bd6 2267 }
2268}
720a8fb7 2269
f0ee053c 2270/*
2271 * draw_tile() is passed physical coordinates
2272 */
dafd6cf6 2273static void draw_tile(drawing *dr, game_state *state, game_drawstate *ds,
f0ee053c 2274 int x, int y, int tile, int src, float angle, int cursor)
2ef96bd6 2275{
2276 int bx = WINDOW_OFFSET + TILE_SIZE * x;
2277 int by = WINDOW_OFFSET + TILE_SIZE * y;
2278 float matrix[4];
2279 float cx, cy, ex, ey, tx, ty;
2280 int dir, col, phase;
720a8fb7 2281
2ef96bd6 2282 /*
2283 * When we draw a single tile, we must draw everything up to
2284 * and including the borders around the tile. This means that
2285 * if the neighbouring tiles have connections to those borders,
2286 * we must draw those connections on the borders themselves.
2ef96bd6 2287 */
2288
dafd6cf6 2289 clip(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
6c333866 2290
2ef96bd6 2291 /*
2292 * So. First blank the tile out completely: draw a big
2293 * rectangle in border colour, and a smaller rectangle in
2294 * background colour to fill it in.
2295 */
dafd6cf6 2296 draw_rect(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
2ef96bd6 2297 COL_BORDER);
dafd6cf6 2298 draw_rect(dr, bx+TILE_BORDER, by+TILE_BORDER,
2ef96bd6 2299 TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
2300 tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
2301
2302 /*
66164171 2303 * Draw an inset outline rectangle as a cursor, in whichever of
2304 * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
2305 * in.
2306 */
2307 if (cursor) {
dafd6cf6 2308 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
66164171 2309 bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2310 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
dafd6cf6 2311 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE/8,
66164171 2312 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2313 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
dafd6cf6 2314 draw_line(dr, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
66164171 2315 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2316 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
dafd6cf6 2317 draw_line(dr, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
66164171 2318 bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2319 tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2320 }
2321
2322 /*
2ef96bd6 2323 * Set up the rotation matrix.
2324 */
03f856c4 2325 matrix[0] = (float)cos(angle * PI / 180.0);
2326 matrix[1] = (float)-sin(angle * PI / 180.0);
2327 matrix[2] = (float)sin(angle * PI / 180.0);
2328 matrix[3] = (float)cos(angle * PI / 180.0);
2ef96bd6 2329
2330 /*
2331 * Draw the wires.
2332 */
03f856c4 2333 cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
2ef96bd6 2334 col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
2335 for (dir = 1; dir < 0x10; dir <<= 1) {
2336 if (tile & dir) {
03f856c4 2337 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2338 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2ef96bd6 2339 MATMUL(tx, ty, matrix, ex, ey);
dafd6cf6 2340 draw_thick_line(dr, bx+(int)cx, by+(int)cy,
03f856c4 2341 bx+(int)(cx+tx), by+(int)(cy+ty),
2ef96bd6 2342 COL_WIRE);
2343 }
2344 }
2345 for (dir = 1; dir < 0x10; dir <<= 1) {
2346 if (tile & dir) {
03f856c4 2347 ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2348 ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2ef96bd6 2349 MATMUL(tx, ty, matrix, ex, ey);
dafd6cf6 2350 draw_line(dr, bx+(int)cx, by+(int)cy,
03f856c4 2351 bx+(int)(cx+tx), by+(int)(cy+ty), col);
2ef96bd6 2352 }
2353 }
2354
2355 /*
2356 * Draw the box in the middle. We do this in blue if the tile
2357 * is an unpowered endpoint, in cyan if the tile is a powered
2358 * endpoint, in black if the tile is the centrepiece, and
2359 * otherwise not at all.
2360 */
2361 col = -1;
f0ee053c 2362 if (src)
2ef96bd6 2363 col = COL_WIRE;
2364 else if (COUNT(tile) == 1) {
2365 col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
2366 }
2367 if (col >= 0) {
2368 int i, points[8];
2369
2370 points[0] = +1; points[1] = +1;
2371 points[2] = +1; points[3] = -1;
2372 points[4] = -1; points[5] = -1;
2373 points[6] = -1; points[7] = +1;
2374
2375 for (i = 0; i < 8; i += 2) {
03f856c4 2376 ex = (TILE_SIZE * 0.24F) * points[i];
2377 ey = (TILE_SIZE * 0.24F) * points[i+1];
2ef96bd6 2378 MATMUL(tx, ty, matrix, ex, ey);
03f856c4 2379 points[i] = bx+(int)(cx+tx);
2380 points[i+1] = by+(int)(cy+ty);
2ef96bd6 2381 }
2382
dafd6cf6 2383 draw_polygon(dr, points, 4, col, COL_WIRE);
2ef96bd6 2384 }
2385
2386 /*
2387 * Draw the points on the border if other tiles are connected
2388 * to us.
2389 */
2390 for (dir = 1; dir < 0x10; dir <<= 1) {
2391 int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
2392
2393 dx = X(dir);
2394 dy = Y(dir);
2395
2396 ox = x + dx;
2397 oy = y + dy;
2398
2399 if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
2400 continue;
2401
f0ee053c 2402 if (!(tile(state, GX(ox), GY(oy)) & F(dir)))
2ef96bd6 2403 continue;
2404
03f856c4 2405 px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
2406 py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
2ef96bd6 2407 lx = dx * (TILE_BORDER-1);
2408 ly = dy * (TILE_BORDER-1);
2409 vx = (dy ? 1 : 0);
2410 vy = (dx ? 1 : 0);
2411
2412 if (angle == 0.0 && (tile & dir)) {
2413 /*
2414 * If we are fully connected to the other tile, we must
2415 * draw right across the tile border. (We can use our
2416 * own ACTIVE state to determine what colour to do this
2417 * in: if we are fully connected to the other tile then
2418 * the two ACTIVE states will be the same.)
2419 */
dafd6cf6 2420 draw_rect_coords(dr, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
2421 draw_rect_coords(dr, px, py, px+lx, py+ly,
2ef96bd6 2422 (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
2423 } else {
2424 /*
2425 * The other tile extends into our border, but isn't
2426 * actually connected to us. Just draw a single black
2427 * dot.
2428 */
dafd6cf6 2429 draw_rect_coords(dr, px, py, px, py, COL_WIRE);
2ef96bd6 2430 }
2431 }
2432
2433 /*
2434 * Draw barrier corners, and then barriers.
2435 */
2436 for (phase = 0; phase < 2; phase++) {
6c333866 2437 for (dir = 1; dir < 0x10; dir <<= 1) {
2438 int x1, y1, corner = FALSE;
2439 /*
2440 * If at least one barrier terminates at the corner
2441 * between dir and A(dir), draw a barrier corner.
2442 */
2443 if (barrier(state, GX(x), GY(y)) & (dir | A(dir))) {
2444 corner = TRUE;
2445 } else {
2446 /*
2447 * Only count barriers terminating at this corner
2448 * if they're physically next to the corner. (That
2449 * is, if they've wrapped round from the far side
2450 * of the screen, they don't count.)
2451 */
2452 x1 = x + X(dir);
2453 y1 = y + Y(dir);
2454 if (x1 >= 0 && x1 < state->width &&
2455 y1 >= 0 && y1 < state->height &&
2456 (barrier(state, GX(x1), GY(y1)) & A(dir))) {
2457 corner = TRUE;
2458 } else {
2459 x1 = x + X(A(dir));
2460 y1 = y + Y(A(dir));
2461 if (x1 >= 0 && x1 < state->width &&
2462 y1 >= 0 && y1 < state->height &&
2463 (barrier(state, GX(x1), GY(y1)) & dir))
2464 corner = TRUE;
2465 }
2466 }
2467
2468 if (corner) {
2469 /*
2470 * At least one barrier terminates here. Draw a
2471 * corner.
2472 */
dafd6cf6 2473 draw_barrier_corner(dr, ds, x, y,
6c333866 2474 X(dir)+X(A(dir)), Y(dir)+Y(A(dir)),
2475 phase);
2476 }
2477 }
2478
2ef96bd6 2479 for (dir = 1; dir < 0x10; dir <<= 1)
f0ee053c 2480 if (barrier(state, GX(x), GY(y)) & dir)
dafd6cf6 2481 draw_barrier(dr, ds, x, y, dir, phase);
2ef96bd6 2482 }
2483
dafd6cf6 2484 unclip(dr);
6c333866 2485
dafd6cf6 2486 draw_update(dr, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
720a8fb7 2487}
2488
dafd6cf6 2489static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
c822de4a 2490 game_state *state, int dir, game_ui *ui, float t, float ft)
2ef96bd6 2491{
f0ee053c 2492 int x, y, tx, ty, frame, last_rotate_dir, moved_origin = FALSE;
2ef96bd6 2493 unsigned char *active;
2494 float angle = 0.0;
2495
2496 /*
6c333866 2497 * Clear the screen, and draw the exterior barrier lines, if
2498 * this is our first call or if the origin has changed.
2ef96bd6 2499 */
6c333866 2500 if (!ds->started || ui->org_x != ds->org_x || ui->org_y != ds->org_y) {
2501 int phase;
2502
2ef96bd6 2503 ds->started = TRUE;
2504
dafd6cf6 2505 draw_rect(dr, 0, 0,
2ef96bd6 2506 WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
2507 WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
2508 COL_BACKGROUND);
f0ee053c 2509
f0ee053c 2510 ds->org_x = ui->org_x;
2511 ds->org_y = ui->org_y;
2512 moved_origin = TRUE;
2513
dafd6cf6 2514 draw_update(dr, 0, 0,
2ef96bd6 2515 WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
2516 WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
6c333866 2517
2ef96bd6 2518 for (phase = 0; phase < 2; phase++) {
2519
2520 for (x = 0; x < ds->width; x++) {
6c333866 2521 if (x+1 < ds->width) {
2522 if (barrier(state, GX(x), GY(0)) & R)
dafd6cf6 2523 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
6c333866 2524 if (barrier(state, GX(x), GY(ds->height-1)) & R)
dafd6cf6 2525 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
6c333866 2526 }
2527 if (barrier(state, GX(x), GY(0)) & U) {
dafd6cf6 2528 draw_barrier_corner(dr, ds, x, -1, -1, +1, phase);
2529 draw_barrier_corner(dr, ds, x, -1, +1, +1, phase);
2530 draw_barrier(dr, ds, x, -1, D, phase);
6c333866 2531 }
2532 if (barrier(state, GX(x), GY(ds->height-1)) & D) {
dafd6cf6 2533 draw_barrier_corner(dr, ds, x, ds->height, -1, -1, phase);
2534 draw_barrier_corner(dr, ds, x, ds->height, +1, -1, phase);
2535 draw_barrier(dr, ds, x, ds->height, U, phase);
6c333866 2536 }
2ef96bd6 2537 }
2538
2539 for (y = 0; y < ds->height; y++) {
6c333866 2540 if (y+1 < ds->height) {
2541 if (barrier(state, GX(0), GY(y)) & D)
dafd6cf6 2542 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
6c333866 2543 if (barrier(state, GX(ds->width-1), GY(y)) & D)
dafd6cf6 2544 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
6c333866 2545 }
2546 if (barrier(state, GX(0), GY(y)) & L) {
dafd6cf6 2547 draw_barrier_corner(dr, ds, -1, y, +1, -1, phase);
2548 draw_barrier_corner(dr, ds, -1, y, +1, +1, phase);
2549 draw_barrier(dr, ds, -1, y, R, phase);
6c333866 2550 }
2551 if (barrier(state, GX(ds->width-1), GY(y)) & R) {
dafd6cf6 2552 draw_barrier_corner(dr, ds, ds->width, y, -1, -1, phase);
2553 draw_barrier_corner(dr, ds, ds->width, y, -1, +1, phase);
2554 draw_barrier(dr, ds, ds->width, y, L, phase);
6c333866 2555 }
2ef96bd6 2556 }
2557 }
2558 }
2559
2560 tx = ty = -1;
cbb5549e 2561 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2562 state->last_rotate_dir;
2563 if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2ef96bd6 2564 /*
1185e3c5 2565 * We're animating a single tile rotation. Find the turning
2566 * tile.
2ef96bd6 2567 */
1185e3c5 2568 tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2569 ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2570 angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2571 state = oldstate;
87ed82be 2572 }
1185e3c5 2573
87ed82be 2574 frame = -1;
2575 if (ft > 0) {
2ef96bd6 2576 /*
2577 * We're animating a completion flash. Find which frame
2578 * we're at.
2579 */
87ed82be 2580 frame = (int)(ft / FLASH_FRAME);
2ef96bd6 2581 }
2582
2583 /*
2584 * Draw any tile which differs from the way it was last drawn.
2585 */
f0ee053c 2586 active = compute_active(state, ui->cx, ui->cy);
2ef96bd6 2587
2588 for (x = 0; x < ds->width; x++)
2589 for (y = 0; y < ds->height; y++) {
f0ee053c 2590 unsigned char c = tile(state, GX(x), GY(y)) |
2591 index(state, active, GX(x), GY(y));
2592 int is_src = GX(x) == ui->cx && GY(y) == ui->cy;
2593 int is_anim = GX(x) == tx && GY(y) == ty;
2594 int is_cursor = ui->cur_visible &&
2595 GX(x) == ui->cur_x && GY(y) == ui->cur_y;
2ef96bd6 2596
2597 /*
2598 * In a completion flash, we adjust the LOCKED bit
2599 * depending on our distance from the centre point and
2600 * the frame number.
2601 */
2602 if (frame >= 0) {
f0ee053c 2603 int rcx = RX(ui->cx), rcy = RY(ui->cy);
2ef96bd6 2604 int xdist, ydist, dist;
f0ee053c 2605 xdist = (x < rcx ? rcx - x : x - rcx);
2606 ydist = (y < rcy ? rcy - y : y - rcy);
2ef96bd6 2607 dist = (xdist > ydist ? xdist : ydist);
2608
2609 if (frame >= dist && frame < dist+4) {
2610 int lock = (frame - dist) & 1;
2611 lock = lock ? LOCKED : 0;
2612 c = (c &~ LOCKED) | lock;
2613 }
2614 }
2615
f0ee053c 2616 if (moved_origin ||
2617 index(state, ds->visible, x, y) != c ||
2ef96bd6 2618 index(state, ds->visible, x, y) == 0xFF ||
f0ee053c 2619 is_src || is_anim || is_cursor) {
dafd6cf6 2620 draw_tile(dr, state, ds, x, y, c,
f0ee053c 2621 is_src, (is_anim ? angle : 0.0F), is_cursor);
2622 if (is_src || is_anim || is_cursor)
2ef96bd6 2623 index(state, ds->visible, x, y) = 0xFF;
2624 else
2625 index(state, ds->visible, x, y) = c;
2626 }
2627 }
2628
fd1a1a2b 2629 /*
2630 * Update the status bar.
2631 */
2632 {
2633 char statusbuf[256];
1185e3c5 2634 int i, n, n2, a;
fd1a1a2b 2635
2636 n = state->width * state->height;
1185e3c5 2637 for (i = a = n2 = 0; i < n; i++) {
fd1a1a2b 2638 if (active[i])
2639 a++;
1185e3c5 2640 if (state->tiles[i] & 0xF)
2641 n2++;
2642 }
fd1a1a2b 2643
2644 sprintf(statusbuf, "%sActive: %d/%d",
2ac6d24e 2645 (state->used_solve ? "Auto-solved. " :
1185e3c5 2646 state->completed ? "COMPLETED! " : ""), a, n2);
fd1a1a2b 2647
dafd6cf6 2648 status_bar(dr, statusbuf);
fd1a1a2b 2649 }
2650
2ef96bd6 2651 sfree(active);
2652}
2653
be8d5aa1 2654static float game_anim_length(game_state *oldstate,
e3f21163 2655 game_state *newstate, int dir, game_ui *ui)
2ef96bd6 2656{
1185e3c5 2657 int last_rotate_dir;
2ef96bd6 2658
2659 /*
cbb5549e 2660 * Don't animate if last_rotate_dir is zero.
2ef96bd6 2661 */
cbb5549e 2662 last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2663 newstate->last_rotate_dir;
1185e3c5 2664 if (last_rotate_dir)
2665 return ROTATE_TIME;
2ef96bd6 2666
87ed82be 2667 return 0.0F;
2668}
2669
be8d5aa1 2670static float game_flash_length(game_state *oldstate,
e3f21163 2671 game_state *newstate, int dir, game_ui *ui)
87ed82be 2672{
2ef96bd6 2673 /*
87ed82be 2674 * If the game has just been completed, we display a completion
2675 * flash.
2ef96bd6 2676 */
2ac6d24e 2677 if (!oldstate->completed && newstate->completed &&
2678 !oldstate->used_solve && !newstate->used_solve) {
f0ee053c 2679 int size = 0;
2680 if (size < newstate->width)
2681 size = newstate->width;
2682 if (size < newstate->height)
2683 size = newstate->height;
87ed82be 2684 return FLASH_FRAME * (size+4);
2ef96bd6 2685 }
2686
87ed82be 2687 return 0.0F;
2ef96bd6 2688}
fd1a1a2b 2689
4d08de49 2690static int game_timing_state(game_state *state, game_ui *ui)
48dcdd62 2691{
2692 return TRUE;
2693}
2694
dafd6cf6 2695static void game_print_size(game_params *params, float *x, float *y)
2696{
2697 int pw, ph;
2698
2699 /*
2700 * I'll use 8mm squares by default.
2701 */
2702 game_compute_size(params, 800, &pw, &ph);
2703 *x = pw / 100.0;
2704 *y = ph / 100.0;
2705}
2706
2707static void draw_diagram(drawing *dr, game_drawstate *ds, int x, int y,
2708 int topleft, int v, int drawlines, int ink)
2709{
2710 int tx, ty, cx, cy, r, br, k, thick;
2711
2712 tx = WINDOW_OFFSET + TILE_SIZE * x;
2713 ty = WINDOW_OFFSET + TILE_SIZE * y;
2714
2715 /*
2716 * Find our centre point.
2717 */
2718 if (topleft) {
2719 cx = tx + (v & L ? TILE_SIZE / 4 : TILE_SIZE / 6);
2720 cy = ty + (v & U ? TILE_SIZE / 4 : TILE_SIZE / 6);
2721 r = TILE_SIZE / 8;
2722 br = TILE_SIZE / 32;
2723 } else {
2724 cx = tx + TILE_SIZE / 2;
2725 cy = ty + TILE_SIZE / 2;
2726 r = TILE_SIZE / 2;
2727 br = TILE_SIZE / 8;
2728 }
2729 thick = r / 20;
2730
2731 /*
2732 * Draw the square block if we have an endpoint.
2733 */
2734 if (v == 1 || v == 2 || v == 4 || v == 8)
2735 draw_rect(dr, cx - br, cy - br, br*2, br*2, ink);
2736
2737 /*
2738 * Draw each radial line.
2739 */
2740 if (drawlines) {
dafd6cf6 2741 for (k = 1; k < 16; k *= 2)
2742 if (v & k) {
2743 int x1 = min(cx, cx + (r-thick) * X(k));
2744 int x2 = max(cx, cx + (r-thick) * X(k));
2745 int y1 = min(cy, cy + (r-thick) * Y(k));
2746 int y2 = max(cy, cy + (r-thick) * Y(k));
2747 draw_rect(dr, x1 - thick, y1 - thick,
2748 (x2 - x1) + 2*thick, (y2 - y1) + 2*thick, ink);
2749 }
2750 }
2751}
2752
2753static void game_print(drawing *dr, game_state *state, int tilesize)
2754{
2755 int w = state->width, h = state->height;
2756 int ink = print_mono_colour(dr, 0);
2757 int x, y;
2758
2759 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2760 game_drawstate ads, *ds = &ads;
4413ef0f 2761 game_set_size(dr, ds, NULL, tilesize);
dafd6cf6 2762
2763 /*
2764 * Border.
2765 */
2766 print_line_width(dr, TILE_SIZE / (state->wrapping ? 128 : 12));
2767 draw_rect_outline(dr, WINDOW_OFFSET, WINDOW_OFFSET,
2768 TILE_SIZE * w, TILE_SIZE * h, ink);
2769
2770 /*
2771 * Grid.
2772 */
2773 print_line_width(dr, TILE_SIZE / 128);
2774 for (x = 1; x < w; x++)
2775 draw_line(dr, WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET,
2776 WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET + TILE_SIZE * h,
2777 ink);
2778 for (y = 1; y < h; y++)
2779 draw_line(dr, WINDOW_OFFSET, WINDOW_OFFSET + TILE_SIZE * y,
2780 WINDOW_OFFSET + TILE_SIZE * w, WINDOW_OFFSET + TILE_SIZE * y,
2781 ink);
2782
2783 /*
2784 * Barriers.
2785 */
2786 for (y = 0; y <= h; y++)
2787 for (x = 0; x <= w; x++) {
2788 int b = barrier(state, x % w, y % h);
dafd6cf6 2789 if (x < w && (b & U))
2790 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
2791 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
2792 TILE_SIZE + TILE_SIZE/24 * 2, TILE_SIZE/24 * 2, ink);
2793 if (y < h && (b & L))
2794 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
2795 WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
2796 TILE_SIZE/24 * 2, TILE_SIZE + TILE_SIZE/24 * 2, ink);
2797 }
2798
2799 /*
2800 * Grid contents.
2801 */
2802 for (y = 0; y < h; y++)
2803 for (x = 0; x < w; x++) {
2804 int vx, v = tile(state, x, y);
2805 int locked = v & LOCKED;
2806
2807 v &= 0xF;
2808
2809 /*
2810 * Rotate into a standard orientation for the top left
2811 * corner diagram.
2812 */
2813 vx = v;
2814 while (vx != 0 && vx != 15 && vx != 1 && vx != 9 && vx != 13 &&
2815 vx != 5)
2816 vx = A(vx);
2817
2818 /*
2819 * Draw the top left corner diagram.
2820 */
2821 draw_diagram(dr, ds, x, y, TRUE, vx, TRUE, ink);
2822
2823 /*
2824 * Draw the real solution diagram, if we're doing so.
2825 */
2826 draw_diagram(dr, ds, x, y, FALSE, v, locked, ink);
2827 }
2828}
2829
be8d5aa1 2830#ifdef COMBINED
2831#define thegame net
2832#endif
2833
2834const struct game thegame = {
750037d7 2835 "Net", "games.net", "net",
be8d5aa1 2836 default_params,
2837 game_fetch_preset,
2838 decode_params,
2839 encode_params,
2840 free_params,
2841 dup_params,
1d228b10 2842 TRUE, game_configure, custom_params,
be8d5aa1 2843 validate_params,
1185e3c5 2844 new_game_desc,
1185e3c5 2845 validate_desc,
be8d5aa1 2846 new_game,
2847 dup_game,
2848 free_game,
2ac6d24e 2849 TRUE, solve_game,
9b4b03d3 2850 FALSE, game_text_format,
be8d5aa1 2851 new_ui,
2852 free_ui,
ae8290c6 2853 encode_ui,
2854 decode_ui,
07dfb697 2855 game_changed_state,
df11cd4e 2856 interpret_move,
2857 execute_move,
1f3ee4ee 2858 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
be8d5aa1 2859 game_colours,
2860 game_new_drawstate,
2861 game_free_drawstate,
2862 game_redraw,
2863 game_anim_length,
2864 game_flash_length,
dafd6cf6 2865 TRUE, FALSE, game_print_size, game_print,
ac9f41c4 2866 TRUE, /* wants_statusbar */
48dcdd62 2867 FALSE, game_timing_state,
2705d374 2868 0, /* flags */
be8d5aa1 2869};