2 * keen.c: an implementation of the Times's 'KenKen' puzzle, and
3 * also of Nikoli's very similar 'Inshi No Heya' puzzle.
17 * Difficulty levels. I do some macro ickery here to ensure that my
18 * enum and the various forms of my name list always match up.
21 A(EASY,Easy,solver_easy,e) \
22 A(NORMAL,Normal,solver_normal,n) \
23 A(HARD,Hard,solver_hard,h) \
24 A(EXTREME,Extreme,NULL,x) \
25 A(UNREASONABLE,Unreasonable,NULL,u)
26 #define ENUM(upper,title,func,lower) DIFF_ ## upper,
27 #define TITLE(upper,title,func,lower) #title,
28 #define ENCODE(upper,title,func,lower) #lower
29 #define CONFIG(upper,title,func,lower) ":" #title
30 enum { DIFFLIST(ENUM) DIFFCOUNT };
31 static char const *const keen_diffnames[] = { DIFFLIST(TITLE) };
32 static char const keen_diffchars[] = DIFFLIST(ENCODE);
33 #define DIFFCONFIG DIFFLIST(CONFIG)
36 * Clue notation. Important here that ADD and MUL come before SUB
37 * and DIV, and that DIV comes last.
39 #define C_ADD 0x00000000L
40 #define C_MUL 0x20000000L
41 #define C_SUB 0x40000000L
42 #define C_DIV 0x60000000L
43 #define CMASK 0x60000000L
44 #define CUNIT 0x20000000L
47 * Maximum size of any clue block. Very large ones are annoying in UI
48 * terms (if they're multiplicative you end up with too many digits to
49 * fit in the square) and also in solver terms (too many possibilities
65 int w, diff, multiplication_only;
79 int *pencil; /* bitmaps using bits 1<<1..1<<n */
80 int completed, cheated;
83 static game_params *default_params(void)
85 game_params *ret = snew(game_params);
88 ret->diff = DIFF_NORMAL;
89 ret->multiplication_only = FALSE;
94 const static struct game_params keen_presets[] = {
95 { 4, DIFF_EASY, FALSE },
96 { 5, DIFF_EASY, FALSE },
97 { 5, DIFF_EASY, TRUE },
98 { 6, DIFF_EASY, FALSE },
99 { 6, DIFF_NORMAL, FALSE },
100 { 6, DIFF_NORMAL, TRUE },
101 { 6, DIFF_HARD, FALSE },
102 { 6, DIFF_EXTREME, FALSE },
103 { 6, DIFF_UNREASONABLE, FALSE },
104 { 9, DIFF_NORMAL, FALSE },
107 static int game_fetch_preset(int i, char **name, game_params **params)
112 if (i < 0 || i >= lenof(keen_presets))
115 ret = snew(game_params);
116 *ret = keen_presets[i]; /* structure copy */
118 sprintf(buf, "%dx%d %s%s", ret->w, ret->w, keen_diffnames[ret->diff],
119 ret->multiplication_only ? ", multiplication only" : "");
126 static void free_params(game_params *params)
131 static game_params *dup_params(const game_params *params)
133 game_params *ret = snew(game_params);
134 *ret = *params; /* structure copy */
138 static void decode_params(game_params *params, char const *string)
140 char const *p = string;
143 while (*p && isdigit((unsigned char)*p)) p++;
148 params->diff = DIFFCOUNT+1; /* ...which is invalid */
150 for (i = 0; i < DIFFCOUNT; i++) {
151 if (*p == keen_diffchars[i])
160 params->multiplication_only = TRUE;
164 static char *encode_params(const game_params *params, int full)
168 sprintf(ret, "%d", params->w);
170 sprintf(ret + strlen(ret), "d%c%s", keen_diffchars[params->diff],
171 params->multiplication_only ? "m" : "");
176 static config_item *game_configure(const game_params *params)
181 ret = snewn(4, config_item);
183 ret[0].name = "Grid size";
184 ret[0].type = C_STRING;
185 sprintf(buf, "%d", params->w);
186 ret[0].u.string.sval = dupstr(buf);
188 ret[1].name = "Difficulty";
189 ret[1].type = C_CHOICES;
190 ret[1].u.choices.choicenames = DIFFCONFIG;
191 ret[1].u.choices.selected = params->diff;
193 ret[2].name = "Multiplication only";
194 ret[2].type = C_BOOLEAN;
195 ret[2].u.boolean.bval = params->multiplication_only;
203 static game_params *custom_params(const config_item *cfg)
205 game_params *ret = snew(game_params);
207 ret->w = atoi(cfg[0].u.string.sval);
208 ret->diff = cfg[1].u.choices.selected;
209 ret->multiplication_only = cfg[2].u.boolean.bval;
214 static const char *validate_params(const game_params *params, int full)
216 if (params->w < 3 || params->w > 9)
217 return "Grid size must be between 3 and 9";
218 if (params->diff >= DIFFCOUNT)
219 return "Unknown difficulty rating";
223 /* ----------------------------------------------------------------------
230 int *boxes, *boxlist, *whichbox;
237 static void solver_clue_candidate(struct solver_ctx *ctx, int diff, int box)
240 int n = ctx->boxes[box+1] - ctx->boxes[box];
244 * This function is called from the main clue-based solver
245 * routine when we discover a candidate layout for a given clue
246 * box consistent with everything we currently know about the
247 * digit constraints in that box. We expect to find the digits
248 * of the candidate layout in ctx->dscratch, and we update
249 * ctx->iscratch as appropriate.
251 * The contents of ctx->iscratch are completely different
252 * depending on whether diff == DIFF_HARD or not. This function
253 * uses iscratch completely differently between the two cases, and
254 * the code in solver_common() which consumes the result must
255 * likewise have an if statement with completely different
256 * branches for the two cases.
258 * In DIFF_EASY and DIFF_NORMAL modes, the valid entries in
259 * ctx->iscratch are 0,...,n-1, and each of those entries
260 * ctx->iscratch[i] gives a bitmap of the possible digits in the
261 * ith square of the clue box currently under consideration. So
262 * each entry of iscratch starts off as an empty bitmap, and we
263 * set bits in it as possible layouts for the clue box are
264 * considered (and the difference between DIFF_EASY and
265 * DIFF_NORMAL is just that in DIFF_EASY mode we deliberately set
266 * more bits than absolutely necessary, hence restricting our own
269 * But in DIFF_HARD mode, the valid entries are 0,...,2*w-1 (at
270 * least outside *this* function - inside this function, we also
271 * use 2*w,...,4*w-1 as scratch space in the loop below); the
272 * first w of those give the possible digits in the intersection
273 * of the current clue box with each column of the puzzle, and the
274 * next w do the same for each row. In this mode, each iscratch
275 * entry starts off as a _full_ bitmap, and in this function we
276 * _clear_ bits for digits that are absent from a given row or
277 * column in each candidate layout, so that the only bits which
278 * remain set are those for digits which have to appear in a given
279 * row/column no matter how the clue box is laid out.
281 if (diff == DIFF_EASY) {
284 * Easy-mode clue deductions: we do not record information
285 * about which squares take which values, so we amalgamate
286 * all the values in dscratch and OR them all into
289 for (j = 0; j < n; j++)
290 mask |= 1 << ctx->dscratch[j];
291 for (j = 0; j < n; j++)
292 ctx->iscratch[j] |= mask;
293 } else if (diff == DIFF_NORMAL) {
295 * Normal-mode deductions: we process the information in
296 * dscratch in the obvious way.
298 for (j = 0; j < n; j++)
299 ctx->iscratch[j] |= 1 << ctx->dscratch[j];
300 } else if (diff == DIFF_HARD) {
302 * Hard-mode deductions: instead of ruling things out
303 * _inside_ the clue box, we look for numbers which occur in
304 * a given row or column in all candidate layouts, and rule
305 * them out of all squares in that row or column that
306 * _aren't_ part of this clue box.
308 int *sq = ctx->boxlist + ctx->boxes[box];
310 for (j = 0; j < 2*w; j++)
311 ctx->iscratch[2*w+j] = 0;
312 for (j = 0; j < n; j++) {
313 int x = sq[j] / w, y = sq[j] % w;
314 ctx->iscratch[2*w+x] |= 1 << ctx->dscratch[j];
315 ctx->iscratch[3*w+y] |= 1 << ctx->dscratch[j];
317 for (j = 0; j < 2*w; j++)
318 ctx->iscratch[j] &= ctx->iscratch[2*w+j];
322 static int solver_common(struct latin_solver *solver, void *vctx, int diff)
324 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
330 * Iterate over each clue box and deduce what we can.
332 for (box = 0; box < ctx->nboxes; box++) {
333 int *sq = ctx->boxlist + ctx->boxes[box];
334 int n = ctx->boxes[box+1] - ctx->boxes[box];
335 long value = ctx->clues[box] & ~CMASK;
336 long op = ctx->clues[box] & CMASK;
339 * Initialise ctx->iscratch for this clue box. At different
340 * difficulty levels we must initialise a different amount of
341 * it to different things; see the comments in
342 * solver_clue_candidate explaining what each version does.
344 if (diff == DIFF_HARD) {
345 for (i = 0; i < 2*w; i++)
346 ctx->iscratch[i] = (1 << (w+1)) - (1 << 1);
348 for (i = 0; i < n; i++)
349 ctx->iscratch[i] = 0;
356 * These two clue types must always apply to a box of
357 * area 2. Also, the two digits in these boxes can never
358 * be the same (because any domino must have its two
359 * squares in either the same row or the same column).
360 * So we simply iterate over all possibilities for the
361 * two squares (both ways round), rule out any which are
362 * inconsistent with the digit constraints we already
363 * have, and update the digit constraints with any new
364 * information thus garnered.
368 for (i = 1; i <= w; i++) {
369 j = (op == C_SUB ? i + value : i * value);
372 /* (i,j) is a valid digit pair. Try it both ways round. */
374 if (solver->cube[sq[0]*w+i-1] &&
375 solver->cube[sq[1]*w+j-1]) {
376 ctx->dscratch[0] = i;
377 ctx->dscratch[1] = j;
378 solver_clue_candidate(ctx, diff, box);
381 if (solver->cube[sq[0]*w+j-1] &&
382 solver->cube[sq[1]*w+i-1]) {
383 ctx->dscratch[0] = j;
384 ctx->dscratch[1] = i;
385 solver_clue_candidate(ctx, diff, box);
394 * For these clue types, I have no alternative but to go
395 * through all possible number combinations.
397 * Instead of a tedious physical recursion, I iterate in
398 * the scratch array through all possibilities. At any
399 * given moment, i indexes the element of the box that
400 * will next be incremented.
403 ctx->dscratch[i] = 0;
404 total = value; /* start with the identity */
408 * Find the next valid value for cell i.
410 for (j = ctx->dscratch[i] + 1; j <= w; j++) {
411 if (op == C_ADD ? (total < j) : (total % j != 0))
412 continue; /* this one won't fit */
413 if (!solver->cube[sq[i]*w+j-1])
414 continue; /* this one is ruled out already */
415 for (k = 0; k < i; k++)
416 if (ctx->dscratch[k] == j &&
417 (sq[k] % w == sq[i] % w ||
418 sq[k] / w == sq[i] / w))
419 break; /* clashes with another row/col */
428 /* No valid values left; drop back. */
431 break; /* overall iteration is finished */
433 total += ctx->dscratch[i];
435 total *= ctx->dscratch[i];
437 /* Got a valid value; store it and move on. */
438 ctx->dscratch[i++] = j;
443 ctx->dscratch[i] = 0;
446 if (total == (op == C_ADD ? 0 : 1))
447 solver_clue_candidate(ctx, diff, box);
450 total += ctx->dscratch[i];
452 total *= ctx->dscratch[i];
460 * Do deductions based on the information we've now
461 * accumulated in ctx->iscratch. See the comments above in
462 * solver_clue_candidate explaining what data is left in here,
463 * and how it differs between DIFF_HARD and lower difficulty
464 * levels (hence the big if statement here).
466 if (diff < DIFF_HARD) {
467 #ifdef STANDALONE_SOLVER
470 if (solver_show_working)
471 sprintf(prefix, "%*susing clue at (%d,%d):\n",
472 solver_recurse_depth*4, "",
473 sq[0]/w+1, sq[0]%w+1);
475 prefix[0] = '\0'; /* placate optimiser */
478 for (i = 0; i < n; i++)
479 for (j = 1; j <= w; j++) {
480 if (solver->cube[sq[i]*w+j-1] &&
481 !(ctx->iscratch[i] & (1 << j))) {
482 #ifdef STANDALONE_SOLVER
483 if (solver_show_working) {
484 printf("%s%*s ruling out %d at (%d,%d)\n",
485 prefix, solver_recurse_depth*4, "",
486 j, sq[i]/w+1, sq[i]%w+1);
490 solver->cube[sq[i]*w+j-1] = 0;
495 #ifdef STANDALONE_SOLVER
498 if (solver_show_working)
499 sprintf(prefix, "%*susing clue at (%d,%d):\n",
500 solver_recurse_depth*4, "",
501 sq[0]/w+1, sq[0]%w+1);
503 prefix[0] = '\0'; /* placate optimiser */
506 for (i = 0; i < 2*w; i++) {
507 int start = (i < w ? i*w : i-w);
508 int step = (i < w ? 1 : w);
509 for (j = 1; j <= w; j++) if (ctx->iscratch[i] & (1 << j)) {
510 #ifdef STANDALONE_SOLVER
513 if (solver_show_working)
514 sprintf(prefix2, "%*s this clue requires %d in"
515 " %s %d:\n", solver_recurse_depth*4, "",
516 j, i < w ? "column" : "row", i%w+1);
518 prefix2[0] = '\0'; /* placate optimiser */
521 for (k = 0; k < w; k++) {
522 int pos = start + k*step;
523 if (ctx->whichbox[pos] != box &&
524 solver->cube[pos*w+j-1]) {
525 #ifdef STANDALONE_SOLVER
526 if (solver_show_working) {
527 printf("%s%s%*s ruling out %d at (%d,%d)\n",
529 solver_recurse_depth*4, "",
530 j, pos/w+1, pos%w+1);
531 prefix[0] = prefix2[0] = '\0';
534 solver->cube[pos*w+j-1] = 0;
542 * Once we find one block we can do something with in
543 * this way, revert to trying easier deductions, so as
544 * not to generate solver diagnostics that make the
545 * problem look harder than it is. (We have to do this
546 * for the Hard deductions but not the Easy/Normal ones,
547 * because only the Hard deductions are cross-box.)
557 static int solver_easy(struct latin_solver *solver, void *vctx)
560 * Omit the EASY deductions when solving at NORMAL level, since
561 * the NORMAL deductions are a superset of them anyway and it
562 * saves on time and confusing solver diagnostics.
564 * Note that this breaks the natural semantics of the return
565 * value of latin_solver. Without this hack, you could determine
566 * a puzzle's difficulty in one go by trying to solve it at
567 * maximum difficulty and seeing what difficulty value was
568 * returned; but with this hack, solving an Easy puzzle on
569 * Normal difficulty will typically return Normal. Hence the
570 * uses of the solver to determine difficulty are all arranged
571 * so as to double-check by re-solving at the next difficulty
572 * level down and making sure it failed.
574 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
575 if (ctx->diff > DIFF_EASY)
577 return solver_common(solver, vctx, DIFF_EASY);
580 static int solver_normal(struct latin_solver *solver, void *vctx)
582 return solver_common(solver, vctx, DIFF_NORMAL);
585 static int solver_hard(struct latin_solver *solver, void *vctx)
587 return solver_common(solver, vctx, DIFF_HARD);
590 #define SOLVER(upper,title,func,lower) func,
591 static usersolver_t const keen_solvers[] = { DIFFLIST(SOLVER) };
593 static int solver(int w, int *dsf, long *clues, digit *soln, int maxdiff)
596 struct solver_ctx ctx;
605 * Transform the dsf-formatted clue list into one over which we
606 * can iterate more easily.
608 * Also transpose the x- and y-coordinates at this point,
609 * because the 'cube' array in the general Latin square solver
610 * puts x first (oops).
612 for (ctx.nboxes = i = 0; i < a; i++)
613 if (dsf_canonify(dsf, i) == i)
615 ctx.boxlist = snewn(a, int);
616 ctx.boxes = snewn(ctx.nboxes+1, int);
617 ctx.clues = snewn(ctx.nboxes, long);
618 ctx.whichbox = snewn(a, int);
619 for (n = m = i = 0; i < a; i++)
620 if (dsf_canonify(dsf, i) == i) {
621 ctx.clues[n] = clues[i];
623 for (j = 0; j < a; j++)
624 if (dsf_canonify(dsf, j) == i) {
625 ctx.boxlist[m++] = (j % w) * w + (j / w); /* transpose */
626 ctx.whichbox[ctx.boxlist[m-1]] = n;
630 assert(n == ctx.nboxes);
634 ctx.dscratch = snewn(a+1, digit);
635 ctx.iscratch = snewn(max(a+1, 4*w), int);
637 ret = latin_solver(soln, w, maxdiff,
638 DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
639 DIFF_EXTREME, DIFF_UNREASONABLE,
640 keen_solvers, &ctx, NULL, NULL);
652 /* ----------------------------------------------------------------------
656 static char *encode_block_structure(char *p, int w, int *dsf)
659 char *orig, *q, *r, c;
664 * Encode the block structure. We do this by encoding the
665 * pattern of dividing lines: first we iterate over the w*(w-1)
666 * internal vertical grid lines in ordinary reading order, then
667 * over the w*(w-1) internal horizontal ones in transposed
670 * We encode the number of non-lines between the lines; _ means
671 * zero (two adjacent divisions), a means 1, ..., y means 25,
672 * and z means 25 non-lines _and no following line_ (so that za
673 * means 26, zb 27 etc).
675 for (i = 0; i <= 2*w*(w-1); i++) {
676 int x, y, p0, p1, edge;
678 if (i == 2*w*(w-1)) {
679 edge = TRUE; /* terminating virtual edge */
692 edge = (dsf_canonify(dsf, p0) != dsf_canonify(dsf, p1));
697 *p++ = 'z', currrun -= 25;
699 *p++ = 'a'-1 + currrun;
708 * Now go through and compress the string by replacing runs of
709 * the same letter with a single copy of that letter followed by
710 * a repeat count, where that makes it shorter. (This puzzle
711 * seems to generate enough long strings of _ to make this a
714 for (q = r = orig; r < p ;) {
717 for (i = 0; r+i < p && r[i] == c; i++);
723 q += sprintf(q, "%d", i);
730 static const char *parse_block_structure(const char **p, int w, int *dsf)
734 int repc = 0, repn = 0;
738 while (**p && (repn > 0 || **p != ',')) {
744 } else if (**p == '_' || (**p >= 'a' && **p <= 'z')) {
745 c = (**p == '_' ? 0 : **p - 'a' + 1);
747 if (**p && isdigit((unsigned char)**p)) {
750 while (**p && isdigit((unsigned char)**p)) (*p)++;
753 return "Invalid character in game description";
755 adv = (c != 25); /* 'z' is a special case */
761 * Non-edge; merge the two dsf classes on either
764 if (pos >= 2*w*(w-1))
765 return "Too much data in block structure specification";
772 int x = pos/(w-1) - w;
777 dsf_merge(dsf, p0, p1);
783 if (pos > 2*w*(w-1)+1)
784 return "Too much data in block structure specification";
789 * When desc is exhausted, we expect to have gone exactly
790 * one space _past_ the end of the grid, due to the dummy
793 if (pos != 2*w*(w-1)+1)
794 return "Not enough data in block structure specification";
799 static char *new_game_desc(const game_params *params, random_state *rs,
800 char **aux, int interactive)
802 int w = params->w, a = w*w;
804 int *order, *revorder, *singletons, *dsf;
805 long *clues, *cluevals;
806 int i, j, k, n, x, y, ret;
807 int diff = params->diff;
811 * Difficulty exceptions: 3x3 puzzles at difficulty Hard or
812 * higher are currently not generable - the generator will spin
813 * forever looking for puzzles of the appropriate difficulty. We
814 * dial each of these down to the next lower difficulty.
816 * Remember to re-test this whenever a change is made to the
819 * I tested it using the following shell command:
821 for d in e n h x u; do
823 echo ./keen --generate 1 ${i}d${d}
824 perl -e 'alarm 30; exec @ARGV' ./keen --generate 5 ${i}d${d} >/dev/null \
829 * Of course, it's better to do that after taking the exceptions
830 * _out_, so as to detect exceptions that should be removed as
831 * well as those which should be added.
833 if (w == 3 && diff > DIFF_NORMAL)
838 order = snewn(a, int);
839 revorder = snewn(a, int);
840 singletons = snewn(a, int);
842 clues = snewn(a, long);
843 cluevals = snewn(a, long);
844 soln = snewn(a, digit);
848 * First construct a latin square to be the solution.
851 grid = latin_generate(w, rs);
854 * Divide the grid into arbitrarily sized blocks, but so as
855 * to arrange plenty of dominoes which can be SUB/DIV clues.
856 * We do this by first placing dominoes at random for a
857 * while, then tying the remaining singletons one by one
858 * into neighbouring blocks.
860 for (i = 0; i < a; i++)
862 shuffle(order, a, sizeof(*order), rs);
863 for (i = 0; i < a; i++)
864 revorder[order[i]] = i;
866 for (i = 0; i < a; i++)
867 singletons[i] = TRUE;
871 /* Place dominoes. */
872 for (i = 0; i < a; i++) {
879 if (x > 0 && singletons[i-1] &&
880 (best == -1 || revorder[i-1] < revorder[best]))
882 if (x+1 < w && singletons[i+1] &&
883 (best == -1 || revorder[i+1] < revorder[best]))
885 if (y > 0 && singletons[i-w] &&
886 (best == -1 || revorder[i-w] < revorder[best]))
888 if (y+1 < w && singletons[i+w] &&
889 (best == -1 || revorder[i+w] < revorder[best]))
893 * When we find a potential domino, we place it with
894 * probability 3/4, which seems to strike a decent
895 * balance between plenty of dominoes and leaving
896 * enough singletons to make interesting larger
899 if (best >= 0 && random_upto(rs, 4)) {
900 singletons[i] = singletons[best] = FALSE;
901 dsf_merge(dsf, i, best);
906 /* Fold in singletons. */
907 for (i = 0; i < a; i++) {
914 if (x > 0 && dsf_size(dsf, i-1) < MAXBLK &&
915 (best == -1 || revorder[i-1] < revorder[best]))
917 if (x+1 < w && dsf_size(dsf, i+1) < MAXBLK &&
918 (best == -1 || revorder[i+1] < revorder[best]))
920 if (y > 0 && dsf_size(dsf, i-w) < MAXBLK &&
921 (best == -1 || revorder[i-w] < revorder[best]))
923 if (y+1 < w && dsf_size(dsf, i+w) < MAXBLK &&
924 (best == -1 || revorder[i+w] < revorder[best]))
928 singletons[i] = singletons[best] = FALSE;
929 dsf_merge(dsf, i, best);
934 /* Quit and start again if we have any singletons left over
935 * which we weren't able to do anything at all with. */
936 for (i = 0; i < a; i++)
943 * Decide what would be acceptable clues for each block.
945 * Blocks larger than 2 have free choice of ADD or MUL;
946 * blocks of size 2 can be anything in principle (except
947 * that they can only be DIV if the two numbers have an
948 * integer quotient, of course), but we rule out (or try to
949 * avoid) some clues because they're of low quality.
951 * Hence, we iterate once over the grid, stopping at the
952 * canonical element of every >2 block and the _non_-
953 * canonical element of every 2-block; the latter means that
954 * we can make our decision about a 2-block in the knowledge
955 * of both numbers in it.
957 * We reuse the 'singletons' array (finished with in the
958 * above loop) to hold information about which blocks are
967 for (i = 0; i < a; i++) {
969 j = dsf_canonify(dsf, i);
970 k = dsf_size(dsf, j);
971 if (params->multiplication_only)
972 singletons[j] = F_MUL;
973 else if (j == i && k > 2) {
974 singletons[j] |= F_ADD | F_MUL;
975 } else if (j != i && k == 2) {
976 /* Fetch the two numbers and sort them into order. */
977 int p = grid[j], q = grid[i], v;
979 int t = p; p = q; q = t;
983 * Addition clues are always allowed, but we try to
984 * avoid sums of 3, 4, (2w-1) and (2w-2) if we can,
985 * because they're too easy - they only leave one
986 * option for the pair of numbers involved.
989 if (v > 4 && v < 2*w-2)
990 singletons[j] |= F_ADD;
992 singletons[j] |= F_ADD << BAD_SHIFT;
995 * Multiplication clues: above Normal difficulty, we
996 * prefer (but don't absolutely insist on) clues of
997 * this type which leave multiple options open.
1001 for (k = 1; k <= w; k++)
1002 if (v % k == 0 && v / k <= w && v / k != k)
1004 if (n <= 2 && diff > DIFF_NORMAL)
1005 singletons[j] |= F_MUL << BAD_SHIFT;
1007 singletons[j] |= F_MUL;
1010 * Subtraction: we completely avoid a difference of
1015 singletons[j] |= F_SUB;
1018 * Division: for a start, the quotient must be an
1019 * integer or the clue type is impossible. Also, we
1020 * never use quotients strictly greater than w/2,
1021 * because they're not only too easy but also
1024 if (p % q == 0 && 2 * (p / q) <= w)
1025 singletons[j] |= F_DIV;
1030 * Actually choose a clue for each block, trying to keep the
1031 * numbers of each type even, and starting with the
1032 * preferred candidates for each type where possible.
1034 * I'm sure there should be a faster algorithm for doing
1035 * this, but I can't be bothered: O(N^2) is good enough when
1036 * N is at most the number of dominoes that fits into a 9x9
1039 shuffle(order, a, sizeof(*order), rs);
1040 for (i = 0; i < a; i++)
1043 int done_something = FALSE;
1045 for (k = 0; k < 4; k++) {
1049 case 0: clue = C_DIV; good = F_DIV; break;
1050 case 1: clue = C_SUB; good = F_SUB; break;
1051 case 2: clue = C_MUL; good = F_MUL; break;
1052 default /* case 3 */ : clue = C_ADD; good = F_ADD; break;
1055 for (i = 0; i < a; i++) {
1057 if (singletons[j] & good) {
1064 /* didn't find a nice one, use a nasty one */
1065 bad = good << BAD_SHIFT;
1066 for (i = 0; i < a; i++) {
1068 if (singletons[j] & bad) {
1076 done_something = TRUE;
1079 if (!done_something)
1089 * Having chosen the clue types, calculate the clue values.
1091 for (i = 0; i < a; i++) {
1092 j = dsf_canonify(dsf, i);
1094 cluevals[j] = grid[i];
1098 cluevals[j] += grid[i];
1101 cluevals[j] *= grid[i];
1104 cluevals[j] = abs(cluevals[j] - grid[i]);
1108 int d1 = cluevals[j], d2 = grid[i];
1109 if (d1 == 0 || d2 == 0)
1112 cluevals[j] = d2/d1 + d1/d2;/* one is 0 :-) */
1119 for (i = 0; i < a; i++) {
1120 j = dsf_canonify(dsf, i);
1122 clues[j] |= cluevals[j];
1127 * See if the game can be solved at the specified difficulty
1128 * level, but not at the one below.
1132 ret = solver(w, dsf, clues, soln, diff-1);
1137 ret = solver(w, dsf, clues, soln, diff);
1139 continue; /* go round again */
1142 * I wondered if at this point it would be worth trying to
1143 * merge adjacent blocks together, to make the puzzle
1144 * gradually more difficult if it's currently easier than
1145 * specced, increasing the chance of a given generation run
1148 * It doesn't seem to be critical for the generation speed,
1149 * though, so for the moment I'm leaving it out.
1153 * We've got a usable puzzle!
1159 * Encode the puzzle description.
1161 desc = snewn(40*a, char);
1163 p = encode_block_structure(p, w, dsf);
1165 for (i = 0; i < a; i++) {
1166 j = dsf_canonify(dsf, i);
1168 switch (clues[j] & CMASK) {
1169 case C_ADD: *p++ = 'a'; break;
1170 case C_SUB: *p++ = 's'; break;
1171 case C_MUL: *p++ = 'm'; break;
1172 case C_DIV: *p++ = 'd'; break;
1174 p += sprintf(p, "%ld", clues[j] & ~CMASK);
1178 desc = sresize(desc, p - desc, char);
1181 * Encode the solution.
1183 assert(memcmp(soln, grid, a) == 0);
1184 *aux = snewn(a+2, char);
1186 for (i = 0; i < a; i++)
1187 (*aux)[i+1] = '0' + soln[i];
1202 /* ----------------------------------------------------------------------
1206 static const char *validate_desc(const game_params *params, const char *desc)
1208 int w = params->w, a = w*w;
1211 const char *p = desc;
1215 * Verify that the block structure makes sense.
1218 ret = parse_block_structure(&p, w, dsf);
1225 return "Expected ',' after block structure description";
1229 * Verify that the right number of clues are given, and that SUB
1230 * and DIV clues don't apply to blocks of the wrong size.
1232 for (i = 0; i < a; i++) {
1233 if (dsf_canonify(dsf, i) == i) {
1234 if (*p == 'a' || *p == 'm') {
1235 /* these clues need no validation */
1236 } else if (*p == 'd' || *p == 's') {
1237 if (dsf_size(dsf, i) != 2)
1238 return "Subtraction and division blocks must have area 2";
1240 return "Too few clues for block structure";
1242 return "Unrecognised clue type";
1245 while (*p && isdigit((unsigned char)*p)) p++;
1249 return "Too many clues for block structure";
1254 static game_state *new_game(midend *me, const game_params *params,
1257 int w = params->w, a = w*w;
1258 game_state *state = snew(game_state);
1259 const char *p = desc;
1262 state->par = *params; /* structure copy */
1263 state->clues = snew(struct clues);
1264 state->clues->refcount = 1;
1265 state->clues->w = w;
1266 state->clues->dsf = snew_dsf(a);
1267 parse_block_structure(&p, w, state->clues->dsf);
1272 state->clues->clues = snewn(a, long);
1273 for (i = 0; i < a; i++) {
1274 if (dsf_canonify(state->clues->dsf, i) == i) {
1285 assert(dsf_size(state->clues->dsf, i) == 2);
1289 assert(dsf_size(state->clues->dsf, i) == 2);
1292 assert(!"Bad description in new_game");
1296 while (*p && isdigit((unsigned char)*p)) p++;
1297 state->clues->clues[i] = clue;
1299 state->clues->clues[i] = 0;
1302 state->grid = snewn(a, digit);
1303 state->pencil = snewn(a, int);
1304 for (i = 0; i < a; i++) {
1306 state->pencil[i] = 0;
1309 state->completed = state->cheated = FALSE;
1314 static game_state *dup_game(const game_state *state)
1316 int w = state->par.w, a = w*w;
1317 game_state *ret = snew(game_state);
1319 ret->par = state->par; /* structure copy */
1321 ret->clues = state->clues;
1322 ret->clues->refcount++;
1324 ret->grid = snewn(a, digit);
1325 ret->pencil = snewn(a, int);
1326 memcpy(ret->grid, state->grid, a*sizeof(digit));
1327 memcpy(ret->pencil, state->pencil, a*sizeof(int));
1329 ret->completed = state->completed;
1330 ret->cheated = state->cheated;
1335 static void free_game(game_state *state)
1338 sfree(state->pencil);
1339 if (--state->clues->refcount <= 0) {
1340 sfree(state->clues->dsf);
1341 sfree(state->clues->clues);
1342 sfree(state->clues);
1347 static char *solve_game(const game_state *state, const game_state *currstate,
1348 const char *aux, const char **error)
1350 int w = state->par.w, a = w*w;
1358 soln = snewn(a, digit);
1361 ret = solver(w, state->clues->dsf, state->clues->clues,
1364 if (ret == diff_impossible) {
1365 *error = "No solution exists for this puzzle";
1367 } else if (ret == diff_ambiguous) {
1368 *error = "Multiple solutions exist for this puzzle";
1371 out = snewn(a+2, char);
1373 for (i = 0; i < a; i++)
1374 out[i+1] = '0' + soln[i];
1382 static int game_can_format_as_text_now(const game_params *params)
1387 static char *game_text_format(const game_state *state)
1394 * These are the coordinates of the currently highlighted
1395 * square on the grid, if hshow = 1.
1399 * This indicates whether the current highlight is a
1400 * pencil-mark one or a real one.
1404 * This indicates whether or not we're showing the highlight
1405 * (used to be hx = hy = -1); important so that when we're
1406 * using the cursor keys it doesn't keep coming back at a
1407 * fixed position. When hshow = 1, pressing a valid number
1408 * or letter key or Space will enter that number or letter in the grid.
1412 * This indicates whether we're using the highlight as a cursor;
1413 * it means that it doesn't vanish on a keypress, and that it is
1414 * allowed on immutable squares.
1419 static game_ui *new_ui(const game_state *state)
1421 game_ui *ui = snew(game_ui);
1423 ui->hx = ui->hy = 0;
1424 ui->hpencil = ui->hshow = ui->hcursor = 0;
1429 static void free_ui(game_ui *ui)
1434 static char *encode_ui(const game_ui *ui)
1439 static void decode_ui(game_ui *ui, const char *encoding)
1443 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1444 const game_state *newstate)
1446 int w = newstate->par.w;
1448 * We prevent pencil-mode highlighting of a filled square, unless
1449 * we're using the cursor keys. So if the user has just filled in
1450 * a square which we had a pencil-mode highlight in (by Undo, or
1451 * by Redo, or by Solve), then we cancel the highlight.
1453 if (ui->hshow && ui->hpencil && !ui->hcursor &&
1454 newstate->grid[ui->hy * w + ui->hx] != 0) {
1459 #define PREFERRED_TILESIZE 48
1460 #define TILESIZE (ds->tilesize)
1461 #define BORDER (TILESIZE / 2)
1462 #define GRIDEXTRA max((TILESIZE / 32),1)
1463 #define COORD(x) ((x)*TILESIZE + BORDER)
1464 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER)) / TILESIZE - 1)
1466 #define FLASH_TIME 0.4F
1468 #define DF_PENCIL_SHIFT 16
1469 #define DF_ERR_LATIN 0x8000
1470 #define DF_ERR_CLUE 0x4000
1471 #define DF_HIGHLIGHT 0x2000
1472 #define DF_HIGHLIGHT_PENCIL 0x1000
1473 #define DF_DIGIT_MASK 0x000F
1475 struct game_drawstate {
1480 char *minus_sign, *times_sign, *divide_sign;
1483 static int check_errors(const game_state *state, long *errors)
1485 int w = state->par.w, a = w*w;
1486 int i, j, x, y, errs = FALSE;
1490 cluevals = snewn(a, long);
1491 full = snewn(a, int);
1494 for (i = 0; i < a; i++) {
1499 for (i = 0; i < a; i++) {
1502 j = dsf_canonify(state->clues->dsf, i);
1504 cluevals[i] = state->grid[i];
1506 clue = state->clues->clues[j] & CMASK;
1510 cluevals[j] += state->grid[i];
1513 cluevals[j] *= state->grid[i];
1516 cluevals[j] = abs(cluevals[j] - state->grid[i]);
1520 int d1 = min(cluevals[j], state->grid[i]);
1521 int d2 = max(cluevals[j], state->grid[i]);
1522 if (d1 == 0 || d2 % d1 != 0)
1525 cluevals[j] = d2 / d1;
1531 if (!state->grid[i])
1535 for (i = 0; i < a; i++) {
1536 j = dsf_canonify(state->clues->dsf, i);
1538 if ((state->clues->clues[j] & ~CMASK) != cluevals[i]) {
1540 if (errors && full[j])
1541 errors[j] |= DF_ERR_CLUE;
1549 for (y = 0; y < w; y++) {
1550 int mask = 0, errmask = 0;
1551 for (x = 0; x < w; x++) {
1552 int bit = 1 << state->grid[y*w+x];
1553 errmask |= (mask & bit);
1557 if (mask != (1 << (w+1)) - (1 << 1)) {
1561 for (x = 0; x < w; x++)
1562 if (errmask & (1 << state->grid[y*w+x]))
1563 errors[y*w+x] |= DF_ERR_LATIN;
1568 for (x = 0; x < w; x++) {
1569 int mask = 0, errmask = 0;
1570 for (y = 0; y < w; y++) {
1571 int bit = 1 << state->grid[y*w+x];
1572 errmask |= (mask & bit);
1576 if (mask != (1 << (w+1)) - (1 << 1)) {
1580 for (y = 0; y < w; y++)
1581 if (errmask & (1 << state->grid[y*w+x]))
1582 errors[y*w+x] |= DF_ERR_LATIN;
1590 static char *interpret_move(const game_state *state, game_ui *ui,
1591 const game_drawstate *ds,
1592 int x, int y, int button)
1594 int w = state->par.w;
1598 button &= ~MOD_MASK;
1603 if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1604 if (button == LEFT_BUTTON) {
1605 if (tx == ui->hx && ty == ui->hy &&
1606 ui->hshow && ui->hpencil == 0) {
1617 if (button == RIGHT_BUTTON) {
1619 * Pencil-mode highlighting for non filled squares.
1621 if (state->grid[ty*w+tx] == 0) {
1622 if (tx == ui->hx && ty == ui->hy &&
1623 ui->hshow && ui->hpencil) {
1638 if (IS_CURSOR_MOVE(button)) {
1639 move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
1640 ui->hshow = ui->hcursor = 1;
1644 (button == CURSOR_SELECT)) {
1645 ui->hpencil = 1 - ui->hpencil;
1651 ((button >= '0' && button <= '9' && button - '0' <= w) ||
1652 button == CURSOR_SELECT2 || button == '\b')) {
1653 int n = button - '0';
1654 if (button == CURSOR_SELECT2 || button == '\b')
1658 * Can't make pencil marks in a filled square. This can only
1659 * become highlighted if we're using cursor keys.
1661 if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1664 sprintf(buf, "%c%d,%d,%d",
1665 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1667 if (!ui->hcursor) ui->hshow = 0;
1672 if (button == 'M' || button == 'm')
1678 static game_state *execute_move(const game_state *from, const char *move)
1680 int w = from->par.w, a = w*w;
1684 if (move[0] == 'S') {
1685 ret = dup_game(from);
1686 ret->completed = ret->cheated = TRUE;
1688 for (i = 0; i < a; i++) {
1689 if (move[i+1] < '1' || move[i+1] > '0'+w) {
1693 ret->grid[i] = move[i+1] - '0';
1697 if (move[a+1] != '\0') {
1703 } else if ((move[0] == 'P' || move[0] == 'R') &&
1704 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1705 x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1707 ret = dup_game(from);
1708 if (move[0] == 'P' && n > 0) {
1709 ret->pencil[y*w+x] ^= 1 << n;
1711 ret->grid[y*w+x] = n;
1712 ret->pencil[y*w+x] = 0;
1714 if (!ret->completed && !check_errors(ret, NULL))
1715 ret->completed = TRUE;
1718 } else if (move[0] == 'M') {
1720 * Fill in absolutely all pencil marks everywhere. (I
1721 * wouldn't use this for actual play, but it's a handy
1722 * starting point when following through a set of
1723 * diagnostics output by the standalone solver.)
1725 ret = dup_game(from);
1726 for (i = 0; i < a; i++) {
1728 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1732 return NULL; /* couldn't parse move string */
1735 /* ----------------------------------------------------------------------
1739 #define SIZE(w) ((w) * TILESIZE + 2*BORDER)
1741 static void game_compute_size(const game_params *params, int tilesize,
1744 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1745 struct { int tilesize; } ads, *ds = &ads;
1746 ads.tilesize = tilesize;
1748 *x = *y = SIZE(params->w);
1751 static void game_set_size(drawing *dr, game_drawstate *ds,
1752 const game_params *params, int tilesize)
1754 ds->tilesize = tilesize;
1757 static float *game_colours(frontend *fe, int *ncolours)
1759 float *ret = snewn(3 * NCOLOURS, float);
1761 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1763 ret[COL_GRID * 3 + 0] = 0.0F;
1764 ret[COL_GRID * 3 + 1] = 0.0F;
1765 ret[COL_GRID * 3 + 2] = 0.0F;
1767 ret[COL_USER * 3 + 0] = 0.0F;
1768 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1769 ret[COL_USER * 3 + 2] = 0.0F;
1771 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1772 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1773 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1775 ret[COL_ERROR * 3 + 0] = 1.0F;
1776 ret[COL_ERROR * 3 + 1] = 0.0F;
1777 ret[COL_ERROR * 3 + 2] = 0.0F;
1779 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1780 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1781 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1783 *ncolours = NCOLOURS;
1787 static const char *const minus_signs[] = { "\xE2\x88\x92", "-" };
1788 static const char *const times_signs[] = { "\xC3\x97", "*" };
1789 static const char *const divide_signs[] = { "\xC3\xB7", "/" };
1791 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1793 int w = state->par.w, a = w*w;
1794 struct game_drawstate *ds = snew(struct game_drawstate);
1798 ds->started = FALSE;
1799 ds->tiles = snewn(a, long);
1800 for (i = 0; i < a; i++)
1802 ds->errors = snewn(a, long);
1803 ds->minus_sign = text_fallback(dr, minus_signs, lenof(minus_signs));
1804 ds->times_sign = text_fallback(dr, times_signs, lenof(times_signs));
1805 ds->divide_sign = text_fallback(dr, divide_signs, lenof(divide_signs));
1810 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1814 sfree(ds->minus_sign);
1815 sfree(ds->times_sign);
1816 sfree(ds->divide_sign);
1820 static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
1821 int x, int y, long tile, int only_one_op)
1823 int w = clues->w /* , a = w*w */;
1828 tx = BORDER + x * TILESIZE + 1 + GRIDEXTRA;
1829 ty = BORDER + y * TILESIZE + 1 + GRIDEXTRA;
1833 cw = tw = TILESIZE-1-2*GRIDEXTRA;
1834 ch = th = TILESIZE-1-2*GRIDEXTRA;
1836 if (x > 0 && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, y*w+x-1))
1837 cx -= GRIDEXTRA, cw += GRIDEXTRA;
1838 if (x+1 < w && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, y*w+x+1))
1840 if (y > 0 && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, (y-1)*w+x))
1841 cy -= GRIDEXTRA, ch += GRIDEXTRA;
1842 if (y+1 < w && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, (y+1)*w+x))
1845 clip(dr, cx, cy, cw, ch);
1847 /* background needs erasing */
1848 draw_rect(dr, cx, cy, cw, ch,
1849 (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
1851 /* pencil-mode highlight */
1852 if (tile & DF_HIGHLIGHT_PENCIL) {
1856 coords[2] = cx+cw/2;
1859 coords[5] = cy+ch/2;
1860 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1864 * Draw the corners of thick lines in corner-adjacent squares,
1865 * which jut into this square by one pixel.
1867 if (x > 0 && y > 0 && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y-1)*w+x-1))
1868 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1869 if (x+1 < w && y > 0 && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y-1)*w+x+1))
1870 draw_rect(dr, tx+TILESIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1871 if (x > 0 && y+1 < w && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y+1)*w+x-1))
1872 draw_rect(dr, tx-GRIDEXTRA, ty+TILESIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1873 if (x+1 < w && y+1 < w && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y+1)*w+x+1))
1874 draw_rect(dr, tx+TILESIZE-1-2*GRIDEXTRA, ty+TILESIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1876 /* Draw the box clue. */
1877 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1878 long clue = clues->clues[y*w+x];
1879 long cluetype = clue & CMASK, clueval = clue & ~CMASK;
1880 int size = dsf_size(clues->dsf, y*w+x);
1882 * Special case of clue-drawing: a box with only one square
1883 * is written as just the number, with no operation, because
1884 * it doesn't matter whether the operation is ADD or MUL.
1885 * The generation code above should never produce puzzles
1886 * containing such a thing - I think they're inelegant - but
1887 * it's possible to type in game IDs from elsewhere, so I
1888 * want to display them right if so.
1890 sprintf (str, "%ld%s", clueval,
1891 (size == 1 || only_one_op ? "" :
1892 cluetype == C_ADD ? "+" :
1893 cluetype == C_SUB ? ds->minus_sign :
1894 cluetype == C_MUL ? ds->times_sign :
1895 /* cluetype == C_DIV ? */ ds->divide_sign));
1896 draw_text(dr, tx + GRIDEXTRA * 2, ty + GRIDEXTRA * 2 + TILESIZE/4,
1897 FONT_VARIABLE, TILESIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
1898 (tile & DF_ERR_CLUE ? COL_ERROR : COL_GRID), str);
1901 /* new number needs drawing? */
1902 if (tile & DF_DIGIT_MASK) {
1904 str[0] = (tile & DF_DIGIT_MASK) + '0';
1905 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1906 FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1907 (tile & DF_ERR_LATIN) ? COL_ERROR : COL_USER, str);
1912 int pw, ph, minph, pbest, fontsize;
1914 /* Count the pencil marks required. */
1915 for (i = 1, npencil = 0; i <= w; i++)
1916 if (tile & (1L << (i + DF_PENCIL_SHIFT)))
1923 * Determine the bounding rectangle within which we're going
1924 * to put the pencil marks.
1926 /* Start with the whole square */
1927 pl = tx + GRIDEXTRA;
1928 pr = pl + TILESIZE - GRIDEXTRA;
1929 pt = ty + GRIDEXTRA;
1930 pb = pt + TILESIZE - GRIDEXTRA;
1931 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1933 * Make space for the clue text.
1940 * We arrange our pencil marks in a grid layout, with
1941 * the number of rows and columns adjusted to allow the
1942 * maximum font size.
1944 * So now we work out what the grid size ought to be.
1949 for (pw = 3; pw < max(npencil,4); pw++) {
1952 ph = (npencil + pw - 1) / pw;
1953 ph = max(ph, minph);
1954 fw = (pr - pl) / (float)pw;
1955 fh = (pb - pt) / (float)ph;
1957 if (fs > bestsize) {
1964 ph = (npencil + pw - 1) / pw;
1965 ph = max(ph, minph);
1968 * Now we've got our grid dimensions, work out the pixel
1969 * size of a grid element, and round it to the nearest
1970 * pixel. (We don't want rounding errors to make the
1971 * grid look uneven at low pixel sizes.)
1973 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1976 * Centre the resulting figure in the square.
1978 pl = tx + (TILESIZE - fontsize * pw) / 2;
1979 pt = ty + (TILESIZE - fontsize * ph) / 2;
1982 * And move it down a bit if it's collided with some
1985 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1986 pt = max(pt, ty + GRIDEXTRA * 3 + TILESIZE/4);
1990 * Now actually draw the pencil marks.
1992 for (i = 1, j = 0; i <= w; i++)
1993 if (tile & (1L << (i + DF_PENCIL_SHIFT))) {
1994 int dx = j % pw, dy = j / pw;
1998 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1999 pt + fontsize * (2*dy+1) / 2,
2000 FONT_VARIABLE, fontsize,
2001 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
2009 draw_update(dr, cx, cy, cw, ch);
2012 static void game_redraw(drawing *dr, game_drawstate *ds,
2013 const game_state *oldstate, const game_state *state,
2014 int dir, const game_ui *ui,
2015 float animtime, float flashtime)
2017 int w = state->par.w /*, a = w*w */;
2022 * The initial contents of the window are not guaranteed and
2023 * can vary with front ends. To be on the safe side, all
2024 * games should start by drawing a big background-colour
2025 * rectangle covering the whole window.
2027 draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
2030 * Big containing rectangle.
2032 draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
2033 w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
2036 draw_update(dr, 0, 0, SIZE(w), SIZE(w));
2041 check_errors(state, ds->errors);
2043 for (y = 0; y < w; y++) {
2044 for (x = 0; x < w; x++) {
2047 if (state->grid[y*w+x])
2048 tile = state->grid[y*w+x];
2050 tile = (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;
2052 if (ui->hshow && ui->hx == x && ui->hy == y)
2053 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
2055 if (flashtime > 0 &&
2056 (flashtime <= FLASH_TIME/3 ||
2057 flashtime >= FLASH_TIME*2/3))
2058 tile |= DF_HIGHLIGHT; /* completion flash */
2060 tile |= ds->errors[y*w+x];
2062 if (ds->tiles[y*w+x] != tile) {
2063 ds->tiles[y*w+x] = tile;
2064 draw_tile(dr, ds, state->clues, x, y, tile,
2065 state->par.multiplication_only);
2071 static float game_anim_length(const game_state *oldstate,
2072 const game_state *newstate, int dir, game_ui *ui)
2077 static float game_flash_length(const game_state *oldstate,
2078 const game_state *newstate, int dir, game_ui *ui)
2080 if (!oldstate->completed && newstate->completed &&
2081 !oldstate->cheated && !newstate->cheated)
2086 static int game_status(const game_state *state)
2088 return state->completed ? +1 : 0;
2091 static int game_timing_state(const game_state *state, game_ui *ui)
2093 if (state->completed)
2098 static void game_print_size(const game_params *params, float *x, float *y)
2103 * We use 9mm squares by default, like Solo.
2105 game_compute_size(params, 900, &pw, &ph);
2111 * Subfunction to draw the thick lines between cells. In order to do
2112 * this using the line-drawing rather than rectangle-drawing API (so
2113 * as to get line thicknesses to scale correctly) and yet have
2114 * correctly mitred joins between lines, we must do this by tracing
2115 * the boundary of each sub-block and drawing it in one go as a
2118 static void outline_block_structure(drawing *dr, game_drawstate *ds,
2119 int w, int *dsf, int ink)
2124 int x, y, dx, dy, sx, sy, sdx, sdy;
2126 coords = snewn(4*a, int);
2129 * Iterate over all the blocks.
2131 for (i = 0; i < a; i++) {
2132 if (dsf_canonify(dsf, i) != i)
2136 * For each block, we need a starting square within it which
2137 * has a boundary at the left. Conveniently, we have one
2138 * right here, by construction.
2146 * Now begin tracing round the perimeter. At all
2147 * times, (x,y) describes some square within the
2148 * block, and (x+dx,y+dy) is some adjacent square
2149 * outside it; so the edge between those two squares
2150 * is always an edge of the block.
2152 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
2155 int cx, cy, tx, ty, nin;
2158 * Advance to the next edge, by looking at the two
2159 * squares beyond it. If they're both outside the block,
2160 * we turn right (by leaving x,y the same and rotating
2161 * dx,dy clockwise); if they're both inside, we turn
2162 * left (by rotating dx,dy anticlockwise and contriving
2163 * to leave x+dx,y+dy unchanged); if one of each, we go
2164 * straight on (and may enforce by assertion that
2165 * they're one of each the _right_ way round).
2170 nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2171 dsf_canonify(dsf, ty*w+tx) == i);
2174 nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2175 dsf_canonify(dsf, ty*w+tx) == i);
2184 } else if (nin == 2) {
2208 * Now enforce by assertion that we ended up
2209 * somewhere sensible.
2211 assert(x >= 0 && x < w && y >= 0 && y < w &&
2212 dsf_canonify(dsf, y*w+x) == i);
2213 assert(x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= w ||
2214 dsf_canonify(dsf, (y+dy)*w+(x+dx)) != i);
2217 * Record the point we just went past at one end of the
2218 * edge. To do this, we translate (x,y) down and right
2219 * by half a unit (so they're describing a point in the
2220 * _centre_ of the square) and then translate back again
2221 * in a manner rotated by dy and dx.
2224 cx = ((2*x+1) + dy + dx) / 2;
2225 cy = ((2*y+1) - dx + dy) / 2;
2226 coords[2*n+0] = BORDER + cx * TILESIZE;
2227 coords[2*n+1] = BORDER + cy * TILESIZE;
2230 } while (x != sx || y != sy || dx != sdx || dy != sdy);
2233 * That's our polygon; now draw it.
2235 draw_polygon(dr, coords, n, -1, ink);
2241 static void game_print(drawing *dr, const game_state *state, int tilesize)
2243 int w = state->par.w;
2244 int ink = print_mono_colour(dr, 0);
2246 char *minus_sign, *times_sign, *divide_sign;
2248 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2249 game_drawstate ads, *ds = &ads;
2250 game_set_size(dr, ds, NULL, tilesize);
2252 minus_sign = text_fallback(dr, minus_signs, lenof(minus_signs));
2253 times_sign = text_fallback(dr, times_signs, lenof(times_signs));
2254 divide_sign = text_fallback(dr, divide_signs, lenof(divide_signs));
2259 print_line_width(dr, 3 * TILESIZE / 40);
2260 draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);
2265 for (x = 1; x < w; x++) {
2266 print_line_width(dr, TILESIZE / 40);
2267 draw_line(dr, BORDER+x*TILESIZE, BORDER,
2268 BORDER+x*TILESIZE, BORDER+w*TILESIZE, ink);
2270 for (y = 1; y < w; y++) {
2271 print_line_width(dr, TILESIZE / 40);
2272 draw_line(dr, BORDER, BORDER+y*TILESIZE,
2273 BORDER+w*TILESIZE, BORDER+y*TILESIZE, ink);
2277 * Thick lines between cells.
2279 print_line_width(dr, 3 * TILESIZE / 40);
2280 outline_block_structure(dr, ds, w, state->clues->dsf, ink);
2285 for (y = 0; y < w; y++)
2286 for (x = 0; x < w; x++)
2287 if (dsf_canonify(state->clues->dsf, y*w+x) == y*w+x) {
2288 long clue = state->clues->clues[y*w+x];
2289 long cluetype = clue & CMASK, clueval = clue & ~CMASK;
2290 int size = dsf_size(state->clues->dsf, y*w+x);
2294 * As in the drawing code, we omit the operator for
2297 sprintf (str, "%ld%s", clueval,
2299 cluetype == C_ADD ? "+" :
2300 cluetype == C_SUB ? minus_sign :
2301 cluetype == C_MUL ? times_sign :
2302 /* cluetype == C_DIV ? */ divide_sign));
2305 BORDER+x*TILESIZE + 5*TILESIZE/80,
2306 BORDER+y*TILESIZE + 20*TILESIZE/80,
2307 FONT_VARIABLE, TILESIZE/4,
2308 ALIGN_VNORMAL | ALIGN_HLEFT,
2313 * Numbers for the solution, if any.
2315 for (y = 0; y < w; y++)
2316 for (x = 0; x < w; x++)
2317 if (state->grid[y*w+x]) {
2320 str[0] = state->grid[y*w+x] + '0';
2321 draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
2322 BORDER + y*TILESIZE + TILESIZE/2,
2323 FONT_VARIABLE, TILESIZE/2,
2324 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2333 #define thegame keen
2336 const struct game thegame = {
2337 "Keen", "games.keen", "keen",
2339 game_fetch_preset, NULL,
2344 TRUE, game_configure, custom_params,
2352 FALSE, game_can_format_as_text_now, game_text_format,
2360 PREFERRED_TILESIZE, game_compute_size, game_set_size,
2363 game_free_drawstate,
2368 TRUE, FALSE, game_print_size, game_print,
2369 FALSE, /* wants_statusbar */
2370 FALSE, game_timing_state,
2371 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
2374 #ifdef STANDALONE_SOLVER
2378 int main(int argc, char **argv)
2382 char *id = NULL, *desc;
2385 int ret, diff, really_show_working = FALSE;
2387 while (--argc > 0) {
2389 if (!strcmp(p, "-v")) {
2390 really_show_working = TRUE;
2391 } else if (!strcmp(p, "-g")) {
2393 } else if (*p == '-') {
2394 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2402 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2406 desc = strchr(id, ':');
2408 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2413 p = default_params();
2414 decode_params(p, id);
2415 err = validate_desc(p, desc);
2417 fprintf(stderr, "%s: %s\n", argv[0], err);
2420 s = new_game(NULL, p, desc);
2423 * When solving an Easy puzzle, we don't want to bother the
2424 * user with Hard-level deductions. For this reason, we grade
2425 * the puzzle internally before doing anything else.
2427 ret = -1; /* placate optimiser */
2428 solver_show_working = FALSE;
2429 for (diff = 0; diff < DIFFCOUNT; diff++) {
2430 memset(s->grid, 0, p->w * p->w);
2431 ret = solver(p->w, s->clues->dsf, s->clues->clues,
2437 if (diff == DIFFCOUNT) {
2439 printf("Difficulty rating: ambiguous\n");
2441 printf("Unable to find a unique solution\n");
2444 if (ret == diff_impossible)
2445 printf("Difficulty rating: impossible (no solution exists)\n");
2447 printf("Difficulty rating: %s\n", keen_diffnames[ret]);
2449 solver_show_working = really_show_working;
2450 memset(s->grid, 0, p->w * p->w);
2451 ret = solver(p->w, s->clues->dsf, s->clues->clues,
2454 printf("Puzzle is inconsistent\n");
2457 * We don't have a game_text_format for this game,
2458 * so we have to output the solution manually.
2461 for (y = 0; y < p->w; y++) {
2462 for (x = 0; x < p->w; x++) {
2463 printf("%s%c", x>0?" ":"", '0' + s->grid[y*p->w+x]);
2476 /* vim: set shiftwidth=4 tabstop=8: */