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].sval = dupstr(buf);
189 ret[1].name = "Difficulty";
190 ret[1].type = C_CHOICES;
191 ret[1].sval = DIFFCONFIG;
192 ret[1].ival = params->diff;
194 ret[2].name = "Multiplication only";
195 ret[2].type = C_BOOLEAN;
197 ret[2].ival = params->multiplication_only;
207 static game_params *custom_params(const config_item *cfg)
209 game_params *ret = snew(game_params);
211 ret->w = atoi(cfg[0].sval);
212 ret->diff = cfg[1].ival;
213 ret->multiplication_only = cfg[2].ival;
218 static char *validate_params(const game_params *params, int full)
220 if (params->w < 3 || params->w > 9)
221 return "Grid size must be between 3 and 9";
222 if (params->diff >= DIFFCOUNT)
223 return "Unknown difficulty rating";
227 /* ----------------------------------------------------------------------
234 int *boxes, *boxlist, *whichbox;
241 static void solver_clue_candidate(struct solver_ctx *ctx, int diff, int box)
244 int n = ctx->boxes[box+1] - ctx->boxes[box];
248 * This function is called from the main clue-based solver
249 * routine when we discover a candidate layout for a given clue
250 * box consistent with everything we currently know about the
251 * digit constraints in that box. We expect to find the digits
252 * of the candidate layout in ctx->dscratch, and we update
253 * ctx->iscratch as appropriate.
255 if (diff == DIFF_EASY) {
258 * Easy-mode clue deductions: we do not record information
259 * about which squares take which values, so we amalgamate
260 * all the values in dscratch and OR them all into
263 for (j = 0; j < n; j++)
264 mask |= 1 << ctx->dscratch[j];
265 for (j = 0; j < n; j++)
266 ctx->iscratch[j] |= mask;
267 } else if (diff == DIFF_NORMAL) {
269 * Normal-mode deductions: we process the information in
270 * dscratch in the obvious way.
272 for (j = 0; j < n; j++)
273 ctx->iscratch[j] |= 1 << ctx->dscratch[j];
274 } else if (diff == DIFF_HARD) {
276 * Hard-mode deductions: instead of ruling things out
277 * _inside_ the clue box, we look for numbers which occur in
278 * a given row or column in all candidate layouts, and rule
279 * them out of all squares in that row or column that
280 * _aren't_ part of this clue box.
282 int *sq = ctx->boxlist + ctx->boxes[box];
284 for (j = 0; j < 2*w; j++)
285 ctx->iscratch[2*w+j] = 0;
286 for (j = 0; j < n; j++) {
287 int x = sq[j] / w, y = sq[j] % w;
288 ctx->iscratch[2*w+x] |= 1 << ctx->dscratch[j];
289 ctx->iscratch[3*w+y] |= 1 << ctx->dscratch[j];
291 for (j = 0; j < 2*w; j++)
292 ctx->iscratch[j] &= ctx->iscratch[2*w+j];
296 static int solver_common(struct latin_solver *solver, void *vctx, int diff)
298 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
304 * Iterate over each clue box and deduce what we can.
306 for (box = 0; box < ctx->nboxes; box++) {
307 int *sq = ctx->boxlist + ctx->boxes[box];
308 int n = ctx->boxes[box+1] - ctx->boxes[box];
309 long value = ctx->clues[box] & ~CMASK;
310 long op = ctx->clues[box] & CMASK;
312 if (diff == DIFF_HARD) {
313 for (i = 0; i < n; i++)
314 ctx->iscratch[i] = (1 << (w+1)) - (1 << 1);
316 for (i = 0; i < n; i++)
317 ctx->iscratch[i] = 0;
324 * These two clue types must always apply to a box of
325 * area 2. Also, the two digits in these boxes can never
326 * be the same (because any domino must have its two
327 * squares in either the same row or the same column).
328 * So we simply iterate over all possibilities for the
329 * two squares (both ways round), rule out any which are
330 * inconsistent with the digit constraints we already
331 * have, and update the digit constraints with any new
332 * information thus garnered.
336 for (i = 1; i <= w; i++) {
337 j = (op == C_SUB ? i + value : i * value);
340 /* (i,j) is a valid digit pair. Try it both ways round. */
342 if (solver->cube[sq[0]*w+i-1] &&
343 solver->cube[sq[1]*w+j-1]) {
344 ctx->dscratch[0] = i;
345 ctx->dscratch[1] = j;
346 solver_clue_candidate(ctx, diff, box);
349 if (solver->cube[sq[0]*w+j-1] &&
350 solver->cube[sq[1]*w+i-1]) {
351 ctx->dscratch[0] = j;
352 ctx->dscratch[1] = i;
353 solver_clue_candidate(ctx, diff, box);
362 * For these clue types, I have no alternative but to go
363 * through all possible number combinations.
365 * Instead of a tedious physical recursion, I iterate in
366 * the scratch array through all possibilities. At any
367 * given moment, i indexes the element of the box that
368 * will next be incremented.
371 ctx->dscratch[i] = 0;
372 total = value; /* start with the identity */
376 * Find the next valid value for cell i.
378 for (j = ctx->dscratch[i] + 1; j <= w; j++) {
379 if (op == C_ADD ? (total < j) : (total % j != 0))
380 continue; /* this one won't fit */
381 if (!solver->cube[sq[i]*w+j-1])
382 continue; /* this one is ruled out already */
383 for (k = 0; k < i; k++)
384 if (ctx->dscratch[k] == j &&
385 (sq[k] % w == sq[i] % w ||
386 sq[k] / w == sq[i] / w))
387 break; /* clashes with another row/col */
396 /* No valid values left; drop back. */
399 break; /* overall iteration is finished */
401 total += ctx->dscratch[i];
403 total *= ctx->dscratch[i];
405 /* Got a valid value; store it and move on. */
406 ctx->dscratch[i++] = j;
411 ctx->dscratch[i] = 0;
414 if (total == (op == C_ADD ? 0 : 1))
415 solver_clue_candidate(ctx, diff, box);
418 total += ctx->dscratch[i];
420 total *= ctx->dscratch[i];
427 if (diff < DIFF_HARD) {
428 #ifdef STANDALONE_SOLVER
431 if (solver_show_working)
432 sprintf(prefix, "%*susing clue at (%d,%d):\n",
433 solver_recurse_depth*4, "",
434 sq[0]/w+1, sq[0]%w+1);
436 prefix[0] = '\0'; /* placate optimiser */
439 for (i = 0; i < n; i++)
440 for (j = 1; j <= w; j++) {
441 if (solver->cube[sq[i]*w+j-1] &&
442 !(ctx->iscratch[i] & (1 << j))) {
443 #ifdef STANDALONE_SOLVER
444 if (solver_show_working) {
445 printf("%s%*s ruling out %d at (%d,%d)\n",
446 prefix, solver_recurse_depth*4, "",
447 j, sq[i]/w+1, sq[i]%w+1);
451 solver->cube[sq[i]*w+j-1] = 0;
456 #ifdef STANDALONE_SOLVER
459 if (solver_show_working)
460 sprintf(prefix, "%*susing clue at (%d,%d):\n",
461 solver_recurse_depth*4, "",
462 sq[0]/w+1, sq[0]%w+1);
464 prefix[0] = '\0'; /* placate optimiser */
467 for (i = 0; i < 2*w; i++) {
468 int start = (i < w ? i*w : i-w);
469 int step = (i < w ? 1 : w);
470 for (j = 1; j <= w; j++) if (ctx->iscratch[i] & (1 << j)) {
471 #ifdef STANDALONE_SOLVER
474 if (solver_show_working)
475 sprintf(prefix2, "%*s this clue requires %d in"
476 " %s %d:\n", solver_recurse_depth*4, "",
477 j, i < w ? "column" : "row", i%w+1);
479 prefix2[0] = '\0'; /* placate optimiser */
482 for (k = 0; k < w; k++) {
483 int pos = start + k*step;
484 if (ctx->whichbox[pos] != box &&
485 solver->cube[pos*w+j-1]) {
486 #ifdef STANDALONE_SOLVER
487 if (solver_show_working) {
488 printf("%s%s%*s ruling out %d at (%d,%d)\n",
490 solver_recurse_depth*4, "",
491 j, pos/w+1, pos%w+1);
492 prefix[0] = prefix2[0] = '\0';
495 solver->cube[pos*w+j-1] = 0;
503 * Once we find one block we can do something with in
504 * this way, revert to trying easier deductions, so as
505 * not to generate solver diagnostics that make the
506 * problem look harder than it is. (We have to do this
507 * for the Hard deductions but not the Easy/Normal ones,
508 * because only the Hard deductions are cross-box.)
518 static int solver_easy(struct latin_solver *solver, void *vctx)
521 * Omit the EASY deductions when solving at NORMAL level, since
522 * the NORMAL deductions are a superset of them anyway and it
523 * saves on time and confusing solver diagnostics.
525 * Note that this breaks the natural semantics of the return
526 * value of latin_solver. Without this hack, you could determine
527 * a puzzle's difficulty in one go by trying to solve it at
528 * maximum difficulty and seeing what difficulty value was
529 * returned; but with this hack, solving an Easy puzzle on
530 * Normal difficulty will typically return Normal. Hence the
531 * uses of the solver to determine difficulty are all arranged
532 * so as to double-check by re-solving at the next difficulty
533 * level down and making sure it failed.
535 struct solver_ctx *ctx = (struct solver_ctx *)vctx;
536 if (ctx->diff > DIFF_EASY)
538 return solver_common(solver, vctx, DIFF_EASY);
541 static int solver_normal(struct latin_solver *solver, void *vctx)
543 return solver_common(solver, vctx, DIFF_NORMAL);
546 static int solver_hard(struct latin_solver *solver, void *vctx)
548 return solver_common(solver, vctx, DIFF_HARD);
551 #define SOLVER(upper,title,func,lower) func,
552 static usersolver_t const keen_solvers[] = { DIFFLIST(SOLVER) };
554 static int solver(int w, int *dsf, long *clues, digit *soln, int maxdiff)
557 struct solver_ctx ctx;
566 * Transform the dsf-formatted clue list into one over which we
567 * can iterate more easily.
569 * Also transpose the x- and y-coordinates at this point,
570 * because the 'cube' array in the general Latin square solver
571 * puts x first (oops).
573 for (ctx.nboxes = i = 0; i < a; i++)
574 if (dsf_canonify(dsf, i) == i)
576 ctx.boxlist = snewn(a, int);
577 ctx.boxes = snewn(ctx.nboxes+1, int);
578 ctx.clues = snewn(ctx.nboxes, long);
579 ctx.whichbox = snewn(a, int);
580 for (n = m = i = 0; i < a; i++)
581 if (dsf_canonify(dsf, i) == i) {
582 ctx.clues[n] = clues[i];
584 for (j = 0; j < a; j++)
585 if (dsf_canonify(dsf, j) == i) {
586 ctx.boxlist[m++] = (j % w) * w + (j / w); /* transpose */
587 ctx.whichbox[ctx.boxlist[m-1]] = n;
591 assert(n == ctx.nboxes);
595 ctx.dscratch = snewn(a+1, digit);
596 ctx.iscratch = snewn(max(a+1, 4*w), int);
598 ret = latin_solver(soln, w, maxdiff,
599 DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
600 DIFF_EXTREME, DIFF_UNREASONABLE,
601 keen_solvers, &ctx, NULL, NULL);
613 /* ----------------------------------------------------------------------
617 static char *encode_block_structure(char *p, int w, int *dsf)
620 char *orig, *q, *r, c;
625 * Encode the block structure. We do this by encoding the
626 * pattern of dividing lines: first we iterate over the w*(w-1)
627 * internal vertical grid lines in ordinary reading order, then
628 * over the w*(w-1) internal horizontal ones in transposed
631 * We encode the number of non-lines between the lines; _ means
632 * zero (two adjacent divisions), a means 1, ..., y means 25,
633 * and z means 25 non-lines _and no following line_ (so that za
634 * means 26, zb 27 etc).
636 for (i = 0; i <= 2*w*(w-1); i++) {
637 int x, y, p0, p1, edge;
639 if (i == 2*w*(w-1)) {
640 edge = TRUE; /* terminating virtual edge */
653 edge = (dsf_canonify(dsf, p0) != dsf_canonify(dsf, p1));
658 *p++ = 'z', currrun -= 25;
660 *p++ = 'a'-1 + currrun;
669 * Now go through and compress the string by replacing runs of
670 * the same letter with a single copy of that letter followed by
671 * a repeat count, where that makes it shorter. (This puzzle
672 * seems to generate enough long strings of _ to make this a
675 for (q = r = orig; r < p ;) {
678 for (i = 0; r+i < p && r[i] == c; i++);
684 q += sprintf(q, "%d", i);
691 static char *parse_block_structure(const char **p, int w, int *dsf)
695 int repc = 0, repn = 0;
699 while (**p && (repn > 0 || **p != ',')) {
705 } else if (**p == '_' || (**p >= 'a' && **p <= 'z')) {
706 c = (**p == '_' ? 0 : **p - 'a' + 1);
708 if (**p && isdigit((unsigned char)**p)) {
711 while (**p && isdigit((unsigned char)**p)) (*p)++;
714 return "Invalid character in game description";
716 adv = (c != 25); /* 'z' is a special case */
722 * Non-edge; merge the two dsf classes on either
725 if (pos >= 2*w*(w-1))
726 return "Too much data in block structure specification";
733 int x = pos/(w-1) - w;
738 dsf_merge(dsf, p0, p1);
744 if (pos > 2*w*(w-1)+1)
745 return "Too much data in block structure specification";
750 * When desc is exhausted, we expect to have gone exactly
751 * one space _past_ the end of the grid, due to the dummy
754 if (pos != 2*w*(w-1)+1)
755 return "Not enough data in block structure specification";
760 static char *new_game_desc(const game_params *params, random_state *rs,
761 char **aux, int interactive)
763 int w = params->w, a = w*w;
765 int *order, *revorder, *singletons, *dsf;
766 long *clues, *cluevals;
767 int i, j, k, n, x, y, ret;
768 int diff = params->diff;
772 * Difficulty exceptions: 3x3 puzzles at difficulty Hard or
773 * higher are currently not generable - the generator will spin
774 * forever looking for puzzles of the appropriate difficulty. We
775 * dial each of these down to the next lower difficulty.
777 * Remember to re-test this whenever a change is made to the
780 * I tested it using the following shell command:
782 for d in e n h x u; do
784 echo ./keen --generate 1 ${i}d${d}
785 perl -e 'alarm 30; exec @ARGV' ./keen --generate 5 ${i}d${d} >/dev/null \
790 * Of course, it's better to do that after taking the exceptions
791 * _out_, so as to detect exceptions that should be removed as
792 * well as those which should be added.
794 if (w == 3 && diff > DIFF_NORMAL)
799 order = snewn(a, int);
800 revorder = snewn(a, int);
801 singletons = snewn(a, int);
803 clues = snewn(a, long);
804 cluevals = snewn(a, long);
805 soln = snewn(a, digit);
809 * First construct a latin square to be the solution.
812 grid = latin_generate(w, rs);
815 * Divide the grid into arbitrarily sized blocks, but so as
816 * to arrange plenty of dominoes which can be SUB/DIV clues.
817 * We do this by first placing dominoes at random for a
818 * while, then tying the remaining singletons one by one
819 * into neighbouring blocks.
821 for (i = 0; i < a; i++)
823 shuffle(order, a, sizeof(*order), rs);
824 for (i = 0; i < a; i++)
825 revorder[order[i]] = i;
827 for (i = 0; i < a; i++)
828 singletons[i] = TRUE;
832 /* Place dominoes. */
833 for (i = 0; i < a; i++) {
840 if (x > 0 && singletons[i-1] &&
841 (best == -1 || revorder[i-1] < revorder[best]))
843 if (x+1 < w && singletons[i+1] &&
844 (best == -1 || revorder[i+1] < revorder[best]))
846 if (y > 0 && singletons[i-w] &&
847 (best == -1 || revorder[i-w] < revorder[best]))
849 if (y+1 < w && singletons[i+w] &&
850 (best == -1 || revorder[i+w] < revorder[best]))
854 * When we find a potential domino, we place it with
855 * probability 3/4, which seems to strike a decent
856 * balance between plenty of dominoes and leaving
857 * enough singletons to make interesting larger
860 if (best >= 0 && random_upto(rs, 4)) {
861 singletons[i] = singletons[best] = FALSE;
862 dsf_merge(dsf, i, best);
867 /* Fold in singletons. */
868 for (i = 0; i < a; i++) {
875 if (x > 0 && dsf_size(dsf, i-1) < MAXBLK &&
876 (best == -1 || revorder[i-1] < revorder[best]))
878 if (x+1 < w && dsf_size(dsf, i+1) < MAXBLK &&
879 (best == -1 || revorder[i+1] < revorder[best]))
881 if (y > 0 && dsf_size(dsf, i-w) < MAXBLK &&
882 (best == -1 || revorder[i-w] < revorder[best]))
884 if (y+1 < w && dsf_size(dsf, i+w) < MAXBLK &&
885 (best == -1 || revorder[i+w] < revorder[best]))
889 singletons[i] = singletons[best] = FALSE;
890 dsf_merge(dsf, i, best);
895 /* Quit and start again if we have any singletons left over
896 * which we weren't able to do anything at all with. */
897 for (i = 0; i < a; i++)
904 * Decide what would be acceptable clues for each block.
906 * Blocks larger than 2 have free choice of ADD or MUL;
907 * blocks of size 2 can be anything in principle (except
908 * that they can only be DIV if the two numbers have an
909 * integer quotient, of course), but we rule out (or try to
910 * avoid) some clues because they're of low quality.
912 * Hence, we iterate once over the grid, stopping at the
913 * canonical element of every >2 block and the _non_-
914 * canonical element of every 2-block; the latter means that
915 * we can make our decision about a 2-block in the knowledge
916 * of both numbers in it.
918 * We reuse the 'singletons' array (finished with in the
919 * above loop) to hold information about which blocks are
928 for (i = 0; i < a; i++) {
930 j = dsf_canonify(dsf, i);
931 k = dsf_size(dsf, j);
932 if (params->multiplication_only)
933 singletons[j] = F_MUL;
934 else if (j == i && k > 2) {
935 singletons[j] |= F_ADD | F_MUL;
936 } else if (j != i && k == 2) {
937 /* Fetch the two numbers and sort them into order. */
938 int p = grid[j], q = grid[i], v;
940 int t = p; p = q; q = t;
944 * Addition clues are always allowed, but we try to
945 * avoid sums of 3, 4, (2w-1) and (2w-2) if we can,
946 * because they're too easy - they only leave one
947 * option for the pair of numbers involved.
950 if (v > 4 && v < 2*w-2)
951 singletons[j] |= F_ADD;
953 singletons[j] |= F_ADD << BAD_SHIFT;
956 * Multiplication clues: above Normal difficulty, we
957 * prefer (but don't absolutely insist on) clues of
958 * this type which leave multiple options open.
962 for (k = 1; k <= w; k++)
963 if (v % k == 0 && v / k <= w && v / k != k)
965 if (n <= 2 && diff > DIFF_NORMAL)
966 singletons[j] |= F_MUL << BAD_SHIFT;
968 singletons[j] |= F_MUL;
971 * Subtraction: we completely avoid a difference of
976 singletons[j] |= F_SUB;
979 * Division: for a start, the quotient must be an
980 * integer or the clue type is impossible. Also, we
981 * never use quotients strictly greater than w/2,
982 * because they're not only too easy but also
985 if (p % q == 0 && 2 * (p / q) <= w)
986 singletons[j] |= F_DIV;
991 * Actually choose a clue for each block, trying to keep the
992 * numbers of each type even, and starting with the
993 * preferred candidates for each type where possible.
995 * I'm sure there should be a faster algorithm for doing
996 * this, but I can't be bothered: O(N^2) is good enough when
997 * N is at most the number of dominoes that fits into a 9x9
1000 shuffle(order, a, sizeof(*order), rs);
1001 for (i = 0; i < a; i++)
1004 int done_something = FALSE;
1006 for (k = 0; k < 4; k++) {
1010 case 0: clue = C_DIV; good = F_DIV; break;
1011 case 1: clue = C_SUB; good = F_SUB; break;
1012 case 2: clue = C_MUL; good = F_MUL; break;
1013 default /* case 3 */ : clue = C_ADD; good = F_ADD; break;
1016 for (i = 0; i < a; i++) {
1018 if (singletons[j] & good) {
1025 /* didn't find a nice one, use a nasty one */
1026 bad = good << BAD_SHIFT;
1027 for (i = 0; i < a; i++) {
1029 if (singletons[j] & bad) {
1037 done_something = TRUE;
1040 if (!done_something)
1050 * Having chosen the clue types, calculate the clue values.
1052 for (i = 0; i < a; i++) {
1053 j = dsf_canonify(dsf, i);
1055 cluevals[j] = grid[i];
1059 cluevals[j] += grid[i];
1062 cluevals[j] *= grid[i];
1065 cluevals[j] = abs(cluevals[j] - grid[i]);
1069 int d1 = cluevals[j], d2 = grid[i];
1070 if (d1 == 0 || d2 == 0)
1073 cluevals[j] = d2/d1 + d1/d2;/* one is 0 :-) */
1080 for (i = 0; i < a; i++) {
1081 j = dsf_canonify(dsf, i);
1083 clues[j] |= cluevals[j];
1088 * See if the game can be solved at the specified difficulty
1089 * level, but not at the one below.
1093 ret = solver(w, dsf, clues, soln, diff-1);
1098 ret = solver(w, dsf, clues, soln, diff);
1100 continue; /* go round again */
1103 * I wondered if at this point it would be worth trying to
1104 * merge adjacent blocks together, to make the puzzle
1105 * gradually more difficult if it's currently easier than
1106 * specced, increasing the chance of a given generation run
1109 * It doesn't seem to be critical for the generation speed,
1110 * though, so for the moment I'm leaving it out.
1114 * We've got a usable puzzle!
1120 * Encode the puzzle description.
1122 desc = snewn(40*a, char);
1124 p = encode_block_structure(p, w, dsf);
1126 for (i = 0; i < a; i++) {
1127 j = dsf_canonify(dsf, i);
1129 switch (clues[j] & CMASK) {
1130 case C_ADD: *p++ = 'a'; break;
1131 case C_SUB: *p++ = 's'; break;
1132 case C_MUL: *p++ = 'm'; break;
1133 case C_DIV: *p++ = 'd'; break;
1135 p += sprintf(p, "%ld", clues[j] & ~CMASK);
1139 desc = sresize(desc, p - desc, char);
1142 * Encode the solution.
1144 assert(memcmp(soln, grid, a) == 0);
1145 *aux = snewn(a+2, char);
1147 for (i = 0; i < a; i++)
1148 (*aux)[i+1] = '0' + soln[i];
1163 /* ----------------------------------------------------------------------
1167 static char *validate_desc(const game_params *params, const char *desc)
1169 int w = params->w, a = w*w;
1172 const char *p = desc;
1176 * Verify that the block structure makes sense.
1179 ret = parse_block_structure(&p, w, dsf);
1186 return "Expected ',' after block structure description";
1190 * Verify that the right number of clues are given, and that SUB
1191 * and DIV clues don't apply to blocks of the wrong size.
1193 for (i = 0; i < a; i++) {
1194 if (dsf_canonify(dsf, i) == i) {
1195 if (*p == 'a' || *p == 'm') {
1196 /* these clues need no validation */
1197 } else if (*p == 'd' || *p == 's') {
1198 if (dsf_size(dsf, i) != 2)
1199 return "Subtraction and division blocks must have area 2";
1201 return "Too few clues for block structure";
1203 return "Unrecognised clue type";
1206 while (*p && isdigit((unsigned char)*p)) p++;
1210 return "Too many clues for block structure";
1215 static game_state *new_game(midend *me, const game_params *params,
1218 int w = params->w, a = w*w;
1219 game_state *state = snew(game_state);
1220 const char *p = desc;
1223 state->par = *params; /* structure copy */
1224 state->clues = snew(struct clues);
1225 state->clues->refcount = 1;
1226 state->clues->w = w;
1227 state->clues->dsf = snew_dsf(a);
1228 parse_block_structure(&p, w, state->clues->dsf);
1233 state->clues->clues = snewn(a, long);
1234 for (i = 0; i < a; i++) {
1235 if (dsf_canonify(state->clues->dsf, i) == i) {
1246 assert(dsf_size(state->clues->dsf, i) == 2);
1250 assert(dsf_size(state->clues->dsf, i) == 2);
1253 assert(!"Bad description in new_game");
1257 while (*p && isdigit((unsigned char)*p)) p++;
1258 state->clues->clues[i] = clue;
1260 state->clues->clues[i] = 0;
1263 state->grid = snewn(a, digit);
1264 state->pencil = snewn(a, int);
1265 for (i = 0; i < a; i++) {
1267 state->pencil[i] = 0;
1270 state->completed = state->cheated = FALSE;
1275 static game_state *dup_game(const game_state *state)
1277 int w = state->par.w, a = w*w;
1278 game_state *ret = snew(game_state);
1280 ret->par = state->par; /* structure copy */
1282 ret->clues = state->clues;
1283 ret->clues->refcount++;
1285 ret->grid = snewn(a, digit);
1286 ret->pencil = snewn(a, int);
1287 memcpy(ret->grid, state->grid, a*sizeof(digit));
1288 memcpy(ret->pencil, state->pencil, a*sizeof(int));
1290 ret->completed = state->completed;
1291 ret->cheated = state->cheated;
1296 static void free_game(game_state *state)
1299 sfree(state->pencil);
1300 if (--state->clues->refcount <= 0) {
1301 sfree(state->clues->dsf);
1302 sfree(state->clues->clues);
1303 sfree(state->clues);
1308 static char *solve_game(const game_state *state, const game_state *currstate,
1309 const char *aux, char **error)
1311 int w = state->par.w, a = w*w;
1319 soln = snewn(a, digit);
1322 ret = solver(w, state->clues->dsf, state->clues->clues,
1325 if (ret == diff_impossible) {
1326 *error = "No solution exists for this puzzle";
1328 } else if (ret == diff_ambiguous) {
1329 *error = "Multiple solutions exist for this puzzle";
1332 out = snewn(a+2, char);
1334 for (i = 0; i < a; i++)
1335 out[i+1] = '0' + soln[i];
1343 static int game_can_format_as_text_now(const game_params *params)
1348 static char *game_text_format(const game_state *state)
1355 * These are the coordinates of the currently highlighted
1356 * square on the grid, if hshow = 1.
1360 * This indicates whether the current highlight is a
1361 * pencil-mark one or a real one.
1365 * This indicates whether or not we're showing the highlight
1366 * (used to be hx = hy = -1); important so that when we're
1367 * using the cursor keys it doesn't keep coming back at a
1368 * fixed position. When hshow = 1, pressing a valid number
1369 * or letter key or Space will enter that number or letter in the grid.
1373 * This indicates whether we're using the highlight as a cursor;
1374 * it means that it doesn't vanish on a keypress, and that it is
1375 * allowed on immutable squares.
1380 static game_ui *new_ui(const game_state *state)
1382 game_ui *ui = snew(game_ui);
1384 ui->hx = ui->hy = 0;
1385 ui->hpencil = ui->hshow = ui->hcursor = 0;
1390 static void free_ui(game_ui *ui)
1395 static char *encode_ui(const game_ui *ui)
1400 static void decode_ui(game_ui *ui, const char *encoding)
1404 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1405 const game_state *newstate)
1407 int w = newstate->par.w;
1409 * We prevent pencil-mode highlighting of a filled square, unless
1410 * we're using the cursor keys. So if the user has just filled in
1411 * a square which we had a pencil-mode highlight in (by Undo, or
1412 * by Redo, or by Solve), then we cancel the highlight.
1414 if (ui->hshow && ui->hpencil && !ui->hcursor &&
1415 newstate->grid[ui->hy * w + ui->hx] != 0) {
1420 #define PREFERRED_TILESIZE 48
1421 #define TILESIZE (ds->tilesize)
1422 #define BORDER (TILESIZE / 2)
1423 #define GRIDEXTRA max((TILESIZE / 32),1)
1424 #define COORD(x) ((x)*TILESIZE + BORDER)
1425 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER)) / TILESIZE - 1)
1427 #define FLASH_TIME 0.4F
1429 #define DF_PENCIL_SHIFT 16
1430 #define DF_ERR_LATIN 0x8000
1431 #define DF_ERR_CLUE 0x4000
1432 #define DF_HIGHLIGHT 0x2000
1433 #define DF_HIGHLIGHT_PENCIL 0x1000
1434 #define DF_DIGIT_MASK 0x000F
1436 struct game_drawstate {
1441 char *minus_sign, *times_sign, *divide_sign;
1444 static int check_errors(const game_state *state, long *errors)
1446 int w = state->par.w, a = w*w;
1447 int i, j, x, y, errs = FALSE;
1451 cluevals = snewn(a, long);
1452 full = snewn(a, int);
1455 for (i = 0; i < a; i++) {
1460 for (i = 0; i < a; i++) {
1463 j = dsf_canonify(state->clues->dsf, i);
1465 cluevals[i] = state->grid[i];
1467 clue = state->clues->clues[j] & CMASK;
1471 cluevals[j] += state->grid[i];
1474 cluevals[j] *= state->grid[i];
1477 cluevals[j] = abs(cluevals[j] - state->grid[i]);
1481 int d1 = min(cluevals[j], state->grid[i]);
1482 int d2 = max(cluevals[j], state->grid[i]);
1483 if (d1 == 0 || d2 % d1 != 0)
1486 cluevals[j] = d2 / d1;
1492 if (!state->grid[i])
1496 for (i = 0; i < a; i++) {
1497 j = dsf_canonify(state->clues->dsf, i);
1499 if ((state->clues->clues[j] & ~CMASK) != cluevals[i]) {
1501 if (errors && full[j])
1502 errors[j] |= DF_ERR_CLUE;
1510 for (y = 0; y < w; y++) {
1511 int mask = 0, errmask = 0;
1512 for (x = 0; x < w; x++) {
1513 int bit = 1 << state->grid[y*w+x];
1514 errmask |= (mask & bit);
1518 if (mask != (1 << (w+1)) - (1 << 1)) {
1522 for (x = 0; x < w; x++)
1523 if (errmask & (1 << state->grid[y*w+x]))
1524 errors[y*w+x] |= DF_ERR_LATIN;
1529 for (x = 0; x < w; x++) {
1530 int mask = 0, errmask = 0;
1531 for (y = 0; y < w; y++) {
1532 int bit = 1 << state->grid[y*w+x];
1533 errmask |= (mask & bit);
1537 if (mask != (1 << (w+1)) - (1 << 1)) {
1541 for (y = 0; y < w; y++)
1542 if (errmask & (1 << state->grid[y*w+x]))
1543 errors[y*w+x] |= DF_ERR_LATIN;
1551 static char *interpret_move(const game_state *state, game_ui *ui,
1552 const game_drawstate *ds,
1553 int x, int y, int button)
1555 int w = state->par.w;
1559 button &= ~MOD_MASK;
1564 if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1565 if (button == LEFT_BUTTON) {
1566 if (tx == ui->hx && ty == ui->hy &&
1567 ui->hshow && ui->hpencil == 0) {
1576 return ""; /* UI activity occurred */
1578 if (button == RIGHT_BUTTON) {
1580 * Pencil-mode highlighting for non filled squares.
1582 if (state->grid[ty*w+tx] == 0) {
1583 if (tx == ui->hx && ty == ui->hy &&
1584 ui->hshow && ui->hpencil) {
1596 return ""; /* UI activity occurred */
1599 if (IS_CURSOR_MOVE(button)) {
1600 move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
1601 ui->hshow = ui->hcursor = 1;
1605 (button == CURSOR_SELECT)) {
1606 ui->hpencil = 1 - ui->hpencil;
1612 ((button >= '0' && button <= '9' && button - '0' <= w) ||
1613 button == CURSOR_SELECT2 || button == '\b')) {
1614 int n = button - '0';
1615 if (button == CURSOR_SELECT2 || button == '\b')
1619 * Can't make pencil marks in a filled square. This can only
1620 * become highlighted if we're using cursor keys.
1622 if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1625 sprintf(buf, "%c%d,%d,%d",
1626 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1628 if (!ui->hcursor) ui->hshow = 0;
1633 if (button == 'M' || button == 'm')
1639 static game_state *execute_move(const game_state *from, const char *move)
1641 int w = from->par.w, a = w*w;
1645 if (move[0] == 'S') {
1646 ret = dup_game(from);
1647 ret->completed = ret->cheated = TRUE;
1649 for (i = 0; i < a; i++) {
1650 if (move[i+1] < '1' || move[i+1] > '0'+w) {
1654 ret->grid[i] = move[i+1] - '0';
1658 if (move[a+1] != '\0') {
1664 } else if ((move[0] == 'P' || move[0] == 'R') &&
1665 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1666 x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1668 ret = dup_game(from);
1669 if (move[0] == 'P' && n > 0) {
1670 ret->pencil[y*w+x] ^= 1 << n;
1672 ret->grid[y*w+x] = n;
1673 ret->pencil[y*w+x] = 0;
1675 if (!ret->completed && !check_errors(ret, NULL))
1676 ret->completed = TRUE;
1679 } else if (move[0] == 'M') {
1681 * Fill in absolutely all pencil marks everywhere. (I
1682 * wouldn't use this for actual play, but it's a handy
1683 * starting point when following through a set of
1684 * diagnostics output by the standalone solver.)
1686 ret = dup_game(from);
1687 for (i = 0; i < a; i++) {
1689 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1693 return NULL; /* couldn't parse move string */
1696 /* ----------------------------------------------------------------------
1700 #define SIZE(w) ((w) * TILESIZE + 2*BORDER)
1702 static void game_compute_size(const game_params *params, int tilesize,
1705 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1706 struct { int tilesize; } ads, *ds = &ads;
1707 ads.tilesize = tilesize;
1709 *x = *y = SIZE(params->w);
1712 static void game_set_size(drawing *dr, game_drawstate *ds,
1713 const game_params *params, int tilesize)
1715 ds->tilesize = tilesize;
1718 static float *game_colours(frontend *fe, int *ncolours)
1720 float *ret = snewn(3 * NCOLOURS, float);
1722 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1724 ret[COL_GRID * 3 + 0] = 0.0F;
1725 ret[COL_GRID * 3 + 1] = 0.0F;
1726 ret[COL_GRID * 3 + 2] = 0.0F;
1728 ret[COL_USER * 3 + 0] = 0.0F;
1729 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1730 ret[COL_USER * 3 + 2] = 0.0F;
1732 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1733 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1734 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1736 ret[COL_ERROR * 3 + 0] = 1.0F;
1737 ret[COL_ERROR * 3 + 1] = 0.0F;
1738 ret[COL_ERROR * 3 + 2] = 0.0F;
1740 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1741 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1742 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1744 *ncolours = NCOLOURS;
1748 static const char *const minus_signs[] = { "\xE2\x88\x92", "-" };
1749 static const char *const times_signs[] = { "\xC3\x97", "*" };
1750 static const char *const divide_signs[] = { "\xC3\xB7", "/" };
1752 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1754 int w = state->par.w, a = w*w;
1755 struct game_drawstate *ds = snew(struct game_drawstate);
1759 ds->started = FALSE;
1760 ds->tiles = snewn(a, long);
1761 for (i = 0; i < a; i++)
1763 ds->errors = snewn(a, long);
1764 ds->minus_sign = text_fallback(dr, minus_signs, lenof(minus_signs));
1765 ds->times_sign = text_fallback(dr, times_signs, lenof(times_signs));
1766 ds->divide_sign = text_fallback(dr, divide_signs, lenof(divide_signs));
1771 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1775 sfree(ds->minus_sign);
1776 sfree(ds->times_sign);
1777 sfree(ds->divide_sign);
1781 static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
1782 int x, int y, long tile, int only_one_op)
1784 int w = clues->w /* , a = w*w */;
1789 tx = BORDER + x * TILESIZE + 1 + GRIDEXTRA;
1790 ty = BORDER + y * TILESIZE + 1 + GRIDEXTRA;
1794 cw = tw = TILESIZE-1-2*GRIDEXTRA;
1795 ch = th = TILESIZE-1-2*GRIDEXTRA;
1797 if (x > 0 && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, y*w+x-1))
1798 cx -= GRIDEXTRA, cw += GRIDEXTRA;
1799 if (x+1 < w && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, y*w+x+1))
1801 if (y > 0 && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, (y-1)*w+x))
1802 cy -= GRIDEXTRA, ch += GRIDEXTRA;
1803 if (y+1 < w && dsf_canonify(clues->dsf, y*w+x) == dsf_canonify(clues->dsf, (y+1)*w+x))
1806 clip(dr, cx, cy, cw, ch);
1808 /* background needs erasing */
1809 draw_rect(dr, cx, cy, cw, ch,
1810 (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
1812 /* pencil-mode highlight */
1813 if (tile & DF_HIGHLIGHT_PENCIL) {
1817 coords[2] = cx+cw/2;
1820 coords[5] = cy+ch/2;
1821 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1825 * Draw the corners of thick lines in corner-adjacent squares,
1826 * which jut into this square by one pixel.
1828 if (x > 0 && y > 0 && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y-1)*w+x-1))
1829 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1830 if (x+1 < w && y > 0 && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y-1)*w+x+1))
1831 draw_rect(dr, tx+TILESIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1832 if (x > 0 && y+1 < w && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y+1)*w+x-1))
1833 draw_rect(dr, tx-GRIDEXTRA, ty+TILESIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1834 if (x+1 < w && y+1 < w && dsf_canonify(clues->dsf, y*w+x) != dsf_canonify(clues->dsf, (y+1)*w+x+1))
1835 draw_rect(dr, tx+TILESIZE-1-2*GRIDEXTRA, ty+TILESIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
1837 /* Draw the box clue. */
1838 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1839 long clue = clues->clues[y*w+x];
1840 long cluetype = clue & CMASK, clueval = clue & ~CMASK;
1841 int size = dsf_size(clues->dsf, y*w+x);
1843 * Special case of clue-drawing: a box with only one square
1844 * is written as just the number, with no operation, because
1845 * it doesn't matter whether the operation is ADD or MUL.
1846 * The generation code above should never produce puzzles
1847 * containing such a thing - I think they're inelegant - but
1848 * it's possible to type in game IDs from elsewhere, so I
1849 * want to display them right if so.
1851 sprintf (str, "%ld%s", clueval,
1852 (size == 1 || only_one_op ? "" :
1853 cluetype == C_ADD ? "+" :
1854 cluetype == C_SUB ? ds->minus_sign :
1855 cluetype == C_MUL ? ds->times_sign :
1856 /* cluetype == C_DIV ? */ ds->divide_sign));
1857 draw_text(dr, tx + GRIDEXTRA * 2, ty + GRIDEXTRA * 2 + TILESIZE/4,
1858 FONT_VARIABLE, TILESIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
1859 (tile & DF_ERR_CLUE ? COL_ERROR : COL_GRID), str);
1862 /* new number needs drawing? */
1863 if (tile & DF_DIGIT_MASK) {
1865 str[0] = (tile & DF_DIGIT_MASK) + '0';
1866 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1867 FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1868 (tile & DF_ERR_LATIN) ? COL_ERROR : COL_USER, str);
1873 int pw, ph, minph, pbest, fontsize;
1875 /* Count the pencil marks required. */
1876 for (i = 1, npencil = 0; i <= w; i++)
1877 if (tile & (1L << (i + DF_PENCIL_SHIFT)))
1884 * Determine the bounding rectangle within which we're going
1885 * to put the pencil marks.
1887 /* Start with the whole square */
1888 pl = tx + GRIDEXTRA;
1889 pr = pl + TILESIZE - GRIDEXTRA;
1890 pt = ty + GRIDEXTRA;
1891 pb = pt + TILESIZE - GRIDEXTRA;
1892 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1894 * Make space for the clue text.
1901 * We arrange our pencil marks in a grid layout, with
1902 * the number of rows and columns adjusted to allow the
1903 * maximum font size.
1905 * So now we work out what the grid size ought to be.
1910 for (pw = 3; pw < max(npencil,4); pw++) {
1913 ph = (npencil + pw - 1) / pw;
1914 ph = max(ph, minph);
1915 fw = (pr - pl) / (float)pw;
1916 fh = (pb - pt) / (float)ph;
1918 if (fs > bestsize) {
1925 ph = (npencil + pw - 1) / pw;
1926 ph = max(ph, minph);
1929 * Now we've got our grid dimensions, work out the pixel
1930 * size of a grid element, and round it to the nearest
1931 * pixel. (We don't want rounding errors to make the
1932 * grid look uneven at low pixel sizes.)
1934 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1937 * Centre the resulting figure in the square.
1939 pl = tx + (TILESIZE - fontsize * pw) / 2;
1940 pt = ty + (TILESIZE - fontsize * ph) / 2;
1943 * And move it down a bit if it's collided with some
1946 if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1947 pt = max(pt, ty + GRIDEXTRA * 3 + TILESIZE/4);
1951 * Now actually draw the pencil marks.
1953 for (i = 1, j = 0; i <= w; i++)
1954 if (tile & (1L << (i + DF_PENCIL_SHIFT))) {
1955 int dx = j % pw, dy = j / pw;
1959 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1960 pt + fontsize * (2*dy+1) / 2,
1961 FONT_VARIABLE, fontsize,
1962 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1970 draw_update(dr, cx, cy, cw, ch);
1973 static void game_redraw(drawing *dr, game_drawstate *ds,
1974 const game_state *oldstate, const game_state *state,
1975 int dir, const game_ui *ui,
1976 float animtime, float flashtime)
1978 int w = state->par.w /*, a = w*w */;
1983 * The initial contents of the window are not guaranteed and
1984 * can vary with front ends. To be on the safe side, all
1985 * games should start by drawing a big background-colour
1986 * rectangle covering the whole window.
1988 draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1991 * Big containing rectangle.
1993 draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1994 w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1997 draw_update(dr, 0, 0, SIZE(w), SIZE(w));
2002 check_errors(state, ds->errors);
2004 for (y = 0; y < w; y++) {
2005 for (x = 0; x < w; x++) {
2008 if (state->grid[y*w+x])
2009 tile = state->grid[y*w+x];
2011 tile = (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;
2013 if (ui->hshow && ui->hx == x && ui->hy == y)
2014 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
2016 if (flashtime > 0 &&
2017 (flashtime <= FLASH_TIME/3 ||
2018 flashtime >= FLASH_TIME*2/3))
2019 tile |= DF_HIGHLIGHT; /* completion flash */
2021 tile |= ds->errors[y*w+x];
2023 if (ds->tiles[y*w+x] != tile) {
2024 ds->tiles[y*w+x] = tile;
2025 draw_tile(dr, ds, state->clues, x, y, tile,
2026 state->par.multiplication_only);
2032 static float game_anim_length(const game_state *oldstate,
2033 const game_state *newstate, int dir, game_ui *ui)
2038 static float game_flash_length(const game_state *oldstate,
2039 const game_state *newstate, int dir, game_ui *ui)
2041 if (!oldstate->completed && newstate->completed &&
2042 !oldstate->cheated && !newstate->cheated)
2047 static int game_status(const game_state *state)
2049 return state->completed ? +1 : 0;
2052 static int game_timing_state(const game_state *state, game_ui *ui)
2054 if (state->completed)
2059 static void game_print_size(const game_params *params, float *x, float *y)
2064 * We use 9mm squares by default, like Solo.
2066 game_compute_size(params, 900, &pw, &ph);
2072 * Subfunction to draw the thick lines between cells. In order to do
2073 * this using the line-drawing rather than rectangle-drawing API (so
2074 * as to get line thicknesses to scale correctly) and yet have
2075 * correctly mitred joins between lines, we must do this by tracing
2076 * the boundary of each sub-block and drawing it in one go as a
2079 static void outline_block_structure(drawing *dr, game_drawstate *ds,
2080 int w, int *dsf, int ink)
2085 int x, y, dx, dy, sx, sy, sdx, sdy;
2087 coords = snewn(4*a, int);
2090 * Iterate over all the blocks.
2092 for (i = 0; i < a; i++) {
2093 if (dsf_canonify(dsf, i) != i)
2097 * For each block, we need a starting square within it which
2098 * has a boundary at the left. Conveniently, we have one
2099 * right here, by construction.
2107 * Now begin tracing round the perimeter. At all
2108 * times, (x,y) describes some square within the
2109 * block, and (x+dx,y+dy) is some adjacent square
2110 * outside it; so the edge between those two squares
2111 * is always an edge of the block.
2113 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
2116 int cx, cy, tx, ty, nin;
2119 * Advance to the next edge, by looking at the two
2120 * squares beyond it. If they're both outside the block,
2121 * we turn right (by leaving x,y the same and rotating
2122 * dx,dy clockwise); if they're both inside, we turn
2123 * left (by rotating dx,dy anticlockwise and contriving
2124 * to leave x+dx,y+dy unchanged); if one of each, we go
2125 * straight on (and may enforce by assertion that
2126 * they're one of each the _right_ way round).
2131 nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2132 dsf_canonify(dsf, ty*w+tx) == i);
2135 nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2136 dsf_canonify(dsf, ty*w+tx) == i);
2145 } else if (nin == 2) {
2169 * Now enforce by assertion that we ended up
2170 * somewhere sensible.
2172 assert(x >= 0 && x < w && y >= 0 && y < w &&
2173 dsf_canonify(dsf, y*w+x) == i);
2174 assert(x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= w ||
2175 dsf_canonify(dsf, (y+dy)*w+(x+dx)) != i);
2178 * Record the point we just went past at one end of the
2179 * edge. To do this, we translate (x,y) down and right
2180 * by half a unit (so they're describing a point in the
2181 * _centre_ of the square) and then translate back again
2182 * in a manner rotated by dy and dx.
2185 cx = ((2*x+1) + dy + dx) / 2;
2186 cy = ((2*y+1) - dx + dy) / 2;
2187 coords[2*n+0] = BORDER + cx * TILESIZE;
2188 coords[2*n+1] = BORDER + cy * TILESIZE;
2191 } while (x != sx || y != sy || dx != sdx || dy != sdy);
2194 * That's our polygon; now draw it.
2196 draw_polygon(dr, coords, n, -1, ink);
2202 static void game_print(drawing *dr, const game_state *state, int tilesize)
2204 int w = state->par.w;
2205 int ink = print_mono_colour(dr, 0);
2207 char *minus_sign, *times_sign, *divide_sign;
2209 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2210 game_drawstate ads, *ds = &ads;
2211 game_set_size(dr, ds, NULL, tilesize);
2213 minus_sign = text_fallback(dr, minus_signs, lenof(minus_signs));
2214 times_sign = text_fallback(dr, times_signs, lenof(times_signs));
2215 divide_sign = text_fallback(dr, divide_signs, lenof(divide_signs));
2220 print_line_width(dr, 3 * TILESIZE / 40);
2221 draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);
2226 for (x = 1; x < w; x++) {
2227 print_line_width(dr, TILESIZE / 40);
2228 draw_line(dr, BORDER+x*TILESIZE, BORDER,
2229 BORDER+x*TILESIZE, BORDER+w*TILESIZE, ink);
2231 for (y = 1; y < w; y++) {
2232 print_line_width(dr, TILESIZE / 40);
2233 draw_line(dr, BORDER, BORDER+y*TILESIZE,
2234 BORDER+w*TILESIZE, BORDER+y*TILESIZE, ink);
2238 * Thick lines between cells.
2240 print_line_width(dr, 3 * TILESIZE / 40);
2241 outline_block_structure(dr, ds, w, state->clues->dsf, ink);
2246 for (y = 0; y < w; y++)
2247 for (x = 0; x < w; x++)
2248 if (dsf_canonify(state->clues->dsf, y*w+x) == y*w+x) {
2249 long clue = state->clues->clues[y*w+x];
2250 long cluetype = clue & CMASK, clueval = clue & ~CMASK;
2251 int size = dsf_size(state->clues->dsf, y*w+x);
2255 * As in the drawing code, we omit the operator for
2258 sprintf (str, "%ld%s", clueval,
2260 cluetype == C_ADD ? "+" :
2261 cluetype == C_SUB ? minus_sign :
2262 cluetype == C_MUL ? times_sign :
2263 /* cluetype == C_DIV ? */ divide_sign));
2266 BORDER+x*TILESIZE + 5*TILESIZE/80,
2267 BORDER+y*TILESIZE + 20*TILESIZE/80,
2268 FONT_VARIABLE, TILESIZE/4,
2269 ALIGN_VNORMAL | ALIGN_HLEFT,
2274 * Numbers for the solution, if any.
2276 for (y = 0; y < w; y++)
2277 for (x = 0; x < w; x++)
2278 if (state->grid[y*w+x]) {
2281 str[0] = state->grid[y*w+x] + '0';
2282 draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
2283 BORDER + y*TILESIZE + TILESIZE/2,
2284 FONT_VARIABLE, TILESIZE/2,
2285 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2294 #define thegame keen
2297 const struct game thegame = {
2298 "Keen", "games.keen", "keen",
2305 TRUE, game_configure, custom_params,
2313 FALSE, game_can_format_as_text_now, game_text_format,
2321 PREFERRED_TILESIZE, game_compute_size, game_set_size,
2324 game_free_drawstate,
2329 TRUE, FALSE, game_print_size, game_print,
2330 FALSE, /* wants_statusbar */
2331 FALSE, game_timing_state,
2332 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
2335 #ifdef STANDALONE_SOLVER
2339 int main(int argc, char **argv)
2343 char *id = NULL, *desc, *err;
2345 int ret, diff, really_show_working = FALSE;
2347 while (--argc > 0) {
2349 if (!strcmp(p, "-v")) {
2350 really_show_working = TRUE;
2351 } else if (!strcmp(p, "-g")) {
2353 } else if (*p == '-') {
2354 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2362 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2366 desc = strchr(id, ':');
2368 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2373 p = default_params();
2374 decode_params(p, id);
2375 err = validate_desc(p, desc);
2377 fprintf(stderr, "%s: %s\n", argv[0], err);
2380 s = new_game(NULL, p, desc);
2383 * When solving an Easy puzzle, we don't want to bother the
2384 * user with Hard-level deductions. For this reason, we grade
2385 * the puzzle internally before doing anything else.
2387 ret = -1; /* placate optimiser */
2388 solver_show_working = FALSE;
2389 for (diff = 0; diff < DIFFCOUNT; diff++) {
2390 memset(s->grid, 0, p->w * p->w);
2391 ret = solver(p->w, s->clues->dsf, s->clues->clues,
2397 if (diff == DIFFCOUNT) {
2399 printf("Difficulty rating: ambiguous\n");
2401 printf("Unable to find a unique solution\n");
2404 if (ret == diff_impossible)
2405 printf("Difficulty rating: impossible (no solution exists)\n");
2407 printf("Difficulty rating: %s\n", keen_diffnames[ret]);
2409 solver_show_working = really_show_working;
2410 memset(s->grid, 0, p->w * p->w);
2411 ret = solver(p->w, s->clues->dsf, s->clues->clues,
2414 printf("Puzzle is inconsistent\n");
2417 * We don't have a game_text_format for this game,
2418 * so we have to output the solution manually.
2421 for (y = 0; y < p->w; y++) {
2422 for (x = 0; x < p->w; x++) {
2423 printf("%s%c", x>0?" ":"", '0' + s->grid[y*p->w+x]);
2436 /* vim: set shiftwidth=4 tabstop=8: */