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