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