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