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