I've never trusted common variables. Take those bare ints out of
[sgt/puzzles] / unequal.c
CommitLineData
149255d7 1/*
2 * unequal.c
3 *
4 * Implementation of 'Futoshiki', a puzzle featured in the Guardian.
5 *
6 * TTD:
7 * add multiple-links-on-same-col/row solver nous
8 * Optimise set solver to use bit operations instead
9 *
10 * Guardian puzzles of note:
11 * #1: 5:0,0L,0L,0,0,0R,0,0L,0D,0L,0R,0,2,0D,0,0,0,0,0,0,0U,0,0,0,0U,
12 * #2: 5:0,0,0,4L,0L,0,2LU,0L,0U,0,0,0U,0,0,0,0,0D,0,3LRUD,0,0R,3,0L,0,0,
13 * #3: (reprint of #2)
14 * #4:
15 * #5: 5:0,0,0,0,0,0,2,0U,3U,0U,0,0,3,0,0,0,3,0D,4,0,0,0L,0R,0,0,
16 * #6: 5:0D,0L,0,0R,0,0,0D,0,3,0D,0,0R,0,0R,0D,0U,0L,0,1,2,0,0,0U,0,0L,
17 */
18
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <assert.h>
23#include <ctype.h>
24#include <math.h>
25
26#include "puzzles.h"
27#include "latin.h" /* contains typedef for digit */
28
29/* ----------------------------------------------------------
30 * Constant and structure definitions
31 */
32
33#define FLASH_TIME 0.4F
34
35#define PREFERRED_TILE_SIZE 32
36
37#define TILE_SIZE (ds->tilesize)
38#define GAP_SIZE (TILE_SIZE/2)
39#define SQUARE_SIZE (TILE_SIZE + GAP_SIZE)
40
41#define BORDER (TILE_SIZE / 2)
42
43#define COORD(x) ( (x) * SQUARE_SIZE + BORDER )
44#define FROMCOORD(x) ( ((x) - BORDER + SQUARE_SIZE) / SQUARE_SIZE - 1 )
45
46#define GRID(p,w,x,y) ((p)->w[((y)*(p)->order)+(x)])
47#define GRID3(p,w,x,y,z) ((p)->w[ (((x)*(p)->order+(y))*(p)->order+(z)) ])
48#define HINT(p,x,y,n) GRID3(p, hints, x, y, n)
49
50enum {
51 COL_BACKGROUND,
52 COL_GRID,
53 COL_TEXT, COL_GUESS, COL_ERROR, COL_PENCIL,
54 COL_HIGHLIGHT, COL_LOWLIGHT,
55 NCOLOURS
56};
57
58struct game_params {
34950d9f 59 int order; /* Size of latin square */
60 int diff; /* Difficulty */
61 int adjacent; /* Puzzle indicators are 'adjacent number'
62 not 'greater-than'. */
149255d7 63};
64
65#define F_IMMUTABLE 1 /* passed in as game description */
34950d9f 66#define F_ADJ_UP 2
67#define F_ADJ_RIGHT 4
68#define F_ADJ_DOWN 8
69#define F_ADJ_LEFT 16
149255d7 70#define F_ERROR 32
71#define F_ERROR_UP 64
72#define F_ERROR_RIGHT 128
73#define F_ERROR_DOWN 256
74#define F_ERROR_LEFT 512
75
76#define F_ERROR_MASK (F_ERROR|F_ERROR_UP|F_ERROR_RIGHT|F_ERROR_DOWN|F_ERROR_LEFT)
77
78struct game_state {
34950d9f 79 int order, completed, cheated, adjacent;
149255d7 80 digit *nums; /* actual numbers (size order^2) */
81 unsigned char *hints; /* remaining possiblities (size order^3) */
82 unsigned int *flags; /* flags (size order^2) */
83};
84
85/* ----------------------------------------------------------
86 * Game parameters and presets
87 */
88
89/* Steal the method from map.c for difficulty levels. */
388b2f00 90#define DIFFLIST(A) \
91 A(LATIN,Trivial,NULL,t) \
92 A(EASY,Easy,solver_easy, e) \
93 A(SET,Tricky,solver_set, k) \
94 A(EXTREME,Extreme,NULL,x) \
95 A(RECURSIVE,Recursive,NULL,r)
96
97#define ENUM(upper,title,func,lower) DIFF_ ## upper,
98#define TITLE(upper,title,func,lower) #title,
99#define ENCODE(upper,title,func,lower) #lower
100#define CONFIG(upper,title,func,lower) ":" #title
149255d7 101enum { DIFFLIST(ENUM) DIFF_IMPOSSIBLE = diff_impossible, DIFF_AMBIGUOUS = diff_ambiguous, DIFF_UNFINISHED = diff_unfinished };
102static char const *const unequal_diffnames[] = { DIFFLIST(TITLE) };
103static char const unequal_diffchars[] = DIFFLIST(ENCODE);
104#define DIFFCOUNT lenof(unequal_diffchars)
105#define DIFFCONFIG DIFFLIST(CONFIG)
106
107#define DEFAULT_PRESET 0
108
109const static struct game_params unequal_presets[] = {
34950d9f 110 { 4, DIFF_EASY, 0 },
111 { 5, DIFF_EASY, 0 },
112 { 5, DIFF_SET, 0 },
113 { 5, DIFF_SET, 1 },
114 { 5, DIFF_EXTREME, 0 },
115 { 6, DIFF_EASY, 0 },
116 { 6, DIFF_SET, 0 },
117 { 6, DIFF_SET, 1 },
118 { 6, DIFF_EXTREME, 0 },
119 { 7, DIFF_SET, 0 },
120 { 7, DIFF_SET, 1 },
121 { 7, DIFF_EXTREME, 0 }
149255d7 122};
123
124static int game_fetch_preset(int i, char **name, game_params **params)
125{
126 game_params *ret;
127 char buf[80];
128
129 if (i < 0 || i >= lenof(unequal_presets))
130 return FALSE;
131
132 ret = snew(game_params);
133 *ret = unequal_presets[i]; /* structure copy */
134
34950d9f 135 sprintf(buf, "%s: %dx%d %s",
136 ret->adjacent ? "Adjacent" : "Unequal",
137 ret->order, ret->order,
149255d7 138 unequal_diffnames[ret->diff]);
139
140 *name = dupstr(buf);
141 *params = ret;
142 return TRUE;
143}
144
145static game_params *default_params(void)
146{
147 game_params *ret;
148 char *name;
149
150 if (!game_fetch_preset(DEFAULT_PRESET, &name, &ret)) return NULL;
151 sfree(name);
152 return ret;
153}
154
155static void free_params(game_params *params)
156{
157 sfree(params);
158}
159
160static game_params *dup_params(game_params *params)
161{
162 game_params *ret = snew(game_params);
163 *ret = *params; /* structure copy */
164 return ret;
165}
166
167static void decode_params(game_params *ret, char const *string)
168{
169 char const *p = string;
170
171 ret->order = atoi(p);
172 while (*p && isdigit((unsigned char)*p)) p++;
173
34950d9f 174 if (*p == 'a') {
175 p++;
176 ret->adjacent = 1;
177 } else
178 ret->adjacent = 0;
179
149255d7 180 if (*p == 'd') {
181 int i;
182 p++;
183 ret->diff = DIFFCOUNT+1; /* ...which is invalid */
184 if (*p) {
185 for (i = 0; i < DIFFCOUNT; i++) {
186 if (*p == unequal_diffchars[i])
187 ret->diff = i;
188 }
189 p++;
190 }
191 }
192}
193
194static char *encode_params(game_params *params, int full)
195{
196 char ret[80];
197
198 sprintf(ret, "%d", params->order);
34950d9f 199 if (params->adjacent)
200 sprintf(ret + strlen(ret), "a");
149255d7 201 if (full)
202 sprintf(ret + strlen(ret), "d%c", unequal_diffchars[params->diff]);
203
204 return dupstr(ret);
205}
206
207static config_item *game_configure(game_params *params)
208{
209 config_item *ret;
210 char buf[80];
211
34950d9f 212 ret = snewn(4, config_item);
149255d7 213
34950d9f 214 ret[0].name = "Mode";
215 ret[0].type = C_CHOICES;
216 ret[0].sval = ":Unequal:Adjacent";
217 ret[0].ival = params->adjacent;
218
219 ret[1].name = "Size (s*s)";
220 ret[1].type = C_STRING;
149255d7 221 sprintf(buf, "%d", params->order);
34950d9f 222 ret[1].sval = dupstr(buf);
223 ret[1].ival = 0;
149255d7 224
34950d9f 225 ret[2].name = "Difficulty";
226 ret[2].type = C_CHOICES;
227 ret[2].sval = DIFFCONFIG;
228 ret[2].ival = params->diff;
149255d7 229
34950d9f 230 ret[3].name = NULL;
231 ret[3].type = C_END;
232 ret[3].sval = NULL;
233 ret[3].ival = 0;
149255d7 234
235 return ret;
236}
237
238static game_params *custom_params(config_item *cfg)
239{
240 game_params *ret = snew(game_params);
241
34950d9f 242 ret->adjacent = cfg[0].ival;
243 ret->order = atoi(cfg[1].sval);
244 ret->diff = cfg[2].ival;
149255d7 245
246 return ret;
247}
248
249static char *validate_params(game_params *params, int full)
250{
251 if (params->order < 3 || params->order > 32)
252 return "Order must be between 3 and 32";
253 if (params->diff >= DIFFCOUNT)
9c90045a 254 return "Unknown difficulty rating";
34950d9f 255 if (params->order < 5 && params->adjacent &&
256 params->diff >= DIFF_SET)
257 return "Order must be at least 5 for Adjacent puzzles of this difficulty.";
149255d7 258 return NULL;
259}
260
261/* ----------------------------------------------------------
262 * Various utility functions
263 */
264
34950d9f 265static const struct { unsigned int f, fo, fe; int dx, dy; char c, ac; } adjthan[] = {
266 { F_ADJ_UP, F_ADJ_DOWN, F_ERROR_UP, 0, -1, '^', '-' },
267 { F_ADJ_RIGHT, F_ADJ_LEFT, F_ERROR_RIGHT, 1, 0, '>', '|' },
268 { F_ADJ_DOWN, F_ADJ_UP, F_ERROR_DOWN, 0, 1, 'v', '-' },
269 { F_ADJ_LEFT, F_ADJ_RIGHT, F_ERROR_LEFT, -1, 0, '<', '|' }
149255d7 270};
271
34950d9f 272static game_state *blank_game(int order, int adjacent)
149255d7 273{
274 game_state *state = snew(game_state);
275 int o2 = order*order, o3 = o2*order;
276
277 state->order = order;
34950d9f 278 state->adjacent = adjacent;
149255d7 279 state->completed = state->cheated = 0;
280
281 state->nums = snewn(o2, digit);
282 state->hints = snewn(o3, unsigned char);
283 state->flags = snewn(o2, unsigned int);
284
285 memset(state->nums, 0, o2 * sizeof(digit));
286 memset(state->hints, 0, o3);
287 memset(state->flags, 0, o2 * sizeof(unsigned int));
288
289 return state;
290}
291
292static game_state *dup_game(game_state *state)
293{
34950d9f 294 game_state *ret = blank_game(state->order, state->adjacent);
149255d7 295 int o2 = state->order*state->order, o3 = o2*state->order;
296
297 memcpy(ret->nums, state->nums, o2 * sizeof(digit));
298 memcpy(ret->hints, state->hints, o3);
299 memcpy(ret->flags, state->flags, o2 * sizeof(unsigned int));
300
301 return ret;
302}
303
304static void free_game(game_state *state)
305{
306 sfree(state->nums);
307 sfree(state->hints);
308 sfree(state->flags);
309 sfree(state);
310}
311
312#define CHECKG(x,y) grid[(y)*o+(x)]
313
314/* Returns 0 if it finds an error, 1 otherwise. */
34950d9f 315static int check_num_adj(digit *grid, game_state *state,
149255d7 316 int x, int y, int me)
317{
318 unsigned int f = GRID(state, flags, x, y);
34950d9f 319 int ret = 1, i, o = state->order;
149255d7 320
321 for (i = 0; i < 4; i++) {
34950d9f 322 int dx = adjthan[i].dx, dy = adjthan[i].dy, n, dn;
323
324 if (x+dx < 0 || x+dx >= o || y+dy < 0 || y+dy >= o)
325 continue;
326
327 n = CHECKG(x, y);
328 dn = CHECKG(x+dx, y+dy);
329
330 assert (n != 0);
331 if (dn == 0) continue;
332
333 if (state->adjacent) {
334 int gd = abs(n-dn);
335
336 if ((f & adjthan[i].f) && (gd != 1)) {
337 debug(("check_adj error (%d,%d):%d should be | (%d,%d):%d",
338 x, y, n, x+dx, y+dy, dn));
339 if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
340 ret = 0;
341 }
342 if (!(f & adjthan[i].f) && (gd == 1)) {
343 debug(("check_adj error (%d,%d):%d should not be | (%d,%d):%d",
344 x, y, n, x+dx, y+dy, dn));
345 if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
346 ret = 0;
347 }
348
349 } else {
350 if ((f & adjthan[i].f) && (n <= dn)) {
351 debug(("check_adj error (%d,%d):%d not > (%d,%d):%d",
352 x, y, n, x+dx, y+dy, dn));
353 if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
354 ret = 0;
355 }
149255d7 356 }
357 }
358 return ret;
359}
360
361/* Returns 0 if it finds an error, 1 otherwise. */
362static int check_num_error(digit *grid, game_state *state,
363 int x, int y, int mark_errors)
364{
365 int o = state->order;
366 int xx, yy, val = CHECKG(x,y), ret = 1;
367
368 assert(val != 0);
369
370 /* check for dups in same column. */
371 for (yy = 0; yy < state->order; yy++) {
372 if (yy == y) continue;
373 if (CHECKG(x,yy) == val) ret = 0;
374 }
375
376 /* check for dups in same row. */
377 for (xx = 0; xx < state->order; xx++) {
378 if (xx == x) continue;
379 if (CHECKG(xx,y) == val) ret = 0;
380 }
381
382 if (!ret) {
383 debug(("check_num_error (%d,%d) duplicate %d", x, y, val));
384 if (mark_errors) GRID(state, flags, x, y) |= F_ERROR;
385 }
386 return ret;
387}
388
389/* Returns: -1 for 'wrong'
390 * 0 for 'incomplete'
391 * 1 for 'complete and correct'
392 */
393static int check_complete(digit *grid, game_state *state, int mark_errors)
394{
395 int x, y, ret = 1, o = state->order;
396
397 if (mark_errors)
398 assert(grid == state->nums);
399
400 for (x = 0; x < state->order; x++) {
401 for (y = 0; y < state->order; y++) {
402 if (mark_errors)
403 GRID(state, flags, x, y) &= ~F_ERROR_MASK;
404 if (grid[y*o+x] == 0) {
405 ret = 0;
406 } else {
407 if (!check_num_error(grid, state, x, y, mark_errors)) ret = -1;
34950d9f 408 if (!check_num_adj(grid, state, x, y, mark_errors)) ret = -1;
149255d7 409 }
410 }
411 }
412 if (ret == 1 && latin_check(grid, o))
413 ret = -1;
414 return ret;
415}
416
417static char n2c(digit n, int order) {
418 if (n == 0) return ' ';
419 if (order < 10) {
420 if (n < 10) return '0' + n;
421 } else {
422 if (n < 11) return '0' + n-1;
423 n -= 11;
424 if (n <= 26) return 'A' + n;
425 }
426 return '?';
427}
428
429/* should be 'digit', but includes -1 for 'not a digit'.
430 * Includes keypresses (0 especially) for interpret_move. */
431static int c2n(int c, int order) {
432 if (c < 0 || c > 0xff)
433 return -1;
7b97f218 434 if (c == ' ' || c == '\b')
149255d7 435 return 0;
436 if (order < 10) {
34950d9f 437 if (c >= '0' && c <= '9')
149255d7 438 return (int)(c - '0');
439 } else {
440 if (c >= '0' && c <= '9')
441 return (int)(c - '0' + 1);
442 if (c >= 'A' && c <= 'Z')
443 return (int)(c - 'A' + 11);
444 if (c >= 'a' && c <= 'z')
445 return (int)(c - 'a' + 11);
446 }
447 return -1;
448}
449
fa3abef5 450static int game_can_format_as_text_now(game_params *params)
451{
452 return TRUE;
453}
454
149255d7 455static char *game_text_format(game_state *state)
456{
457 int x, y, len, n;
458 char *ret, *p;
459
460 len = (state->order*2) * (state->order*2-1) + 1;
461 ret = snewn(len, char);
462 p = ret;
463
464 for (y = 0; y < state->order; y++) {
465 for (x = 0; x < state->order; x++) {
466 n = GRID(state, nums, x, y);
467 *p++ = n > 0 ? n2c(n, state->order) : '.';
468
469 if (x < (state->order-1)) {
34950d9f 470 if (state->adjacent) {
471 *p++ = (GRID(state, flags, x, y) & F_ADJ_RIGHT) ? '|' : ' ';
472 } else {
473 if (GRID(state, flags, x, y) & F_ADJ_RIGHT)
474 *p++ = '>';
475 else if (GRID(state, flags, x+1, y) & F_ADJ_LEFT)
476 *p++ = '<';
477 else
478 *p++ = ' ';
479 }
149255d7 480 }
481 }
482 *p++ = '\n';
483
484 if (y < (state->order-1)) {
485 for (x = 0; x < state->order; x++) {
34950d9f 486 if (state->adjacent) {
487 *p++ = (GRID(state, flags, x, y) & F_ADJ_DOWN) ? '-' : ' ';
488 } else {
489 if (GRID(state, flags, x, y) & F_ADJ_DOWN)
490 *p++ = 'v';
491 else if (GRID(state, flags, x, y+1) & F_ADJ_UP)
492 *p++ = '^';
493 else
494 *p++ = ' ';
495 }
149255d7 496
497 if (x < state->order-1)
498 *p++ = ' ';
499 }
500 *p++ = '\n';
501 }
502 }
503 *p++ = '\0';
504
505 assert(p - ret == len);
506 return ret;
507}
508
509#ifdef STANDALONE_SOLVER
510static void game_debug(game_state *state)
511{
512 char *dbg = game_text_format(state);
513 printf("%s", dbg);
514 sfree(dbg);
515}
516#endif
517
518/* ----------------------------------------------------------
519 * Solver.
520 */
521
522struct solver_link {
523 int len, gx, gy, lx, ly;
524};
525
388b2f00 526struct solver_ctx {
149255d7 527 game_state *state;
528
529 int nlinks, alinks;
530 struct solver_link *links;
388b2f00 531};
149255d7 532
388b2f00 533static void solver_add_link(struct solver_ctx *ctx,
149255d7 534 int gx, int gy, int lx, int ly, int len)
535{
388b2f00 536 if (ctx->alinks < ctx->nlinks+1) {
537 ctx->alinks = ctx->alinks*2 + 1;
538 /*debug(("resizing ctx->links, new size %d", ctx->alinks));*/
539 ctx->links = sresize(ctx->links, ctx->alinks, struct solver_link);
149255d7 540 }
388b2f00 541 ctx->links[ctx->nlinks].gx = gx;
542 ctx->links[ctx->nlinks].gy = gy;
543 ctx->links[ctx->nlinks].lx = lx;
544 ctx->links[ctx->nlinks].ly = ly;
545 ctx->links[ctx->nlinks].len = len;
546 ctx->nlinks++;
149255d7 547 /*debug(("Adding new link: len %d (%d,%d) < (%d,%d), nlinks now %d",
388b2f00 548 len, lx, ly, gx, gy, ctx->nlinks));*/
149255d7 549}
550
388b2f00 551static struct solver_ctx *new_ctx(game_state *state)
149255d7 552{
388b2f00 553 struct solver_ctx *ctx = snew(struct solver_ctx);
149255d7 554 int o = state->order;
555 int i, x, y;
556 unsigned int f;
557
388b2f00 558 ctx->nlinks = ctx->alinks = 0;
559 ctx->links = NULL;
560 ctx->state = state;
149255d7 561
388b2f00 562 if (state->adjacent) return ctx; /* adjacent mode doesn't use links. */
149255d7 563
564 for (x = 0; x < o; x++) {
565 for (y = 0; y < o; y++) {
566 f = GRID(state, flags, x, y);
567 for (i = 0; i < 4; i++) {
34950d9f 568 if (f & adjthan[i].f)
388b2f00 569 solver_add_link(ctx, x, y, x+adjthan[i].dx, y+adjthan[i].dy, 1);
149255d7 570 }
571 }
572 }
573
388b2f00 574 return ctx;
149255d7 575}
576
388b2f00 577static void *clone_ctx(void *vctx)
149255d7 578{
388b2f00 579 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
580 return new_ctx(ctx->state);
149255d7 581}
582
388b2f00 583static void free_ctx(void *vctx)
584{
585 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
586 if (ctx->links) sfree(ctx->links);
587 sfree(ctx);
588}
589
590static void solver_nminmax(struct latin_solver *solver,
149255d7 591 int x, int y, int *min_r, int *max_r,
592 unsigned char **ns_r)
593{
388b2f00 594 int o = solver->o, min = o, max = 0, n;
149255d7 595 unsigned char *ns;
596
597 assert(x >= 0 && y >= 0 && x < o && y < o);
598
599 ns = solver->cube + cubepos(x,y,1);
600
601 if (grid(x,y) > 0) {
602 min = max = grid(x,y)-1;
603 } else {
604 for (n = 0; n < o; n++) {
605 if (ns[n]) {
606 if (n > max) max = n;
607 if (n < min) min = n;
608 }
609 }
610 }
611 if (min_r) *min_r = min;
612 if (max_r) *max_r = max;
613 if (ns_r) *ns_r = ns;
614}
615
388b2f00 616static int solver_links(struct latin_solver *solver, void *vctx)
149255d7 617{
388b2f00 618 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
149255d7 619 int i, j, lmin, gmax, nchanged = 0;
620 unsigned char *gns, *lns;
621 struct solver_link *link;
149255d7 622
388b2f00 623 for (i = 0; i < ctx->nlinks; i++) {
624 link = &ctx->links[i];
625 solver_nminmax(solver, link->gx, link->gy, NULL, &gmax, &gns);
626 solver_nminmax(solver, link->lx, link->ly, &lmin, NULL, &lns);
149255d7 627
628 for (j = 0; j < solver->o; j++) {
629 /* For the 'greater' end of the link, discount all numbers
630 * too small to satisfy the inequality. */
631 if (gns[j]) {
632 if (j < (lmin+link->len)) {
633#ifdef STANDALONE_SOLVER
634 if (solver_show_working) {
635 printf("%*slink elimination, (%d,%d) > (%d,%d):\n",
636 solver_recurse_depth*4, "",
637 link->gx, link->gy, link->lx, link->ly);
638 printf("%*s ruling out %d at (%d,%d)\n",
639 solver_recurse_depth*4, "",
640 j+1, link->gx, link->gy);
641 }
642#endif
643 cube(link->gx, link->gy, j+1) = FALSE;
644 nchanged++;
645 }
646 }
647 /* For the 'lesser' end of the link, discount all numbers
648 * too large to satisfy inequality. */
649 if (lns[j]) {
650 if (j > (gmax-link->len)) {
651#ifdef STANDALONE_SOLVER
652 if (solver_show_working) {
653 printf("%*slink elimination, (%d,%d) > (%d,%d):\n",
654 solver_recurse_depth*4, "",
655 link->gx, link->gy, link->lx, link->ly);
656 printf("%*s ruling out %d at (%d,%d)\n",
657 solver_recurse_depth*4, "",
658 j+1, link->lx, link->ly);
659 }
660#endif
661 cube(link->lx, link->ly, j+1) = FALSE;
662 nchanged++;
663 }
664 }
665 }
666 }
667 return nchanged;
668}
669
388b2f00 670static int solver_adjacent(struct latin_solver *solver, void *vctx)
34950d9f 671{
388b2f00 672 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
673 int nchanged = 0, x, y, i, n, o = solver->o, nx, ny, gd;
34950d9f 674
675 /* Update possible values based on known values and adjacency clues. */
676
677 for (x = 0; x < o; x++) {
678 for (y = 0; y < o; y++) {
679 if (grid(x, y) == 0) continue;
680
681 /* We have a definite number here. Make sure that any
682 * adjacent possibles reflect the adjacent/non-adjacent clue. */
683
684 for (i = 0; i < 4; i++) {
388b2f00 685 int isadjacent = (GRID(ctx->state, flags, x, y) & adjthan[i].f);
34950d9f 686
687 nx = x + adjthan[i].dx, ny = y + adjthan[i].dy;
688 if (nx < 0 || ny < 0 || nx >= o || ny >= o)
689 continue;
690
691 for (n = 0; n < o; n++) {
692 /* Continue past numbers the adjacent square _could_ be,
693 * given the clue we have. */
694 gd = abs((n+1) - grid(x, y));
695 if (isadjacent && (gd == 1)) continue;
696 if (!isadjacent && (gd != 1)) continue;
697
698 if (cube(nx, ny, n+1) == FALSE)
699 continue; /* already discounted this possibility. */
700
701#ifdef STANDALONE_SOLVER
702 if (solver_show_working) {
703 printf("%*sadjacent elimination, (%d,%d):%d %s (%d,%d):\n",
704 solver_recurse_depth*4, "",
705 x, y, grid(x, y), isadjacent ? "|" : "!|", nx, ny);
706 printf("%*s ruling out %d at (%d,%d)\n",
707 solver_recurse_depth*4, "", n+1, nx, ny);
708 }
709#endif
710 cube(nx, ny, n+1) = FALSE;
711 nchanged++;
712 }
713 }
714 }
715 }
716
717 return nchanged;
718}
719
388b2f00 720static int solver_adjacent_set(struct latin_solver *solver, void *vctx)
34950d9f 721{
388b2f00 722 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
723 int x, y, i, n, nn, o = solver->o, nx, ny, gd;
34950d9f 724 int nchanged = 0, *scratch = snewn(o, int);
725
726 /* Update possible values based on other possible values
727 * of adjacent squares, and adjacency clues. */
728
729 for (x = 0; x < o; x++) {
730 for (y = 0; y < o; y++) {
731 for (i = 0; i < o; i++) {
388b2f00 732 int isadjacent = (GRID(ctx->state, flags, x, y) & adjthan[i].f);
34950d9f 733
734 nx = x + adjthan[i].dx, ny = y + adjthan[i].dy;
735 if (nx < 0 || ny < 0 || nx >= o || ny >= o)
736 continue;
737
738 /* We know the current possibles for the square (x,y)
739 * and also the adjacency clue from (x,y) to (nx,ny).
740 * Construct a maximum set of possibles for (nx,ny)
741 * in scratch, based on these constraints... */
742
743 memset(scratch, 0, o*sizeof(int));
744
745 for (n = 0; n < o; n++) {
746 if (cube(x, y, n+1) == FALSE) continue;
747
748 for (nn = 0; nn < o; nn++) {
749 if (n == nn) continue;
750
751 gd = abs(nn - n);
752 if (isadjacent && (gd != 1)) continue;
753 if (!isadjacent && (gd == 1)) continue;
754
755 scratch[nn] = 1;
756 }
757 }
758
759 /* ...and remove any possibilities for (nx,ny) that are
760 * currently set but are not indicated in scratch. */
761 for (n = 0; n < o; n++) {
762 if (scratch[n] == 1) continue;
763 if (cube(nx, ny, n+1) == FALSE) continue;
764
765#ifdef STANDALONE_SOLVER
766 if (solver_show_working) {
767 printf("%*sadjacent possible elimination, (%d,%d) %s (%d,%d):\n",
768 solver_recurse_depth*4, "",
769 x, y, isadjacent ? "|" : "!|", nx, ny);
770 printf("%*s ruling out %d at (%d,%d)\n",
771 solver_recurse_depth*4, "", n+1, nx, ny);
772 }
773#endif
774 cube(nx, ny, n+1) = FALSE;
775 nchanged++;
776 }
777 }
778 }
779 }
780
781 return nchanged;
782}
783
388b2f00 784static int solver_easy(struct latin_solver *solver, void *vctx)
149255d7 785{
388b2f00 786 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
787 if (ctx->state->adjacent)
788 return solver_adjacent(solver, vctx);
789 else
790 return solver_links(solver, vctx);
791}
149255d7 792
388b2f00 793static int solver_set(struct latin_solver *solver, void *vctx)
794{
795 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
796 if (ctx->state->adjacent)
797 return solver_adjacent_set(solver, vctx);
798 else
799 return 0;
800}
481628b3 801
388b2f00 802#define SOLVER(upper,title,func,lower) func,
803static usersolver_t const unequal_solvers[] = { DIFFLIST(SOLVER) };
149255d7 804
388b2f00 805static int solver_state(game_state *state, int maxdiff)
806{
807 struct solver_ctx *ctx = new_ctx(state);
808 struct latin_solver solver;
809 int diff;
149255d7 810
388b2f00 811 latin_solver_alloc(&solver, state->nums, state->order);
149255d7 812
388b2f00 813 diff = latin_solver_main(&solver, maxdiff,
814 DIFF_LATIN, DIFF_SET, DIFF_EXTREME,
815 DIFF_EXTREME, DIFF_RECURSIVE,
816 unequal_solvers, ctx, clone_ctx, free_ctx);
149255d7 817
388b2f00 818 memcpy(state->hints, solver.cube, state->order*state->order*state->order);
149255d7 819
388b2f00 820 free_ctx(ctx);
149255d7 821
388b2f00 822 latin_solver_free(&solver);
149255d7 823
824 if (diff == DIFF_IMPOSSIBLE)
825 return -1;
826 if (diff == DIFF_UNFINISHED)
827 return 0;
828 if (diff == DIFF_AMBIGUOUS)
829 return 2;
830 return 1;
831}
832
833static game_state *solver_hint(game_state *state, int *diff_r, int mindiff, int maxdiff)
834{
835 game_state *ret = dup_game(state);
836 int diff, r = 0;
837
838 for (diff = mindiff; diff <= maxdiff; diff++) {
839 r = solver_state(ret, diff);
840 debug(("solver_state after %s %d", unequal_diffnames[diff], r));
841 if (r != 0) goto done;
842 }
843
844done:
845 if (diff_r) *diff_r = (r > 0) ? diff : -1;
846 return ret;
847}
848
849/* ----------------------------------------------------------
850 * Game generation.
851 */
852
853static char *latin_desc(digit *sq, size_t order)
854{
855 int o2 = order*order, i;
856 char *soln = snewn(o2+2, char);
857
858 soln[0] = 'S';
859 for (i = 0; i < o2; i++)
860 soln[i+1] = n2c(sq[i], order);
861 soln[o2+1] = '\0';
862
863 return soln;
864}
865
866/* returns non-zero if it placed (or could have placed) clue. */
867static int gg_place_clue(game_state *state, int ccode, digit *latin, int checkonly)
868{
869 int loc = ccode / 5, which = ccode % 5;
870 int x = loc % state->order, y = loc / state->order;
871
872 assert(loc < state->order*state->order);
873
874 if (which == 4) { /* add number */
875 if (state->nums[loc] != 0) {
876#ifdef STANDALONE_SOLVER
877 if (state->nums[loc] != latin[loc]) {
878 printf("inconsistency for (%d,%d): state %d latin %d\n",
879 x, y, state->nums[loc], latin[loc]);
880 }
881#endif
882 assert(state->nums[loc] == latin[loc]);
883 return 0;
884 }
885 if (!checkonly) {
886 state->nums[loc] = latin[loc];
887 }
888 } else { /* add flag */
889 int lx, ly, lloc;
890
34950d9f 891 if (state->adjacent)
892 return 0; /* never add flag clues in adjacent mode (they're always
893 all present) */
894
895 if (state->flags[loc] & adjthan[which].f)
149255d7 896 return 0; /* already has flag. */
897
34950d9f 898 lx = x + adjthan[which].dx;
899 ly = y + adjthan[which].dy;
149255d7 900 if (lx < 0 || ly < 0 || lx >= state->order || ly >= state->order)
901 return 0; /* flag compares to off grid */
902
34950d9f 903 lloc = loc + adjthan[which].dx + adjthan[which].dy*state->order;
149255d7 904 if (latin[loc] <= latin[lloc])
905 return 0; /* flag would be incorrect */
906
907 if (!checkonly) {
34950d9f 908 state->flags[loc] |= adjthan[which].f;
149255d7 909 }
910 }
911 return 1;
912}
913
914/* returns non-zero if it removed (or could have removed) the clue. */
915static int gg_remove_clue(game_state *state, int ccode, int checkonly)
916{
917 int loc = ccode / 5, which = ccode % 5;
918#ifdef STANDALONE_SOLVER
919 int x = loc % state->order, y = loc / state->order;
920#endif
921
922 assert(loc < state->order*state->order);
923
924 if (which == 4) { /* remove number. */
925 if (state->nums[loc] == 0) return 0;
926 if (!checkonly) {
927#ifdef STANDALONE_SOLVER
928 if (solver_show_working)
929 printf("gg_remove_clue: removing %d at (%d,%d)",
930 state->nums[loc], x, y);
931#endif
932 state->nums[loc] = 0;
933 }
934 } else { /* remove flag */
34950d9f 935 if (state->adjacent)
936 return 0; /* never remove clues in adjacent mode. */
937
938 if (!(state->flags[loc] & adjthan[which].f)) return 0;
149255d7 939 if (!checkonly) {
940#ifdef STANDALONE_SOLVER
941 if (solver_show_working)
942 printf("gg_remove_clue: removing %c at (%d,%d)",
34950d9f 943 adjthan[which].c, x, y);
149255d7 944#endif
34950d9f 945 state->flags[loc] &= ~adjthan[which].f;
149255d7 946 }
947 }
948 return 1;
949}
950
951static int gg_best_clue(game_state *state, int *scratch, digit *latin)
952{
953 int ls = state->order * state->order * 5;
954 int maxposs = 0, minclues = 5, best = -1, i, j;
955 int nposs, nclues, loc, x, y;
956
957#ifdef STANDALONE_SOLVER
958 if (solver_show_working) {
959 game_debug(state);
960 latin_solver_debug(state->hints, state->order);
961 }
962#endif
963
242a7d91 964 for (i = ls; i-- > 0 ;) {
149255d7 965 if (!gg_place_clue(state, scratch[i], latin, 1)) continue;
966
967 loc = scratch[i] / 5;
968 x = loc % state->order; y = loc / state->order;
969 for (j = nposs = 0; j < state->order; j++) {
970 if (state->hints[loc*state->order + j]) nposs++;
971 }
972 for (j = nclues = 0; j < 4; j++) {
34950d9f 973 if (state->flags[loc] & adjthan[j].f) nclues++;
149255d7 974 }
975 if ((nposs > maxposs) ||
976 (nposs == maxposs && nclues < minclues)) {
977 best = i; maxposs = nposs; minclues = nclues;
978#ifdef STANDALONE_SOLVER
979 if (solver_show_working)
807a3bee 980 printf("gg_best_clue: b%d (%d,%d) new best [%d poss, %d clues].\n",
149255d7 981 best, x, y, nposs, nclues);
982#endif
983 }
984 }
985 /* if we didn't solve, we must have 1 clue to place! */
986 assert(best != -1);
987 return best;
988}
989
990#ifdef STANDALONE_SOLVER
991int maxtries;
992#define MAXTRIES maxtries
993#else
994#define MAXTRIES 50
995#endif
996int gg_solved;
997
998static int game_assemble(game_state *new, int *scratch, digit *latin,
999 int difficulty)
1000{
1001 game_state *copy = dup_game(new);
1002 int best;
1003
1004 if (difficulty >= DIFF_RECURSIVE) {
1005 /* We mustn't use any solver that might guess answers;
1006 * if it guesses wrongly but solves, gg_place_clue will
1007 * get mighty confused. We will always trim clues down
1008 * (making it more difficult) in game_strip, which doesn't
1009 * have this problem. */
1010 difficulty = DIFF_RECURSIVE-1;
1011 }
1012
1013#ifdef STANDALONE_SOLVER
1014 if (solver_show_working) {
1015 game_debug(new);
1016 latin_solver_debug(new->hints, new->order);
1017 }
1018#endif
1019
1020 while(1) {
1021 gg_solved++;
1022 if (solver_state(copy, difficulty) == 1) break;
1023
1024 best = gg_best_clue(copy, scratch, latin);
1025 gg_place_clue(new, scratch[best], latin, 0);
1026 gg_place_clue(copy, scratch[best], latin, 0);
1027 }
1028 free_game(copy);
1029#ifdef STANDALONE_SOLVER
1030 if (solver_show_working) {
1031 char *dbg = game_text_format(new);
1032 printf("game_assemble: done, %d solver iterations:\n%s\n", gg_solved, dbg);
1033 sfree(dbg);
1034 }
1035#endif
1036 return 0;
1037}
1038
1039static void game_strip(game_state *new, int *scratch, digit *latin,
1040 int difficulty)
1041{
1042 int o = new->order, o2 = o*o, lscratch = o2*5, i;
34950d9f 1043 game_state *copy = blank_game(new->order, new->adjacent);
149255d7 1044
1045 /* For each symbol (if it exists in new), try and remove it and
1046 * solve again; if we couldn't solve without it put it back. */
1047 for (i = 0; i < lscratch; i++) {
1048 if (!gg_remove_clue(new, scratch[i], 0)) continue;
1049
1050 memcpy(copy->nums, new->nums, o2 * sizeof(digit));
1051 memcpy(copy->flags, new->flags, o2 * sizeof(unsigned int));
1052 gg_solved++;
1053 if (solver_state(copy, difficulty) != 1) {
1054 /* put clue back, we can't solve without it. */
242a7d91 1055 int ret = gg_place_clue(new, scratch[i], latin, 0);
1056 assert(ret == 1);
149255d7 1057 } else {
1058#ifdef STANDALONE_SOLVER
1059 if (solver_show_working)
1060 printf("game_strip: clue was redundant.");
1061#endif
1062 }
1063 }
1064 free_game(copy);
1065#ifdef STANDALONE_SOLVER
1066 if (solver_show_working) {
1067 char *dbg = game_text_format(new);
1068 debug(("game_strip: done, %d solver iterations.", gg_solved));
1069 debug(("%s", dbg));
1070 sfree(dbg);
1071 }
1072#endif
1073}
1074
34950d9f 1075static void add_adjacent_flags(game_state *state, digit *latin)
1076{
1077 int x, y, o = state->order;
1078
1079 /* All clues in adjacent mode are always present (the only variables are
1080 * the numbers). This adds all the flags to state based on the supplied
1081 * latin square. */
1082
1083 for (y = 0; y < o; y++) {
1084 for (x = 0; x < o; x++) {
1085 if (x < (o-1) && (abs(latin[y*o+x] - latin[y*o+x+1]) == 1)) {
1086 GRID(state, flags, x, y) |= F_ADJ_RIGHT;
1087 GRID(state, flags, x+1, y) |= F_ADJ_LEFT;
1088 }
1089 if (y < (o-1) && (abs(latin[y*o+x] - latin[(y+1)*o+x]) == 1)) {
1090 GRID(state, flags, x, y) |= F_ADJ_DOWN;
1091 GRID(state, flags, x, y+1) |= F_ADJ_UP;
1092 }
1093 }
1094 }
1095}
1096
149255d7 1097static char *new_game_desc(game_params *params, random_state *rs,
1098 char **aux, int interactive)
1099{
1100 digit *sq = NULL;
1101 int i, x, y, retlen, k, nsol;
807a3bee 1102 int o2 = params->order * params->order, ntries = 1;
149255d7 1103 int *scratch, lscratch = o2*5;
1104 char *ret, buf[80];
34950d9f 1105 game_state *state = blank_game(params->order, params->adjacent);
149255d7 1106
1107 /* Generate a list of 'things to strip' (randomised later) */
1108 scratch = snewn(lscratch, int);
242a7d91 1109 /* Put the numbers (4 mod 5) before the inequalities (0-3 mod 5) */
1110 for (i = 0; i < lscratch; i++) scratch[i] = (i%o2)*5 + 4 - (i/o2);
149255d7 1111
1112generate:
1113#ifdef STANDALONE_SOLVER
1114 if (solver_show_working)
34950d9f 1115 printf("new_game_desc: generating %s puzzle, ntries so far %d\n",
149255d7 1116 unequal_diffnames[params->diff], ntries);
1117#endif
1118 if (sq) sfree(sq);
1119 sq = latin_generate(params->order, rs);
1120 latin_debug(sq, params->order);
242a7d91 1121 /* Separately shuffle the numeric and inequality clues */
1122 shuffle(scratch, lscratch/5, sizeof(int), rs);
1123 shuffle(scratch+lscratch/5, 4*lscratch/5, sizeof(int), rs);
149255d7 1124
1125 memset(state->nums, 0, o2 * sizeof(digit));
1126 memset(state->flags, 0, o2 * sizeof(unsigned int));
1127
34950d9f 1128 if (state->adjacent) {
1129 /* All adjacency flags are always present. */
1130 add_adjacent_flags(state, sq);
1131 }
1132
149255d7 1133 gg_solved = 0;
1134 if (game_assemble(state, scratch, sq, params->diff) < 0)
1135 goto generate;
1136 game_strip(state, scratch, sq, params->diff);
1137
1138 if (params->diff > 0) {
1139 game_state *copy = dup_game(state);
1140 nsol = solver_state(copy, params->diff-1);
1141 free_game(copy);
1142 if (nsol > 0) {
1143#ifdef STANDALONE_SOLVER
1144 if (solver_show_working)
807a3bee 1145 printf("game_assemble: puzzle as generated is too easy.\n");
149255d7 1146#endif
1147 if (ntries < MAXTRIES) {
1148 ntries++;
1149 goto generate;
1150 }
1151#ifdef STANDALONE_SOLVER
1152 if (solver_show_working)
807a3bee 1153 printf("Unable to generate %s %dx%d after %d attempts.\n",
149255d7 1154 unequal_diffnames[params->diff],
1155 params->order, params->order, MAXTRIES);
1156#endif
1157 params->diff--;
1158 }
1159 }
1160#ifdef STANDALONE_SOLVER
1161 if (solver_show_working)
807a3bee 1162 printf("new_game_desc: generated %s puzzle; %d attempts (%d solver).\n",
149255d7 1163 unequal_diffnames[params->diff], ntries, gg_solved);
1164#endif
1165
1166 ret = NULL; retlen = 0;
1167 for (y = 0; y < params->order; y++) {
1168 for (x = 0; x < params->order; x++) {
1169 unsigned int f = GRID(state, flags, x, y);
1170 k = sprintf(buf, "%d%s%s%s%s,",
1171 GRID(state, nums, x, y),
34950d9f 1172 (f & F_ADJ_UP) ? "U" : "",
1173 (f & F_ADJ_RIGHT) ? "R" : "",
1174 (f & F_ADJ_DOWN) ? "D" : "",
1175 (f & F_ADJ_LEFT) ? "L" : "");
149255d7 1176
1177 ret = sresize(ret, retlen + k + 1, char);
1178 strcpy(ret + retlen, buf);
1179 retlen += k;
1180 }
1181 }
1182 *aux = latin_desc(sq, params->order);
1183
1184 free_game(state);
1185 sfree(sq);
1186 sfree(scratch);
1187
1188 return ret;
1189}
1190
1191static game_state *load_game(game_params *params, char *desc,
1192 char **why_r)
1193{
34950d9f 1194 game_state *state = blank_game(params->order, params->adjacent);
149255d7 1195 char *p = desc;
1196 int i = 0, n, o = params->order, x, y;
1197 char *why = NULL;
1198
1199 while (*p) {
1200 while (*p >= 'a' && *p <= 'z') {
1201 i += *p - 'a' + 1;
1202 p++;
1203 }
1204 if (i >= o*o) {
1205 why = "Too much data to fill grid"; goto fail;
1206 }
1207
1208 if (*p < '0' && *p > '9') {
1209 why = "Expecting number in game description"; goto fail;
1210 }
1211 n = atoi(p);
1212 if (n < 0 || n > o) {
1213 why = "Out-of-range number in game description"; goto fail;
1214 }
1215 state->nums[i] = (digit)n;
1216 while (*p >= '0' && *p <= '9') p++; /* skip number */
1217
1218 if (state->nums[i] != 0)
1219 state->flags[i] |= F_IMMUTABLE; /* === number set by game description */
1220
1221 while (*p == 'U' || *p == 'R' || *p == 'D' || *p == 'L') {
1222 switch (*p) {
34950d9f 1223 case 'U': state->flags[i] |= F_ADJ_UP; break;
1224 case 'R': state->flags[i] |= F_ADJ_RIGHT; break;
1225 case 'D': state->flags[i] |= F_ADJ_DOWN; break;
1226 case 'L': state->flags[i] |= F_ADJ_LEFT; break;
149255d7 1227 default: why = "Expecting flag URDL in game description"; goto fail;
1228 }
1229 p++;
1230 }
1231 i++;
1232 if (i < o*o && *p != ',') {
1233 why = "Missing separator"; goto fail;
1234 }
1235 if (*p == ',') p++;
1236 }
1237 if (i < o*o) {
1238 why = "Not enough data to fill grid"; goto fail;
1239 }
1240 i = 0;
1241 for (y = 0; y < o; y++) {
1242 for (x = 0; x < o; x++) {
1243 for (n = 0; n < 4; n++) {
34950d9f 1244 if (GRID(state, flags, x, y) & adjthan[n].f) {
1245 int nx = x + adjthan[n].dx;
1246 int ny = y + adjthan[n].dy;
149255d7 1247 /* a flag must not point us off the grid. */
1248 if (nx < 0 || ny < 0 || nx >= o || ny >= o) {
1249 why = "Flags go off grid"; goto fail;
1250 }
34950d9f 1251 if (params->adjacent) {
1252 /* if one cell is adjacent to another, the other must
1253 * also be adjacent to the first. */
1254 if (!(GRID(state, flags, nx, ny) & adjthan[n].fo)) {
1255 why = "Flags contradicting each other"; goto fail;
1256 }
1257 } else {
1258 /* if one cell is GT another, the other must _not_ also
1259 * be GT the first. */
1260 if (GRID(state, flags, nx, ny) & adjthan[n].fo) {
1261 why = "Flags contradicting each other"; goto fail;
1262 }
149255d7 1263 }
1264 }
1265 }
1266 }
1267 }
1268
1269 return state;
1270
1271fail:
1272 free_game(state);
1273 if (why_r) *why_r = why;
1274 return NULL;
1275}
1276
1277static game_state *new_game(midend *me, game_params *params, char *desc)
1278{
1279 game_state *state = load_game(params, desc, NULL);
1280 if (!state) {
1281 assert("Unable to load ?validated game.");
1282 return NULL;
1283 }
1284 return state;
1285}
1286
1287static char *validate_desc(game_params *params, char *desc)
1288{
1289 char *why = NULL;
1290 game_state *dummy = load_game(params, desc, &why);
1291 if (dummy) {
1292 free_game(dummy);
1293 assert(!why);
1294 } else
1295 assert(why);
1296 return why;
1297}
1298
1299static char *solve_game(game_state *state, game_state *currstate,
1300 char *aux, char **error)
1301{
1302 game_state *solved;
1303 int r;
1304 char *ret = NULL;
1305
1306 if (aux) return dupstr(aux);
1307
1308 solved = dup_game(state);
1309 for (r = 0; r < state->order*state->order; r++) {
1310 if (!(solved->flags[r] & F_IMMUTABLE))
1311 solved->nums[r] = 0;
1312 }
1313 r = solver_state(solved, DIFFCOUNT);
1314 if (r > 0) ret = latin_desc(solved->nums, solved->order);
1315 free_game(solved);
1316 return ret;
1317}
1318
1319/* ----------------------------------------------------------
1320 * Game UI input processing.
1321 */
1322
1323struct game_ui {
9c90045a 1324 int hx, hy; /* as for solo.c, highlight pos */
1325 int hshow, hpencil, hcursor; /* show state, type, and ?cursor. */
149255d7 1326};
1327
1328static game_ui *new_ui(game_state *state)
1329{
1330 game_ui *ui = snew(game_ui);
1331
9c90045a 1332 ui->hx = ui->hy = 0;
1333 ui->hpencil = ui->hshow = ui->hcursor = 0;
149255d7 1334
1335 return ui;
1336}
1337
1338static void free_ui(game_ui *ui)
1339{
1340 sfree(ui);
1341}
1342
1343static char *encode_ui(game_ui *ui)
1344{
1345 return NULL;
1346}
1347
1348static void decode_ui(game_ui *ui, char *encoding)
1349{
1350}
1351
1352static void game_changed_state(game_ui *ui, game_state *oldstate,
1353 game_state *newstate)
1354{
1355 /* See solo.c; if we were pencil-mode highlighting and
1356 * somehow a square has just been properly filled, cancel
1357 * pencil mode. */
9c90045a 1358 if (ui->hshow && ui->hpencil && !ui->hcursor &&
149255d7 1359 GRID(newstate, nums, ui->hx, ui->hy) != 0) {
9c90045a 1360 ui->hshow = 0;
149255d7 1361 }
1362}
1363
1364struct game_drawstate {
34950d9f 1365 int tilesize, order, started, adjacent;
9c90045a 1366 digit *nums; /* copy of nums, o^2 */
1367 unsigned char *hints; /* copy of hints, o^3 */
149255d7 1368 unsigned int *flags; /* o^2 */
1369
9c90045a 1370 int hx, hy, hshow, hpencil; /* as for game_ui. */
149255d7 1371 int hflash;
1372};
1373
1374static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1375 int ox, int oy, int button)
1376{
1377 int x = FROMCOORD(ox), y = FROMCOORD(oy), n;
1378 char buf[80];
1379
1380 button &= ~MOD_MASK;
1381
84f7de6d 1382 if (x >= 0 && x < ds->order && ((ox - COORD(x)) <= TILE_SIZE) &&
1383 y >= 0 && y < ds->order && ((oy - COORD(y)) <= TILE_SIZE)) {
149255d7 1384 if (button == LEFT_BUTTON) {
1385 /* normal highlighting for non-immutable squares */
1386 if (GRID(state, flags, x, y) & F_IMMUTABLE)
9c90045a 1387 ui->hshow = 0;
1388 else if (x == ui->hx && y == ui->hy &&
1389 ui->hshow && ui->hpencil == 0)
1390 ui->hshow = 0;
149255d7 1391 else {
1392 ui->hx = x; ui->hy = y; ui->hpencil = 0;
9c90045a 1393 ui->hshow = 1;
149255d7 1394 }
9c90045a 1395 ui->hcursor = 0;
149255d7 1396 return "";
1397 }
1398 if (button == RIGHT_BUTTON) {
1399 /* pencil highlighting for non-filled squares */
1400 if (GRID(state, nums, x, y) != 0)
9c90045a 1401 ui->hshow = 0;
1402 else if (x == ui->hx && y == ui->hy &&
1403 ui->hshow && ui->hpencil)
1404 ui->hshow = 0;
149255d7 1405 else {
1406 ui->hx = x; ui->hy = y; ui->hpencil = 1;
9c90045a 1407 ui->hshow = 1;
149255d7 1408 }
9c90045a 1409 ui->hcursor = 0;
149255d7 1410 return "";
1411 }
1412 }
9c90045a 1413
1414 if (IS_CURSOR_MOVE(button)) {
1415 move_cursor(button, &ui->hx, &ui->hy, ds->order, ds->order, 0);
1416 ui->hshow = ui->hcursor = 1;
1417 return "";
1418 }
1419 if (ui->hshow && IS_CURSOR_SELECT(button)) {
1420 ui->hpencil = 1 - ui->hpencil;
1421 ui->hcursor = 1;
1422 return "";
1423 }
1424
149255d7 1425
9c90045a 1426 if (ui->hshow) {
149255d7 1427 debug(("button %d, cbutton %d", button, (int)((char)button)));
1428 n = c2n(button, state->order);
1429
1430 debug(("n %d, h (%d,%d) p %d flags 0x%x nums %d",
1431 n, ui->hx, ui->hy, ui->hpencil,
1432 GRID(state, flags, ui->hx, ui->hy),
1433 GRID(state, nums, ui->hx, ui->hy)));
1434
1435 if (n < 0 || n > ds->order)
1436 return NULL; /* out of range */
1437 if (GRID(state, flags, ui->hx, ui->hy) & F_IMMUTABLE)
1438 return NULL; /* can't edit immutable square (!) */
1439 if (ui->hpencil && GRID(state, nums, ui->hx, ui->hy) > 0)
1440 return NULL; /* can't change hints on filled square (!) */
1441
1442
1443 sprintf(buf, "%c%d,%d,%d",
1444 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1445
9c90045a 1446 if (!ui->hcursor) ui->hshow = 0;
149255d7 1447
1448 return dupstr(buf);
1449 }
03b9ec27 1450
1451 if (button == 'H' || button == 'h')
1452 return dupstr("H");
1453 if (button == 'M' || button == 'm')
1454 return dupstr("M");
1455
149255d7 1456 return NULL;
1457}
1458
1459static game_state *execute_move(game_state *state, char *move)
1460{
1461 game_state *ret = NULL;
242a7d91 1462 int x, y, n, i, rc;
149255d7 1463
1464 debug(("execute_move: %s", move));
1465
1466 if ((move[0] == 'P' || move[0] == 'R') &&
1467 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1468 x >= 0 && x < state->order && y >= 0 && y < state->order &&
1469 n >= 0 && n <= state->order) {
1470 ret = dup_game(state);
1471 if (move[0] == 'P' && n > 0)
1472 HINT(ret, x, y, n-1) = !HINT(ret, x, y, n-1);
1473 else {
1474 GRID(ret, nums, x, y) = n;
1475 for (i = 0; i < state->order; i++)
1476 HINT(ret, x, y, i) = 0;
1477
1478 /* real change to grid; check for completion */
1479 if (!ret->completed && check_complete(ret->nums, ret, 1) > 0)
1480 ret->completed = TRUE;
1481 }
1482 return ret;
1483 } else if (move[0] == 'S') {
1484 char *p;
1485
1486 ret = dup_game(state);
1487 ret->completed = ret->cheated = TRUE;
1488
1489 p = move+1;
1490 for (i = 0; i < state->order*state->order; i++) {
1491 n = c2n((int)*p, state->order);
1492 if (!*p || n <= 0 || n > state->order)
1493 goto badmove;
1494 ret->nums[i] = n;
1495 p++;
1496 }
1497 if (*p) goto badmove;
242a7d91 1498 rc = check_complete(ret->nums, ret, 1);
1499 assert(rc > 0);
149255d7 1500 return ret;
9c90045a 1501 } else if (move[0] == 'M') {
1502 ret = dup_game(state);
1503 for (x = 0; x < state->order; x++) {
1504 for (y = 0; y < state->order; y++) {
1505 for (n = 0; n < state->order; n++) {
1506 HINT(ret, x, y, n) = 1;
1507 }
1508 }
1509 }
1510 return ret;
149255d7 1511 } else if (move[0] == 'H') {
1512 return solver_hint(state, NULL, DIFF_EASY, DIFF_EASY);
1513 }
1514
1515badmove:
1516 if (ret) free_game(ret);
1517 return NULL;
1518}
1519
1520/* ----------------------------------------------------------------------
1521 * Drawing/printing routines.
1522 */
1523
1524#define DRAW_SIZE (TILE_SIZE*ds->order + GAP_SIZE*(ds->order-1) + BORDER*2)
1525
1526static void game_compute_size(game_params *params, int tilesize,
1527 int *x, int *y)
1528{
1529 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1530 struct { int tilesize, order; } ads, *ds = &ads;
1531 ads.tilesize = tilesize;
1532 ads.order = params->order;
1533
1534 *x = *y = DRAW_SIZE;
1535}
1536
1537static void game_set_size(drawing *dr, game_drawstate *ds,
1538 game_params *params, int tilesize)
1539{
1540 ds->tilesize = tilesize;
1541}
1542
1543static float *game_colours(frontend *fe, int *ncolours)
1544{
1545 float *ret = snewn(3 * NCOLOURS, float);
1546 int i;
1547
1548 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1549
1550 for (i = 0; i < 3; i++) {
1551 ret[COL_TEXT * 3 + i] = 0.0F;
1552 ret[COL_GRID * 3 + i] = 0.5F;
1553 }
1554
1555 /* Lots of these were taken from solo.c. */
1556 ret[COL_GUESS * 3 + 0] = 0.0F;
1557 ret[COL_GUESS * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1558 ret[COL_GUESS * 3 + 2] = 0.0F;
1559
1560 ret[COL_ERROR * 3 + 0] = 1.0F;
1561 ret[COL_ERROR * 3 + 1] = 0.0F;
1562 ret[COL_ERROR * 3 + 2] = 0.0F;
1563
1564 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1565 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1566 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1567
1568 *ncolours = NCOLOURS;
1569 return ret;
1570}
1571
1572static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1573{
1574 struct game_drawstate *ds = snew(struct game_drawstate);
1575 int o2 = state->order*state->order, o3 = o2*state->order;
1576
1577 ds->tilesize = 0;
1578 ds->order = state->order;
34950d9f 1579 ds->adjacent = state->adjacent;
149255d7 1580
1581 ds->nums = snewn(o2, digit);
1582 ds->hints = snewn(o3, unsigned char);
1583 ds->flags = snewn(o2, unsigned int);
1584 memset(ds->nums, 0, o2*sizeof(digit));
1585 memset(ds->hints, 0, o3);
1586 memset(ds->flags, 0, o2*sizeof(unsigned int));
1587
9c90045a 1588 ds->hx = ds->hy = 0;
1589 ds->started = ds->hshow = ds->hpencil = ds->hflash = 0;
149255d7 1590
1591 return ds;
1592}
1593
1594static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1595{
1596 sfree(ds->nums);
1597 sfree(ds->hints);
1598 sfree(ds->flags);
1599 sfree(ds);
1600}
1601
1602static void draw_gt(drawing *dr, int ox, int oy,
1603 int dx1, int dy1, int dx2, int dy2, int col)
1604{
1605 draw_line(dr, ox, oy, ox+dx1, oy+dy1, col);
1606 draw_line(dr, ox+dx1, oy+dy1, ox+dx1+dx2, oy+dy1+dy2, col);
1607}
1608
1609static void draw_gts(drawing *dr, game_drawstate *ds, int ox, int oy,
34950d9f 1610 unsigned int f, int col)
149255d7 1611{
1612 int g = GAP_SIZE, g2 = (g+1)/2, g4 = (g+1)/4;
1613
34950d9f 1614 /* Draw all the greater-than signs emanating from this tile. */
1615
1616 if (f & F_ADJ_UP) {
149255d7 1617 draw_gt(dr, ox+g2, oy-g4, g2, -g2, g2, g2,
1618 (f & F_ERROR_UP) ? COL_ERROR : col);
34950d9f 1619 draw_update(dr, ox, oy-g, TILE_SIZE, g);
149255d7 1620 }
34950d9f 1621 if (f & F_ADJ_RIGHT) {
149255d7 1622 draw_gt(dr, ox+TILE_SIZE+g4, oy+g2, g2, g2, -g2, g2,
1623 (f & F_ERROR_RIGHT) ? COL_ERROR : col);
34950d9f 1624 draw_update(dr, ox+TILE_SIZE, oy, g, TILE_SIZE);
149255d7 1625 }
34950d9f 1626 if (f & F_ADJ_DOWN) {
149255d7 1627 draw_gt(dr, ox+g2, oy+TILE_SIZE+g4, g2, g2, g2, -g2,
1628 (f & F_ERROR_DOWN) ? COL_ERROR : col);
34950d9f 1629 draw_update(dr, ox, oy+TILE_SIZE, TILE_SIZE, g);
149255d7 1630 }
34950d9f 1631 if (f & F_ADJ_LEFT) {
149255d7 1632 draw_gt(dr, ox-g4, oy+g2, -g2, g2, g2, g2,
1633 (f & F_ERROR_LEFT) ? COL_ERROR : col);
34950d9f 1634 draw_update(dr, ox-g, oy, g, TILE_SIZE);
1635 }
1636}
1637
1638static void draw_adjs(drawing *dr, game_drawstate *ds, int ox, int oy,
1639 unsigned int f, int col)
1640{
1641 int g = GAP_SIZE, g38 = 3*(g+1)/8, g4 = (g+1)/4;
1642
1643 /* Draw all the adjacency bars relevant to this tile; we only have
1644 * to worry about F_ADJ_RIGHT and F_ADJ_DOWN.
1645 *
1646 * If we _only_ have the error flag set (i.e. it's not supposed to be
1647 * adjacent, but adjacent numbers were entered) draw an outline red bar.
1648 */
1649
1650 if (f & (F_ADJ_RIGHT|F_ERROR_RIGHT)) {
1651 if (f & F_ADJ_RIGHT) {
1652 draw_rect(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE,
1653 (f & F_ERROR_RIGHT) ? COL_ERROR : col);
1654 } else {
1655 draw_rect_outline(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE, COL_ERROR);
1656 }
1657 } else {
1658 draw_rect(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE, COL_BACKGROUND);
1659 }
1660 draw_update(dr, ox+TILE_SIZE, oy, g, TILE_SIZE);
1661
1662 if (f & (F_ADJ_DOWN|F_ERROR_DOWN)) {
1663 if (f & F_ADJ_DOWN) {
1664 draw_rect(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4,
1665 (f & F_ERROR_DOWN) ? COL_ERROR : col);
1666 } else {
1667 draw_rect_outline(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4, COL_ERROR);
1668 }
1669 } else {
1670 draw_rect(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4, COL_BACKGROUND);
149255d7 1671 }
34950d9f 1672 draw_update(dr, ox, oy+TILE_SIZE, TILE_SIZE, g);
149255d7 1673}
1674
1675static void draw_furniture(drawing *dr, game_drawstate *ds, game_state *state,
1676 game_ui *ui, int x, int y, int hflash)
1677{
9c90045a 1678 int ox = COORD(x), oy = COORD(y), bg, hon;
149255d7 1679 unsigned int f = GRID(state, flags, x, y);
1680
1681 bg = hflash ? COL_HIGHLIGHT : COL_BACKGROUND;
1682
9c90045a 1683 hon = (ui->hshow && x == ui->hx && y == ui->hy);
149255d7 1684
1685 /* Clear square. */
1686 draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE,
1687 (hon && !ui->hpencil) ? COL_HIGHLIGHT : bg);
1688
1689 /* Draw the highlight (pencil or full), if we're the highlight */
1690 if (hon && ui->hpencil) {
1691 int coords[6];
1692 coords[0] = ox;
1693 coords[1] = oy;
1694 coords[2] = ox + TILE_SIZE/2;
1695 coords[3] = oy;
1696 coords[4] = ox;
1697 coords[5] = oy + TILE_SIZE/2;
1698 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1699 }
1700
1701 /* Draw the square outline (which is the cursor, if we're the cursor). */
9c90045a 1702 draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
149255d7 1703
1704 draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
1705
34950d9f 1706 /* Draw the adjacent clue signs. */
1707 if (ds->adjacent)
1708 draw_adjs(dr, ds, ox, oy, f, COL_GRID);
1709 else
1710 draw_gts(dr, ds, ox, oy, f, COL_TEXT);
149255d7 1711}
1712
1713static void draw_num(drawing *dr, game_drawstate *ds, int x, int y)
1714{
1715 int ox = COORD(x), oy = COORD(y);
1716 unsigned int f = GRID(ds,flags,x,y);
1717 char str[2];
1718
1719 /* (can assume square has just been cleared) */
1720
1721 /* Draw number, choosing appropriate colour */
1722 str[0] = n2c(GRID(ds, nums, x, y), ds->order);
1723 str[1] = '\0';
1724 draw_text(dr, ox + TILE_SIZE/2, oy + TILE_SIZE/2,
1725 FONT_VARIABLE, 3*TILE_SIZE/4, ALIGN_VCENTRE | ALIGN_HCENTRE,
1726 (f & F_IMMUTABLE) ? COL_TEXT : (f & F_ERROR) ? COL_ERROR : COL_GUESS, str);
1727}
1728
1729static void draw_hints(drawing *dr, game_drawstate *ds, int x, int y)
1730{
1731 int ox = COORD(x), oy = COORD(y);
1732 int nhints, i, j, hw, hh, hmax, fontsz;
1733 char str[2];
1734
1735 /* (can assume square has just been cleared) */
1736
1737 /* Draw hints; steal ingenious algorithm (basically)
1738 * from solo.c:draw_number() */
1739 for (i = nhints = 0; i < ds->order; i++) {
1740 if (HINT(ds, x, y, i)) nhints++;
1741 }
1742
1743 for (hw = 1; hw * hw < nhints; hw++);
1744 if (hw < 3) hw = 3;
1745 hh = (nhints + hw - 1) / hw;
1746 if (hh < 2) hh = 2;
1747 hmax = max(hw, hh);
1748 fontsz = TILE_SIZE/(hmax*(11-hmax)/8);
1749
1750 for (i = j = 0; i < ds->order; i++) {
1751 if (HINT(ds,x,y,i)) {
1752 int hx = j % hw, hy = j / hw;
1753
1754 str[0] = n2c(i+1, ds->order);
1755 str[1] = '\0';
1756 draw_text(dr,
1757 ox + (4*hx+3) * TILE_SIZE / (4*hw+2),
1758 oy + (4*hy+3) * TILE_SIZE / (4*hh+2),
1759 FONT_VARIABLE, fontsz,
1760 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1761 j++;
1762 }
1763 }
1764}
1765
1766static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1767 game_state *state, int dir, game_ui *ui,
1768 float animtime, float flashtime)
1769{
9c90045a 1770 int x, y, i, hchanged = 0, stale, hflash = 0;
149255d7 1771
1772 debug(("highlight old (%d,%d), new (%d,%d)", ds->hx, ds->hy, ui->hx, ui->hy));
1773
1774 if (flashtime > 0 &&
1775 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3))
1776 hflash = 1;
1777
1778 if (!ds->started) {
1779 draw_rect(dr, 0, 0, DRAW_SIZE, DRAW_SIZE, COL_BACKGROUND);
1780 draw_update(dr, 0, 0, DRAW_SIZE, DRAW_SIZE);
1781 }
9c90045a 1782 if (ds->hx != ui->hx || ds->hy != ui->hy ||
1783 ds->hshow != ui->hshow || ds->hpencil != ui->hpencil)
149255d7 1784 hchanged = 1;
149255d7 1785
1786 for (x = 0; x < ds->order; x++) {
1787 for (y = 0; y < ds->order; y++) {
1788 if (!ds->started)
1789 stale = 1;
1790 else if (hflash != ds->hflash)
1791 stale = 1;
1792 else
1793 stale = 0;
1794
1795 if (hchanged) {
1796 if ((x == ui->hx && y == ui->hy) ||
1797 (x == ds->hx && y == ds->hy))
1798 stale = 1;
1799 }
149255d7 1800
1801 if (GRID(state, nums, x, y) != GRID(ds, nums, x, y)) {
1802 GRID(ds, nums, x, y) = GRID(state, nums, x, y);
1803 stale = 1;
1804 }
1805 if (GRID(state, flags, x, y) != GRID(ds, flags, x, y)) {
1806 GRID(ds, flags, x, y) = GRID(state, flags, x, y);
1807 stale = 1;
1808 }
1809 if (GRID(ds, nums, x, y) == 0) {
1810 /* We're not a number square (therefore we might
1811 * display hints); do we need to update? */
1812 for (i = 0; i < ds->order; i++) {
1813 if (HINT(state, x, y, i) != HINT(ds, x, y, i)) {
1814 HINT(ds, x, y, i) = HINT(state, x, y, i);
1815 stale = 1;
1816 }
1817 }
1818 }
1819 if (stale) {
1820 draw_furniture(dr, ds, state, ui, x, y, hflash);
1821 if (GRID(ds, nums, x, y) > 0)
1822 draw_num(dr, ds, x, y);
1823 else
1824 draw_hints(dr, ds, x, y);
1825 }
1826 }
1827 }
9c90045a 1828 ds->hx = ui->hx; ds->hy = ui->hy;
1829 ds->hshow = ui->hshow;
1830 ds->hpencil = ui->hpencil;
1831
149255d7 1832 ds->started = 1;
1833 ds->hflash = hflash;
1834}
1835
1836static float game_anim_length(game_state *oldstate, game_state *newstate,
1837 int dir, game_ui *ui)
1838{
1839 return 0.0F;
1840}
1841
1842static float game_flash_length(game_state *oldstate, game_state *newstate,
1843 int dir, game_ui *ui)
1844{
1845 if (!oldstate->completed && newstate->completed &&
1846 !oldstate->cheated && !newstate->cheated)
1847 return FLASH_TIME;
1848 return 0.0F;
1849}
1850
1851static int game_timing_state(game_state *state, game_ui *ui)
1852{
1853 return TRUE;
1854}
1855
1856static void game_print_size(game_params *params, float *x, float *y)
1857{
1858 int pw, ph;
1859
1860 /* 10mm squares by default, roughly the same as Grauniad. */
1861 game_compute_size(params, 1000, &pw, &ph);
1862 *x = pw / 100.0F;
1863 *y = ph / 100.0F;
1864}
1865
1866static void game_print(drawing *dr, game_state *state, int tilesize)
1867{
1868 int ink = print_mono_colour(dr, 0);
1869 int x, y, o = state->order, ox, oy, n;
1870 char str[2];
1871
1872 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1873 game_drawstate ads, *ds = &ads;
1874 game_set_size(dr, ds, NULL, tilesize);
1875
1876 print_line_width(dr, 2 * TILE_SIZE / 40);
1877
1878 /* Squares, numbers, gt signs */
1879 for (y = 0; y < o; y++) {
1880 for (x = 0; x < o; x++) {
1881 ox = COORD(x); oy = COORD(y);
1882 n = GRID(state, nums, x, y);
1883
1884 draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, ink);
1885
1886 str[0] = n ? n2c(n, state->order) : ' ';
1887 str[1] = '\0';
1888 draw_text(dr, ox + TILE_SIZE/2, oy + TILE_SIZE/2,
1889 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1890 ink, str);
1891
34950d9f 1892 if (ds->adjacent)
1893 draw_adjs(dr, ds, ox, oy, GRID(state, flags, x, y), ink);
1894 else
1895 draw_gts(dr, ds, ox, oy, GRID(state, flags, x, y), ink);
149255d7 1896 }
1897 }
1898}
1899
1900/* ----------------------------------------------------------------------
1901 * Housekeeping.
1902 */
1903
1904#ifdef COMBINED
1905#define thegame unequal
1906#endif
1907
1908const struct game thegame = {
1909 "Unequal", "games.unequal", "unequal",
1910 default_params,
1911 game_fetch_preset,
1912 decode_params,
1913 encode_params,
1914 free_params,
1915 dup_params,
1916 TRUE, game_configure, custom_params,
1917 validate_params,
1918 new_game_desc,
1919 validate_desc,
1920 new_game,
1921 dup_game,
1922 free_game,
1923 TRUE, solve_game,
fa3abef5 1924 TRUE, game_can_format_as_text_now, game_text_format,
149255d7 1925 new_ui,
1926 free_ui,
1927 encode_ui,
1928 decode_ui,
1929 game_changed_state,
1930 interpret_move,
1931 execute_move,
1932 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1933 game_colours,
1934 game_new_drawstate,
1935 game_free_drawstate,
1936 game_redraw,
1937 game_anim_length,
1938 game_flash_length,
1939 TRUE, FALSE, game_print_size, game_print,
1940 FALSE, /* wants_statusbar */
1941 FALSE, game_timing_state,
cb0c7d4a 1942 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
149255d7 1943};
1944
1945/* ----------------------------------------------------------------------
1946 * Standalone solver.
1947 */
1948
1949#ifdef STANDALONE_SOLVER
1950
1951#include <time.h>
1952#include <stdarg.h>
1953
1954const char *quis = NULL;
1955
1956#if 0 /* currently unused */
1957
1958static void debug_printf(char *fmt, ...)
1959{
1960 char buf[4096];
1961 va_list ap;
1962
1963 va_start(ap, fmt);
1964 vsprintf(buf, fmt, ap);
1965 puts(buf);
1966 va_end(ap);
1967}
1968
1969static void game_printf(game_state *state)
1970{
1971 char *dbg = game_text_format(state);
1972 printf("%s", dbg);
1973 sfree(dbg);
1974}
1975
1976static void game_printf_wide(game_state *state)
1977{
1978 int x, y, i, n;
1979
1980 for (y = 0; y < state->order; y++) {
1981 for (x = 0; x < state->order; x++) {
1982 n = GRID(state, nums, x, y);
1983 for (i = 0; i < state->order; i++) {
1984 if (n > 0)
1985 printf("%c", n2c(n, state->order));
1986 else if (HINT(state, x, y, i))
1987 printf("%c", n2c(i+1, state->order));
1988 else
1989 printf(".");
1990 }
1991 printf(" ");
1992 }
1993 printf("\n");
1994 }
1995 printf("\n");
1996}
1997
1998#endif
1999
2000static void pdiff(int diff)
2001{
2002 if (diff == DIFF_IMPOSSIBLE)
2003 printf("Game is impossible.\n");
2004 else if (diff == DIFF_UNFINISHED)
2005 printf("Game has incomplete.\n");
2006 else if (diff == DIFF_AMBIGUOUS)
2007 printf("Game has multiple solutions.\n");
2008 else
2009 printf("Game has difficulty %s.\n", unequal_diffnames[diff]);
2010}
2011
2012static int solve(game_params *p, char *desc, int debug)
2013{
388b2f00 2014 game_state *state = new_game(NULL, p, desc);
2015 struct solver_ctx *ctx = new_ctx(state);
2016 struct latin_solver solver;
149255d7 2017 int diff;
2018
2019 solver_show_working = debug;
388b2f00 2020 game_debug(state);
2021
2022 latin_solver_alloc(&solver, state->nums, state->order);
2023
2024 diff = latin_solver_main(&solver, DIFF_RECURSIVE,
2025 DIFF_LATIN, DIFF_SET, DIFF_EXTREME,
2026 DIFF_EXTREME, DIFF_RECURSIVE,
2027 unequal_solvers, ctx, clone_ctx, free_ctx);
2028
2029 free_ctx(ctx);
2030
2031 latin_solver_free(&solver);
149255d7 2032
149255d7 2033 if (debug) pdiff(diff);
2034
388b2f00 2035 game_debug(state);
2036 free_game(state);
149255d7 2037 return diff;
2038}
2039
2040static void check(game_params *p)
2041{
2042 char *msg = validate_params(p, 1);
2043 if (msg) {
2044 fprintf(stderr, "%s: %s", quis, msg);
2045 exit(1);
2046 }
2047}
2048
2049static int gen(game_params *p, random_state *rs, int debug)
2050{
2051 char *desc, *aux;
2052 int diff;
2053
2054 check(p);
2055
2056 solver_show_working = debug;
2057 desc = new_game_desc(p, rs, &aux, 0);
2058 diff = solve(p, desc, debug);
2059 sfree(aux);
2060 sfree(desc);
2061
2062 return diff;
2063}
2064
2065static void soak(game_params *p, random_state *rs)
2066{
2067 time_t tt_start, tt_now, tt_last;
2068 char *aux, *desc;
2069 game_state *st;
2070 int n = 0, neasy = 0, realdiff = p->diff;
2071
2072 check(p);
2073
2074 solver_show_working = 0;
2075 maxtries = 1;
2076
2077 tt_start = tt_now = time(NULL);
2078
34950d9f 2079 printf("Soak-generating an %s %dx%d grid, difficulty %s.\n",
2080 p->adjacent ? "adjacent" : "unequal",
149255d7 2081 p->order, p->order, unequal_diffnames[p->diff]);
2082
2083 while (1) {
2084 p->diff = realdiff;
2085 desc = new_game_desc(p, rs, &aux, 0);
2086 st = new_game(NULL, p, desc);
2087 solver_state(st, DIFF_RECURSIVE);
2088 free_game(st);
2089 sfree(aux);
2090 sfree(desc);
2091
2092 n++;
2093 if (realdiff != p->diff) neasy++;
2094
2095 tt_last = time(NULL);
2096 if (tt_last > tt_now) {
2097 tt_now = tt_last;
2098 printf("%d total, %3.1f/s; %d/%2.1f%% easy, %3.1f/s good.\n",
2099 n, (double)n / ((double)tt_now - tt_start),
2100 neasy, (double)neasy*100.0/(double)n,
2101 (double)(n - neasy) / ((double)tt_now - tt_start));
2102 }
2103 }
2104}
2105
2106static void usage_exit(const char *msg)
2107{
2108 if (msg)
2109 fprintf(stderr, "%s: %s\n", quis, msg);
2110 fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
2111 exit(1);
2112}
2113
2114int main(int argc, const char *argv[])
2115{
2116 random_state *rs;
2117 time_t seed = time(NULL);
2118 int do_soak = 0, diff;
2119
2120 game_params *p;
2121
2122 maxtries = 50;
2123
2124 quis = argv[0];
2125 while (--argc > 0) {
2126 const char *p = *++argv;
2127 if (!strcmp(p, "--soak"))
2128 do_soak = 1;
2129 else if (!strcmp(p, "--seed")) {
2130 if (argc == 0)
2131 usage_exit("--seed needs an argument");
2132 seed = (time_t)atoi(*++argv);
2133 argc--;
2134 } else if (*p == '-')
2135 usage_exit("unrecognised option");
2136 else
2137 break;
2138 }
2139 rs = random_new((void*)&seed, sizeof(time_t));
2140
2141 if (do_soak == 1) {
2142 if (argc != 1) usage_exit("only one argument for --soak");
2143 p = default_params();
2144 decode_params(p, *argv);
2145 soak(p, rs);
2146 } else if (argc > 0) {
2147 int i;
2148 for (i = 0; i < argc; i++) {
2149 const char *id = *argv++;
2150 char *desc = strchr(id, ':'), *err;
2151 p = default_params();
2152 if (desc) {
2153 *desc++ = '\0';
2154 decode_params(p, id);
2155 err = validate_desc(p, desc);
2156 if (err) {
2157 fprintf(stderr, "%s: %s\n", quis, err);
2158 exit(1);
2159 }
2160 solve(p, desc, 1);
2161 } else {
2162 decode_params(p, id);
2163 diff = gen(p, rs, 1);
2164 }
2165 }
2166 } else {
2167 while(1) {
2168 p = default_params();
2169 p->order = random_upto(rs, 7) + 3;
2170 p->diff = random_upto(rs, 4);
2171 diff = gen(p, rs, 0);
2172 pdiff(diff);
2173 }
2174 }
2175
2176 return 0;
2177}
2178
2179#endif
2180
2181/* vim: set shiftwidth=4 tabstop=8: */