chiark / gitweb /
Make the code base clean under -Wwrite-strings.
[sgt-puzzles.git] / keen.c
1 /*
2  * keen.c: an implementation of the Times's 'KenKen' puzzle, and
3  * also of Nikoli's very similar 'Inshi No Heya' puzzle.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <math.h>
12
13 #include "puzzles.h"
14 #include "latin.h"
15
16 /*
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.
19  */
20 #define DIFFLIST(A) \
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)
34
35 /*
36  * Clue notation. Important here that ADD and MUL come before SUB
37  * and DIV, and that DIV comes last. 
38  */
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
45
46 /*
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
50  * to iterate over).
51  */
52 #define MAXBLK 6
53
54 enum {
55     COL_BACKGROUND,
56     COL_GRID,
57     COL_USER,
58     COL_HIGHLIGHT,
59     COL_ERROR,
60     COL_PENCIL,
61     NCOLOURS
62 };
63
64 struct game_params {
65     int w, diff, multiplication_only;
66 };
67
68 struct clues {
69     int refcount;
70     int w;
71     int *dsf;
72     long *clues;
73 };
74
75 struct game_state {
76     game_params par;
77     struct clues *clues;
78     digit *grid;
79     int *pencil;                       /* bitmaps using bits 1<<1..1<<n */
80     int completed, cheated;
81 };
82
83 static game_params *default_params(void)
84 {
85     game_params *ret = snew(game_params);
86
87     ret->w = 6;
88     ret->diff = DIFF_NORMAL;
89     ret->multiplication_only = FALSE;
90
91     return ret;
92 }
93
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 },
105 };
106
107 static int game_fetch_preset(int i, char **name, game_params **params)
108 {
109     game_params *ret;
110     char buf[80];
111
112     if (i < 0 || i >= lenof(keen_presets))
113         return FALSE;
114
115     ret = snew(game_params);
116     *ret = keen_presets[i]; /* structure copy */
117
118     sprintf(buf, "%dx%d %s%s", ret->w, ret->w, keen_diffnames[ret->diff],
119             ret->multiplication_only ? ", multiplication only" : "");
120
121     *name = dupstr(buf);
122     *params = ret;
123     return TRUE;
124 }
125
126 static void free_params(game_params *params)
127 {
128     sfree(params);
129 }
130
131 static game_params *dup_params(const game_params *params)
132 {
133     game_params *ret = snew(game_params);
134     *ret = *params;                    /* structure copy */
135     return ret;
136 }
137
138 static void decode_params(game_params *params, char const *string)
139 {
140     char const *p = string;
141
142     params->w = atoi(p);
143     while (*p && isdigit((unsigned char)*p)) p++;
144
145     if (*p == 'd') {
146         int i;
147         p++;
148         params->diff = DIFFCOUNT+1; /* ...which is invalid */
149         if (*p) {
150             for (i = 0; i < DIFFCOUNT; i++) {
151                 if (*p == keen_diffchars[i])
152                     params->diff = i;
153             }
154             p++;
155         }
156     }
157
158     if (*p == 'm') {
159         p++;
160         params->multiplication_only = TRUE;
161     }
162 }
163
164 static char *encode_params(const game_params *params, int full)
165 {
166     char ret[80];
167
168     sprintf(ret, "%d", params->w);
169     if (full)
170         sprintf(ret + strlen(ret), "d%c%s", keen_diffchars[params->diff],
171                 params->multiplication_only ? "m" : "");
172
173     return dupstr(ret);
174 }
175
176 static config_item *game_configure(const game_params *params)
177 {
178     config_item *ret;
179     char buf[80];
180
181     ret = snewn(4, config_item);
182
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);
187
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;
192
193     ret[2].name = "Multiplication only";
194     ret[2].type = C_BOOLEAN;
195     ret[2].u.boolean.bval = params->multiplication_only;
196
197     ret[3].name = NULL;
198     ret[3].type = C_END;
199
200     return ret;
201 }
202
203 static game_params *custom_params(const config_item *cfg)
204 {
205     game_params *ret = snew(game_params);
206
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;
210
211     return ret;
212 }
213
214 static const char *validate_params(const game_params *params, int full)
215 {
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";
220     return NULL;
221 }
222
223 /* ----------------------------------------------------------------------
224  * Solver.
225  */
226
227 struct solver_ctx {
228     int w, diff;
229     int nboxes;
230     int *boxes, *boxlist, *whichbox;
231     long *clues;
232     digit *soln;
233     digit *dscratch;
234     int *iscratch;
235 };
236
237 static void solver_clue_candidate(struct solver_ctx *ctx, int diff, int box)
238 {
239     int w = ctx->w;
240     int n = ctx->boxes[box+1] - ctx->boxes[box];
241     int j;
242
243     /*
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.
250      *
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.
257      *
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
267      * knowledge).
268      *
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.
280      */
281     if (diff == DIFF_EASY) {
282         unsigned mask = 0;
283         /*
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
287          * everywhere.
288          */
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) {
294         /*
295          * Normal-mode deductions: we process the information in
296          * dscratch in the obvious way.
297          */
298         for (j = 0; j < n; j++)
299             ctx->iscratch[j] |= 1 << ctx->dscratch[j];
300     } else if (diff == DIFF_HARD) {
301         /*
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.
307          */
308         int *sq = ctx->boxlist + ctx->boxes[box];
309
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];
316         }
317         for (j = 0; j < 2*w; j++)
318             ctx->iscratch[j] &= ctx->iscratch[2*w+j];
319     }
320 }
321
322 static int solver_common(struct latin_solver *solver, void *vctx, int diff)
323 {
324     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
325     int w = ctx->w;
326     int box, i, j, k;
327     int ret = 0, total;
328
329     /*
330      * Iterate over each clue box and deduce what we can.
331      */
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;
337
338         /*
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.
343          */
344         if (diff == DIFF_HARD) {
345             for (i = 0; i < 2*w; i++)
346                 ctx->iscratch[i] = (1 << (w+1)) - (1 << 1);
347         } else {
348             for (i = 0; i < n; i++)
349                 ctx->iscratch[i] = 0;
350         }
351
352         switch (op) {
353           case C_SUB:
354           case C_DIV:
355             /*
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.
365              */
366             assert(n == 2);
367
368             for (i = 1; i <= w; i++) {
369                 j = (op == C_SUB ? i + value : i * value);
370                 if (j > w) break;
371
372                 /* (i,j) is a valid digit pair. Try it both ways round. */
373
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);
379                 }
380
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);
386                 }
387             }
388
389             break;
390
391           case C_ADD:
392           case C_MUL:
393             /*
394              * For these clue types, I have no alternative but to go
395              * through all possible number combinations.
396              *
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.
401              */
402             i = 0;
403             ctx->dscratch[i] = 0;
404             total = value;             /* start with the identity */
405             while (1) {
406                 if (i < n) {
407                     /*
408                      * Find the next valid value for cell i.
409                      */
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 */
420                         if (k < i)
421                             continue;
422
423                         /* Found one. */
424                         break;
425                     }
426
427                     if (j > w) {
428                         /* No valid values left; drop back. */
429                         i--;
430                         if (i < 0)
431                             break;     /* overall iteration is finished */
432                         if (op == C_ADD)
433                             total += ctx->dscratch[i];
434                         else
435                             total *= ctx->dscratch[i];
436                     } else {
437                         /* Got a valid value; store it and move on. */
438                         ctx->dscratch[i++] = j;
439                         if (op == C_ADD)
440                             total -= j;
441                         else
442                             total /= j;
443                         ctx->dscratch[i] = 0;
444                     }
445                 } else {
446                     if (total == (op == C_ADD ? 0 : 1))
447                         solver_clue_candidate(ctx, diff, box);
448                     i--;
449                     if (op == C_ADD)
450                         total += ctx->dscratch[i];
451                     else
452                         total *= ctx->dscratch[i];
453                 }
454             }
455
456             break;
457         }
458
459         /*
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).
465          */
466         if (diff < DIFF_HARD) {
467 #ifdef STANDALONE_SOLVER
468             char prefix[256];
469
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);
474             else
475                 prefix[0] = '\0';              /* placate optimiser */
476 #endif
477
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);
487                             prefix[0] = '\0';
488                         }
489 #endif
490                         solver->cube[sq[i]*w+j-1] = 0;
491                         ret = 1;
492                     }
493                 }
494         } else {
495 #ifdef STANDALONE_SOLVER
496             char prefix[256];
497
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);
502             else
503                 prefix[0] = '\0';              /* placate optimiser */
504 #endif
505
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
511                     char prefix2[256];
512
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);
517                     else
518                         prefix2[0] = '\0';   /* placate optimiser */
519 #endif
520
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",
528                                        prefix, prefix2,
529                                        solver_recurse_depth*4, "",
530                                        j, pos/w+1, pos%w+1);
531                                 prefix[0] = prefix2[0] = '\0';
532                             }
533 #endif
534                             solver->cube[pos*w+j-1] = 0;
535                             ret = 1;
536                         }
537                     }
538                 }
539             }
540
541             /*
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.)
548              */
549             if (ret)
550                 return ret;
551         }
552     }
553
554     return ret;
555 }
556
557 static int solver_easy(struct latin_solver *solver, void *vctx)
558 {
559     /*
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.
563      *
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.
573      */
574     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
575     if (ctx->diff > DIFF_EASY)
576         return 0;
577     return solver_common(solver, vctx, DIFF_EASY);
578 }
579
580 static int solver_normal(struct latin_solver *solver, void *vctx)
581 {
582     return solver_common(solver, vctx, DIFF_NORMAL);
583 }
584
585 static int solver_hard(struct latin_solver *solver, void *vctx)
586 {
587     return solver_common(solver, vctx, DIFF_HARD);
588 }
589
590 #define SOLVER(upper,title,func,lower) func,
591 static usersolver_t const keen_solvers[] = { DIFFLIST(SOLVER) };
592
593 static int solver(int w, int *dsf, long *clues, digit *soln, int maxdiff)
594 {
595     int a = w*w;
596     struct solver_ctx ctx;
597     int ret;
598     int i, j, n, m;
599     
600     ctx.w = w;
601     ctx.soln = soln;
602     ctx.diff = maxdiff;
603
604     /*
605      * Transform the dsf-formatted clue list into one over which we
606      * can iterate more easily.
607      *
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).
611      */
612     for (ctx.nboxes = i = 0; i < a; i++)
613         if (dsf_canonify(dsf, i) == i)
614             ctx.nboxes++;
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];
622             ctx.boxes[n] = m;
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;
627                 }
628             n++;
629         }
630     assert(n == ctx.nboxes);
631     assert(m == a);
632     ctx.boxes[n] = m;
633
634     ctx.dscratch = snewn(a+1, digit);
635     ctx.iscratch = snewn(max(a+1, 4*w), int);
636
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);
641
642     sfree(ctx.dscratch);
643     sfree(ctx.iscratch);
644     sfree(ctx.whichbox);
645     sfree(ctx.boxlist);
646     sfree(ctx.boxes);
647     sfree(ctx.clues);
648
649     return ret;
650 }
651
652 /* ----------------------------------------------------------------------
653  * Grid generation.
654  */
655
656 static char *encode_block_structure(char *p, int w, int *dsf)
657 {
658     int i, currrun = 0;
659     char *orig, *q, *r, c;
660
661     orig = p;
662
663     /*
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
668      * reading order.
669      *
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).
674      */
675     for (i = 0; i <= 2*w*(w-1); i++) {
676         int x, y, p0, p1, edge;
677
678         if (i == 2*w*(w-1)) {
679             edge = TRUE;       /* terminating virtual edge */
680         } else {
681             if (i < w*(w-1)) {
682                 y = i/(w-1);
683                 x = i%(w-1);
684                 p0 = y*w+x;
685                 p1 = y*w+x+1;
686             } else {
687                 x = i/(w-1) - w;
688                 y = i%(w-1);
689                 p0 = y*w+x;
690                 p1 = (y+1)*w+x;
691             }
692             edge = (dsf_canonify(dsf, p0) != dsf_canonify(dsf, p1));
693         }
694
695         if (edge) {
696             while (currrun > 25)
697                 *p++ = 'z', currrun -= 25;
698             if (currrun)
699                 *p++ = 'a'-1 + currrun;
700             else
701                 *p++ = '_';
702             currrun = 0;
703         } else
704             currrun++;
705     }
706
707     /*
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
712      * worthwhile step.)
713      */
714     for (q = r = orig; r < p ;) {
715         *q++ = c = *r;
716
717         for (i = 0; r+i < p && r[i] == c; i++);
718         r += i;
719
720         if (i == 2) {
721             *q++ = c;
722         } else if (i > 2) {
723             q += sprintf(q, "%d", i);
724         }
725     }
726     
727     return q;
728 }
729
730 static const char *parse_block_structure(const char **p, int w, int *dsf)
731 {
732     int a = w*w;
733     int pos = 0;
734     int repc = 0, repn = 0;
735
736     dsf_init(dsf, a);
737
738     while (**p && (repn > 0 || **p != ',')) {
739         int c, adv;
740
741         if (repn > 0) {
742             repn--;
743             c = repc;
744         } else if (**p == '_' || (**p >= 'a' && **p <= 'z')) {
745             c = (**p == '_' ? 0 : **p - 'a' + 1);
746             (*p)++;
747             if (**p && isdigit((unsigned char)**p)) {
748                 repc = c;
749                 repn = atoi(*p)-1;
750                 while (**p && isdigit((unsigned char)**p)) (*p)++;
751             }
752         } else
753             return "Invalid character in game description";
754
755         adv = (c != 25);               /* 'z' is a special case */
756
757         while (c-- > 0) {
758             int p0, p1;
759
760             /*
761              * Non-edge; merge the two dsf classes on either
762              * side of it.
763              */
764             if (pos >= 2*w*(w-1))
765                 return "Too much data in block structure specification";
766             if (pos < w*(w-1)) {
767                 int y = pos/(w-1);
768                 int x = pos%(w-1);
769                 p0 = y*w+x;
770                 p1 = y*w+x+1;
771             } else {
772                 int x = pos/(w-1) - w;
773                 int y = pos%(w-1);
774                 p0 = y*w+x;
775                 p1 = (y+1)*w+x;
776             }
777             dsf_merge(dsf, p0, p1);
778
779             pos++;
780         }
781         if (adv) {
782             pos++;
783             if (pos > 2*w*(w-1)+1)
784                 return "Too much data in block structure specification";
785         }
786     }
787
788     /*
789      * When desc is exhausted, we expect to have gone exactly
790      * one space _past_ the end of the grid, due to the dummy
791      * edge at the end.
792      */
793     if (pos != 2*w*(w-1)+1)
794         return "Not enough data in block structure specification";
795
796     return NULL;
797 }
798
799 static char *new_game_desc(const game_params *params, random_state *rs,
800                            char **aux, int interactive)
801 {
802     int w = params->w, a = w*w;
803     digit *grid, *soln;
804     int *order, *revorder, *singletons, *dsf;
805     long *clues, *cluevals;
806     int i, j, k, n, x, y, ret;
807     int diff = params->diff;
808     char *desc, *p;
809
810     /*
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.
815      *
816      * Remember to re-test this whenever a change is made to the
817      * solver logic!
818      *
819      * I tested it using the following shell command:
820
821 for d in e n h x u; do
822   for i in {3..9}; do
823     echo ./keen --generate 1 ${i}d${d}
824     perl -e 'alarm 30; exec @ARGV' ./keen --generate 5 ${i}d${d} >/dev/null \
825       || echo broken
826   done
827 done
828
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.
832      */
833     if (w == 3 && diff > DIFF_NORMAL)
834         diff = DIFF_NORMAL;
835
836     grid = NULL;
837
838     order = snewn(a, int);
839     revorder = snewn(a, int);
840     singletons = snewn(a, int);
841     dsf = snew_dsf(a);
842     clues = snewn(a, long);
843     cluevals = snewn(a, long);
844     soln = snewn(a, digit);
845
846     while (1) {
847         /*
848          * First construct a latin square to be the solution.
849          */
850         sfree(grid);
851         grid = latin_generate(w, rs);
852
853         /*
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.
859          */
860         for (i = 0; i < a; i++)
861             order[i] = i;
862         shuffle(order, a, sizeof(*order), rs);
863         for (i = 0; i < a; i++)
864             revorder[order[i]] = i;
865
866         for (i = 0; i < a; i++)
867             singletons[i] = TRUE;
868
869         dsf_init(dsf, a);
870
871         /* Place dominoes. */
872         for (i = 0; i < a; i++) {
873             if (singletons[i]) {
874                 int best = -1;
875
876                 x = i % w;
877                 y = i / w;
878
879                 if (x > 0 && singletons[i-1] &&
880                     (best == -1 || revorder[i-1] < revorder[best]))
881                     best = i-1;
882                 if (x+1 < w && singletons[i+1] &&
883                     (best == -1 || revorder[i+1] < revorder[best]))
884                     best = i+1;
885                 if (y > 0 && singletons[i-w] &&
886                     (best == -1 || revorder[i-w] < revorder[best]))
887                     best = i-w;
888                 if (y+1 < w && singletons[i+w] &&
889                     (best == -1 || revorder[i+w] < revorder[best]))
890                     best = i+w;
891
892                 /*
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
897                  * shapes.
898                  */
899                 if (best >= 0 && random_upto(rs, 4)) {
900                     singletons[i] = singletons[best] = FALSE;
901                     dsf_merge(dsf, i, best);
902                 }
903             }
904         }
905
906         /* Fold in singletons. */
907         for (i = 0; i < a; i++) {
908             if (singletons[i]) {
909                 int best = -1;
910
911                 x = i % w;
912                 y = i / w;
913
914                 if (x > 0 && dsf_size(dsf, i-1) < MAXBLK &&
915                     (best == -1 || revorder[i-1] < revorder[best]))
916                     best = i-1;
917                 if (x+1 < w && dsf_size(dsf, i+1) < MAXBLK &&
918                     (best == -1 || revorder[i+1] < revorder[best]))
919                     best = i+1;
920                 if (y > 0 && dsf_size(dsf, i-w) < MAXBLK &&
921                     (best == -1 || revorder[i-w] < revorder[best]))
922                     best = i-w;
923                 if (y+1 < w && dsf_size(dsf, i+w) < MAXBLK &&
924                     (best == -1 || revorder[i+w] < revorder[best]))
925                     best = i+w;
926
927                 if (best >= 0) {
928                     singletons[i] = singletons[best] = FALSE;
929                     dsf_merge(dsf, i, best);
930                 }
931             }
932         }
933
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++)
937             if (singletons[i])
938                 break;
939         if (i < a)
940             continue;
941
942         /*
943          * Decide what would be acceptable clues for each block.
944          *
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.
950          *
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.
956          *
957          * We reuse the 'singletons' array (finished with in the
958          * above loop) to hold information about which blocks are
959          * suitable for what.
960          */
961 #define F_ADD     0x01
962 #define F_SUB     0x02
963 #define F_MUL     0x04
964 #define F_DIV     0x08
965 #define BAD_SHIFT 4
966
967         for (i = 0; i < a; i++) {
968             singletons[i] = 0;
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;
978                 if (p < q) {
979                     int t = p; p = q; q = t;
980                 }
981
982                 /*
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.
987                  */
988                 v = p + q;
989                 if (v > 4 && v < 2*w-2)
990                     singletons[j] |= F_ADD;
991                 else
992                     singletons[j] |= F_ADD << BAD_SHIFT;
993
994                 /*
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.
998                  */
999                 v = p * q;
1000                 n = 0;
1001                 for (k = 1; k <= w; k++)
1002                     if (v % k == 0 && v / k <= w && v / k != k)
1003                         n++;
1004                 if (n <= 2 && diff > DIFF_NORMAL)
1005                     singletons[j] |= F_MUL << BAD_SHIFT;
1006                 else
1007                     singletons[j] |= F_MUL;
1008
1009                 /*
1010                  * Subtraction: we completely avoid a difference of
1011                  * w-1.
1012                  */
1013                 v = p - q;
1014                 if (v < w-1)
1015                     singletons[j] |= F_SUB;
1016
1017                 /*
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
1022                  * inelegant.
1023                  */
1024                 if (p % q == 0 && 2 * (p / q) <= w)
1025                     singletons[j] |= F_DIV;
1026             }
1027         }
1028
1029         /*
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.
1033          *
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
1037          * square.
1038          */
1039         shuffle(order, a, sizeof(*order), rs);
1040         for (i = 0; i < a; i++)
1041             clues[i] = 0;
1042         while (1) {
1043             int done_something = FALSE;
1044
1045             for (k = 0; k < 4; k++) {
1046                 long clue;
1047                 int good, bad;
1048                 switch (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;
1053                 }
1054
1055                 for (i = 0; i < a; i++) {
1056                     j = order[i];
1057                     if (singletons[j] & good) {
1058                         clues[j] = clue;
1059                         singletons[j] = 0;
1060                         break;
1061                     }
1062                 }
1063                 if (i == a) {
1064                     /* didn't find a nice one, use a nasty one */
1065                     bad = good << BAD_SHIFT;
1066                     for (i = 0; i < a; i++) {
1067                         j = order[i];
1068                         if (singletons[j] & bad) {
1069                             clues[j] = clue;
1070                             singletons[j] = 0;
1071                             break;
1072                         }
1073                     }
1074                 }
1075                 if (i < a)
1076                     done_something = TRUE;
1077             }
1078
1079             if (!done_something)
1080                 break;
1081         }
1082 #undef F_ADD
1083 #undef F_SUB
1084 #undef F_MUL
1085 #undef F_DIV
1086 #undef BAD_SHIFT
1087
1088         /*
1089          * Having chosen the clue types, calculate the clue values.
1090          */
1091         for (i = 0; i < a; i++) {
1092             j = dsf_canonify(dsf, i);
1093             if (j == i) {
1094                 cluevals[j] = grid[i];
1095             } else {
1096                 switch (clues[j]) {
1097                   case C_ADD:
1098                     cluevals[j] += grid[i];
1099                     break;
1100                   case C_MUL:
1101                     cluevals[j] *= grid[i];
1102                     break;
1103                   case C_SUB:
1104                     cluevals[j] = abs(cluevals[j] - grid[i]);
1105                     break;
1106                   case C_DIV:
1107                     {
1108                         int d1 = cluevals[j], d2 = grid[i];
1109                         if (d1 == 0 || d2 == 0)
1110                             cluevals[j] = 0;
1111                         else
1112                             cluevals[j] = d2/d1 + d1/d2;/* one is 0 :-) */
1113                     }
1114                     break;
1115                 }
1116             }
1117         }
1118
1119         for (i = 0; i < a; i++) {
1120             j = dsf_canonify(dsf, i);
1121             if (j == i) {
1122                 clues[j] |= cluevals[j];
1123             }
1124         }
1125
1126         /*
1127          * See if the game can be solved at the specified difficulty
1128          * level, but not at the one below.
1129          */
1130         if (diff > 0) {
1131             memset(soln, 0, a);
1132             ret = solver(w, dsf, clues, soln, diff-1);
1133             if (ret <= diff-1)
1134                 continue;
1135         }
1136         memset(soln, 0, a);
1137         ret = solver(w, dsf, clues, soln, diff);
1138         if (ret != diff)
1139             continue;                  /* go round again */
1140
1141         /*
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
1146          * being successful.
1147          *
1148          * It doesn't seem to be critical for the generation speed,
1149          * though, so for the moment I'm leaving it out.
1150          */
1151
1152         /*
1153          * We've got a usable puzzle!
1154          */
1155         break;
1156     }
1157
1158     /*
1159      * Encode the puzzle description.
1160      */
1161     desc = snewn(40*a, char);
1162     p = desc;
1163     p = encode_block_structure(p, w, dsf);
1164     *p++ = ',';
1165     for (i = 0; i < a; i++) {
1166         j = dsf_canonify(dsf, i);
1167         if (j == 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;
1173             }
1174             p += sprintf(p, "%ld", clues[j] & ~CMASK);
1175         }
1176     }
1177     *p++ = '\0';
1178     desc = sresize(desc, p - desc, char);
1179
1180     /*
1181      * Encode the solution.
1182      */
1183     assert(memcmp(soln, grid, a) == 0);
1184     *aux = snewn(a+2, char);
1185     (*aux)[0] = 'S';
1186     for (i = 0; i < a; i++)
1187         (*aux)[i+1] = '0' + soln[i];
1188     (*aux)[a+1] = '\0';
1189
1190     sfree(grid);
1191     sfree(order);
1192     sfree(revorder);
1193     sfree(singletons);
1194     sfree(dsf);
1195     sfree(clues);
1196     sfree(cluevals);
1197     sfree(soln);
1198
1199     return desc;
1200 }
1201
1202 /* ----------------------------------------------------------------------
1203  * Gameplay.
1204  */
1205
1206 static const char *validate_desc(const game_params *params, const char *desc)
1207 {
1208     int w = params->w, a = w*w;
1209     int *dsf;
1210     const char *ret;
1211     const char *p = desc;
1212     int i;
1213
1214     /*
1215      * Verify that the block structure makes sense.
1216      */
1217     dsf = snew_dsf(a);
1218     ret = parse_block_structure(&p, w, dsf);
1219     if (ret) {
1220         sfree(dsf);
1221         return ret;
1222     }
1223
1224     if (*p != ',')
1225         return "Expected ',' after block structure description";
1226     p++;
1227
1228     /*
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.
1231      */
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";
1239             } else if (!*p) {
1240                 return "Too few clues for block structure";
1241             } else {
1242                 return "Unrecognised clue type";
1243             }
1244             p++;
1245             while (*p && isdigit((unsigned char)*p)) p++;
1246         }
1247     }
1248     if (*p)
1249         return "Too many clues for block structure";
1250
1251     return NULL;
1252 }
1253
1254 static game_state *new_game(midend *me, const game_params *params,
1255                             const char *desc)
1256 {
1257     int w = params->w, a = w*w;
1258     game_state *state = snew(game_state);
1259     const char *p = desc;
1260     int i;
1261
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);
1268
1269     assert(*p == ',');
1270     p++;
1271
1272     state->clues->clues = snewn(a, long);
1273     for (i = 0; i < a; i++) {
1274         if (dsf_canonify(state->clues->dsf, i) == i) {
1275             long clue = 0;
1276             switch (*p) {
1277               case 'a':
1278                 clue = C_ADD;
1279                 break;
1280               case 'm':
1281                 clue = C_MUL;
1282                 break;
1283               case 's':
1284                 clue = C_SUB;
1285                 assert(dsf_size(state->clues->dsf, i) == 2);
1286                 break;
1287               case 'd':
1288                 clue = C_DIV;
1289                 assert(dsf_size(state->clues->dsf, i) == 2);
1290                 break;
1291               default:
1292                 assert(!"Bad description in new_game");
1293             }
1294             p++;
1295             clue |= atol(p);
1296             while (*p && isdigit((unsigned char)*p)) p++;
1297             state->clues->clues[i] = clue;
1298         } else
1299             state->clues->clues[i] = 0;
1300     }
1301
1302     state->grid = snewn(a, digit);
1303     state->pencil = snewn(a, int);
1304     for (i = 0; i < a; i++) {
1305         state->grid[i] = 0;
1306         state->pencil[i] = 0;
1307     }
1308
1309     state->completed = state->cheated = FALSE;
1310
1311     return state;
1312 }
1313
1314 static game_state *dup_game(const game_state *state)
1315 {
1316     int w = state->par.w, a = w*w;
1317     game_state *ret = snew(game_state);
1318
1319     ret->par = state->par;             /* structure copy */
1320
1321     ret->clues = state->clues;
1322     ret->clues->refcount++;
1323
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));
1328
1329     ret->completed = state->completed;
1330     ret->cheated = state->cheated;
1331
1332     return ret;
1333 }
1334
1335 static void free_game(game_state *state)
1336 {
1337     sfree(state->grid);
1338     sfree(state->pencil);
1339     if (--state->clues->refcount <= 0) {
1340         sfree(state->clues->dsf);
1341         sfree(state->clues->clues);
1342         sfree(state->clues);
1343     }
1344     sfree(state);
1345 }
1346
1347 static char *solve_game(const game_state *state, const game_state *currstate,
1348                         const char *aux, const char **error)
1349 {
1350     int w = state->par.w, a = w*w;
1351     int i, ret;
1352     digit *soln;
1353     char *out;
1354
1355     if (aux)
1356         return dupstr(aux);
1357
1358     soln = snewn(a, digit);
1359     memset(soln, 0, a);
1360
1361     ret = solver(w, state->clues->dsf, state->clues->clues,
1362                  soln, DIFFCOUNT-1);
1363
1364     if (ret == diff_impossible) {
1365         *error = "No solution exists for this puzzle";
1366         out = NULL;
1367     } else if (ret == diff_ambiguous) {
1368         *error = "Multiple solutions exist for this puzzle";
1369         out = NULL;
1370     } else {
1371         out = snewn(a+2, char);
1372         out[0] = 'S';
1373         for (i = 0; i < a; i++)
1374             out[i+1] = '0' + soln[i];
1375         out[a+1] = '\0';
1376     }
1377
1378     sfree(soln);
1379     return out;
1380 }
1381
1382 static int game_can_format_as_text_now(const game_params *params)
1383 {
1384     return TRUE;
1385 }
1386
1387 static char *game_text_format(const game_state *state)
1388 {
1389     return NULL;
1390 }
1391
1392 struct game_ui {
1393     /*
1394      * These are the coordinates of the currently highlighted
1395      * square on the grid, if hshow = 1.
1396      */
1397     int hx, hy;
1398     /*
1399      * This indicates whether the current highlight is a
1400      * pencil-mark one or a real one.
1401      */
1402     int hpencil;
1403     /*
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.
1409      */
1410     int hshow;
1411     /*
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.
1415      */
1416     int hcursor;
1417 };
1418
1419 static game_ui *new_ui(const game_state *state)
1420 {
1421     game_ui *ui = snew(game_ui);
1422
1423     ui->hx = ui->hy = 0;
1424     ui->hpencil = ui->hshow = ui->hcursor = 0;
1425
1426     return ui;
1427 }
1428
1429 static void free_ui(game_ui *ui)
1430 {
1431     sfree(ui);
1432 }
1433
1434 static char *encode_ui(const game_ui *ui)
1435 {
1436     return NULL;
1437 }
1438
1439 static void decode_ui(game_ui *ui, const char *encoding)
1440 {
1441 }
1442
1443 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1444                                const game_state *newstate)
1445 {
1446     int w = newstate->par.w;
1447     /*
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.
1452      */
1453     if (ui->hshow && ui->hpencil && !ui->hcursor &&
1454         newstate->grid[ui->hy * w + ui->hx] != 0) {
1455         ui->hshow = 0;
1456     }
1457 }
1458
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)
1465
1466 #define FLASH_TIME 0.4F
1467
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
1474
1475 struct game_drawstate {
1476     int tilesize;
1477     int started;
1478     long *tiles;
1479     long *errors;
1480     char *minus_sign, *times_sign, *divide_sign;
1481 };
1482
1483 static int check_errors(const game_state *state, long *errors)
1484 {
1485     int w = state->par.w, a = w*w;
1486     int i, j, x, y, errs = FALSE;
1487     long *cluevals;
1488     int *full;
1489
1490     cluevals = snewn(a, long);
1491     full = snewn(a, int);
1492
1493     if (errors)
1494         for (i = 0; i < a; i++) {
1495             errors[i] = 0;
1496             full[i] = TRUE;
1497         }
1498
1499     for (i = 0; i < a; i++) {
1500         long clue;
1501
1502         j = dsf_canonify(state->clues->dsf, i);
1503         if (j == i) {
1504             cluevals[i] = state->grid[i];
1505         } else {
1506             clue = state->clues->clues[j] & CMASK;
1507
1508             switch (clue) {
1509               case C_ADD:
1510                 cluevals[j] += state->grid[i];
1511                 break;
1512               case C_MUL:
1513                 cluevals[j] *= state->grid[i];
1514                 break;
1515               case C_SUB:
1516                 cluevals[j] = abs(cluevals[j] - state->grid[i]);
1517                 break;
1518               case C_DIV:
1519                 {
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)
1523                         cluevals[j] = 0;
1524                     else
1525                         cluevals[j] = d2 / d1;
1526                 }
1527                 break;
1528             }
1529         }
1530
1531         if (!state->grid[i])
1532             full[j] = FALSE;
1533     }
1534
1535     for (i = 0; i < a; i++) {
1536         j = dsf_canonify(state->clues->dsf, i);
1537         if (j == i) {
1538             if ((state->clues->clues[j] & ~CMASK) != cluevals[i]) {
1539                 errs = TRUE;
1540                 if (errors && full[j])
1541                     errors[j] |= DF_ERR_CLUE;
1542             }
1543         }
1544     }
1545
1546     sfree(cluevals);
1547     sfree(full);
1548
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);
1554             mask |= bit;
1555         }
1556
1557         if (mask != (1 << (w+1)) - (1 << 1)) {
1558             errs = TRUE;
1559             errmask &= ~1;
1560             if (errors) {
1561                 for (x = 0; x < w; x++)
1562                     if (errmask & (1 << state->grid[y*w+x]))
1563                         errors[y*w+x] |= DF_ERR_LATIN;
1564             }
1565         }
1566     }
1567
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);
1573             mask |= bit;
1574         }
1575
1576         if (mask != (1 << (w+1)) - (1 << 1)) {
1577             errs = TRUE;
1578             errmask &= ~1;
1579             if (errors) {
1580                 for (y = 0; y < w; y++)
1581                     if (errmask & (1 << state->grid[y*w+x]))
1582                         errors[y*w+x] |= DF_ERR_LATIN;
1583             }
1584         }
1585     }
1586
1587     return errs;
1588 }
1589
1590 static char *interpret_move(const game_state *state, game_ui *ui,
1591                             const game_drawstate *ds,
1592                             int x, int y, int button)
1593 {
1594     int w = state->par.w;
1595     int tx, ty;
1596     char buf[80];
1597
1598     button &= ~MOD_MASK;
1599
1600     tx = FROMCOORD(x);
1601     ty = FROMCOORD(y);
1602
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) {
1607                 ui->hshow = 0;
1608             } else {
1609                 ui->hx = tx;
1610                 ui->hy = ty;
1611                 ui->hshow = 1;
1612                 ui->hpencil = 0;
1613             }
1614             ui->hcursor = 0;
1615             return UI_UPDATE;
1616         }
1617         if (button == RIGHT_BUTTON) {
1618             /*
1619              * Pencil-mode highlighting for non filled squares.
1620              */
1621             if (state->grid[ty*w+tx] == 0) {
1622                 if (tx == ui->hx && ty == ui->hy &&
1623                     ui->hshow && ui->hpencil) {
1624                     ui->hshow = 0;
1625                 } else {
1626                     ui->hpencil = 1;
1627                     ui->hx = tx;
1628                     ui->hy = ty;
1629                     ui->hshow = 1;
1630                 }
1631             } else {
1632                 ui->hshow = 0;
1633             }
1634             ui->hcursor = 0;
1635             return UI_UPDATE;
1636         }
1637     }
1638     if (IS_CURSOR_MOVE(button)) {
1639         move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
1640         ui->hshow = ui->hcursor = 1;
1641         return UI_UPDATE;
1642     }
1643     if (ui->hshow &&
1644         (button == CURSOR_SELECT)) {
1645         ui->hpencil = 1 - ui->hpencil;
1646         ui->hcursor = 1;
1647         return UI_UPDATE;
1648     }
1649
1650     if (ui->hshow &&
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')
1655             n = 0;
1656
1657         /*
1658          * Can't make pencil marks in a filled square. This can only
1659          * become highlighted if we're using cursor keys.
1660          */
1661         if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1662             return NULL;
1663
1664         sprintf(buf, "%c%d,%d,%d",
1665                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1666
1667         if (!ui->hcursor) ui->hshow = 0;
1668
1669         return dupstr(buf);
1670     }
1671
1672     if (button == 'M' || button == 'm')
1673         return dupstr("M");
1674
1675     return NULL;
1676 }
1677
1678 static game_state *execute_move(const game_state *from, const char *move)
1679 {
1680     int w = from->par.w, a = w*w;
1681     game_state *ret;
1682     int x, y, i, n;
1683
1684     if (move[0] == 'S') {
1685         ret = dup_game(from);
1686         ret->completed = ret->cheated = TRUE;
1687
1688         for (i = 0; i < a; i++) {
1689             if (move[i+1] < '1' || move[i+1] > '0'+w) {
1690                 free_game(ret);
1691                 return NULL;
1692             }
1693             ret->grid[i] = move[i+1] - '0';
1694             ret->pencil[i] = 0;
1695         }
1696
1697         if (move[a+1] != '\0') {
1698             free_game(ret);
1699             return NULL;
1700         }
1701
1702         return ret;
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) {
1706
1707         ret = dup_game(from);
1708         if (move[0] == 'P' && n > 0) {
1709             ret->pencil[y*w+x] ^= 1 << n;
1710         } else {
1711             ret->grid[y*w+x] = n;
1712             ret->pencil[y*w+x] = 0;
1713
1714             if (!ret->completed && !check_errors(ret, NULL))
1715                 ret->completed = TRUE;
1716         }
1717         return ret;
1718     } else if (move[0] == 'M') {
1719         /*
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.)
1724          */
1725         ret = dup_game(from);
1726         for (i = 0; i < a; i++) {
1727             if (!ret->grid[i])
1728                 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1729         }
1730         return ret;
1731     } else
1732         return NULL;                   /* couldn't parse move string */
1733 }
1734
1735 /* ----------------------------------------------------------------------
1736  * Drawing routines.
1737  */
1738
1739 #define SIZE(w) ((w) * TILESIZE + 2*BORDER)
1740
1741 static void game_compute_size(const game_params *params, int tilesize,
1742                               int *x, int *y)
1743 {
1744     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1745     struct { int tilesize; } ads, *ds = &ads;
1746     ads.tilesize = tilesize;
1747
1748     *x = *y = SIZE(params->w);
1749 }
1750
1751 static void game_set_size(drawing *dr, game_drawstate *ds,
1752                           const game_params *params, int tilesize)
1753 {
1754     ds->tilesize = tilesize;
1755 }
1756
1757 static float *game_colours(frontend *fe, int *ncolours)
1758 {
1759     float *ret = snewn(3 * NCOLOURS, float);
1760
1761     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1762
1763     ret[COL_GRID * 3 + 0] = 0.0F;
1764     ret[COL_GRID * 3 + 1] = 0.0F;
1765     ret[COL_GRID * 3 + 2] = 0.0F;
1766
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;
1770
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];
1774
1775     ret[COL_ERROR * 3 + 0] = 1.0F;
1776     ret[COL_ERROR * 3 + 1] = 0.0F;
1777     ret[COL_ERROR * 3 + 2] = 0.0F;
1778
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];
1782
1783     *ncolours = NCOLOURS;
1784     return ret;
1785 }
1786
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", "/" };
1790
1791 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1792 {
1793     int w = state->par.w, a = w*w;
1794     struct game_drawstate *ds = snew(struct game_drawstate);
1795     int i;
1796
1797     ds->tilesize = 0;
1798     ds->started = FALSE;
1799     ds->tiles = snewn(a, long);
1800     for (i = 0; i < a; i++)
1801         ds->tiles[i] = -1;
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));
1806
1807     return ds;
1808 }
1809
1810 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1811 {
1812     sfree(ds->tiles);
1813     sfree(ds->errors);
1814     sfree(ds->minus_sign);
1815     sfree(ds->times_sign);
1816     sfree(ds->divide_sign);
1817     sfree(ds);
1818 }
1819
1820 static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
1821                       int x, int y, long tile, int only_one_op)
1822 {
1823     int w = clues->w /* , a = w*w */;
1824     int tx, ty, tw, th;
1825     int cx, cy, cw, ch;
1826     char str[64];
1827
1828     tx = BORDER + x * TILESIZE + 1 + GRIDEXTRA;
1829     ty = BORDER + y * TILESIZE + 1 + GRIDEXTRA;
1830
1831     cx = tx;
1832     cy = ty;
1833     cw = tw = TILESIZE-1-2*GRIDEXTRA;
1834     ch = th = TILESIZE-1-2*GRIDEXTRA;
1835
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))
1839         cw += GRIDEXTRA;
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))
1843         ch += GRIDEXTRA;
1844
1845     clip(dr, cx, cy, cw, ch);
1846
1847     /* background needs erasing */
1848     draw_rect(dr, cx, cy, cw, ch,
1849               (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
1850
1851     /* pencil-mode highlight */
1852     if (tile & DF_HIGHLIGHT_PENCIL) {
1853         int coords[6];
1854         coords[0] = cx;
1855         coords[1] = cy;
1856         coords[2] = cx+cw/2;
1857         coords[3] = cy;
1858         coords[4] = cx;
1859         coords[5] = cy+ch/2;
1860         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1861     }
1862
1863     /*
1864      * Draw the corners of thick lines in corner-adjacent squares,
1865      * which jut into this square by one pixel.
1866      */
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);
1875
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);
1881         /*
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.
1889          */
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);
1899     }
1900
1901     /* new number needs drawing? */
1902     if (tile & DF_DIGIT_MASK) {
1903         str[1] = '\0';
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);
1908     } else {
1909         int i, j, npencil;
1910         int pl, pr, pt, pb;
1911         float bestsize;
1912         int pw, ph, minph, pbest, fontsize;
1913
1914         /* Count the pencil marks required. */
1915         for (i = 1, npencil = 0; i <= w; i++)
1916             if (tile & (1L << (i + DF_PENCIL_SHIFT)))
1917                 npencil++;
1918         if (npencil) {
1919
1920             minph = 2;
1921
1922             /*
1923              * Determine the bounding rectangle within which we're going
1924              * to put the pencil marks.
1925              */
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) {
1932                 /*
1933                  * Make space for the clue text.
1934                  */
1935                 pt += TILESIZE/4;
1936                 /* minph--; */
1937             }
1938
1939             /*
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.
1943              *
1944              * So now we work out what the grid size ought to be.
1945              */
1946             bestsize = 0.0;
1947             pbest = 0;
1948             /* Minimum */
1949             for (pw = 3; pw < max(npencil,4); pw++) {
1950                 float fw, fh, fs;
1951
1952                 ph = (npencil + pw - 1) / pw;
1953                 ph = max(ph, minph);
1954                 fw = (pr - pl) / (float)pw;
1955                 fh = (pb - pt) / (float)ph;
1956                 fs = min(fw, fh);
1957                 if (fs > bestsize) {
1958                     bestsize = fs;
1959                     pbest = pw;
1960                 }
1961             }
1962             assert(pbest > 0);
1963             pw = pbest;
1964             ph = (npencil + pw - 1) / pw;
1965             ph = max(ph, minph);
1966
1967             /*
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.)
1972              */
1973             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1974
1975             /*
1976              * Centre the resulting figure in the square.
1977              */
1978             pl = tx + (TILESIZE - fontsize * pw) / 2;
1979             pt = ty + (TILESIZE - fontsize * ph) / 2;
1980
1981             /*
1982              * And move it down a bit if it's collided with some
1983              * clue text.
1984              */
1985             if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1986                 pt = max(pt, ty + GRIDEXTRA * 3 + TILESIZE/4);
1987             }
1988
1989             /*
1990              * Now actually draw the pencil marks.
1991              */
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;
1995
1996                     str[1] = '\0';
1997                     str[0] = i + '0';
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);
2002                     j++;
2003                 }
2004         }
2005     }
2006
2007     unclip(dr);
2008
2009     draw_update(dr, cx, cy, cw, ch);
2010 }
2011
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)
2016 {
2017     int w = state->par.w /*, a = w*w */;
2018     int x, y;
2019
2020     if (!ds->started) {
2021         /*
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.
2026          */
2027         draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
2028
2029         /*
2030          * Big containing rectangle.
2031          */
2032         draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
2033                   w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
2034                   COL_GRID);
2035
2036         draw_update(dr, 0, 0, SIZE(w), SIZE(w));
2037
2038         ds->started = TRUE;
2039     }
2040
2041     check_errors(state, ds->errors);
2042
2043     for (y = 0; y < w; y++) {
2044         for (x = 0; x < w; x++) {
2045             long tile = 0L;
2046
2047             if (state->grid[y*w+x])
2048                 tile = state->grid[y*w+x];
2049             else
2050                 tile = (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;
2051
2052             if (ui->hshow && ui->hx == x && ui->hy == y)
2053                 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
2054
2055             if (flashtime > 0 &&
2056                 (flashtime <= FLASH_TIME/3 ||
2057                  flashtime >= FLASH_TIME*2/3))
2058                 tile |= DF_HIGHLIGHT;  /* completion flash */
2059
2060             tile |= ds->errors[y*w+x];
2061
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);
2066             }
2067         }
2068     }
2069 }
2070
2071 static float game_anim_length(const game_state *oldstate,
2072                               const game_state *newstate, int dir, game_ui *ui)
2073 {
2074     return 0.0F;
2075 }
2076
2077 static float game_flash_length(const game_state *oldstate,
2078                                const game_state *newstate, int dir, game_ui *ui)
2079 {
2080     if (!oldstate->completed && newstate->completed &&
2081         !oldstate->cheated && !newstate->cheated)
2082         return FLASH_TIME;
2083     return 0.0F;
2084 }
2085
2086 static int game_status(const game_state *state)
2087 {
2088     return state->completed ? +1 : 0;
2089 }
2090
2091 static int game_timing_state(const game_state *state, game_ui *ui)
2092 {
2093     if (state->completed)
2094         return FALSE;
2095     return TRUE;
2096 }
2097
2098 static void game_print_size(const game_params *params, float *x, float *y)
2099 {
2100     int pw, ph;
2101
2102     /*
2103      * We use 9mm squares by default, like Solo.
2104      */
2105     game_compute_size(params, 900, &pw, &ph);
2106     *x = pw / 100.0F;
2107     *y = ph / 100.0F;
2108 }
2109
2110 /*
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
2116  * single polygon.
2117  */
2118 static void outline_block_structure(drawing *dr, game_drawstate *ds,
2119                                     int w, int *dsf, int ink)
2120 {
2121     int a = w*w;
2122     int *coords;
2123     int i, n;
2124     int x, y, dx, dy, sx, sy, sdx, sdy;
2125
2126     coords = snewn(4*a, int);
2127
2128     /*
2129      * Iterate over all the blocks.
2130      */
2131     for (i = 0; i < a; i++) {
2132         if (dsf_canonify(dsf, i) != i)
2133             continue;
2134
2135         /*
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.
2139          */
2140         x = i % w;
2141         y = i / w;
2142         dx = -1;
2143         dy = 0;
2144
2145         /*
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.
2151          */
2152         sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
2153         n = 0;
2154         do {
2155             int cx, cy, tx, ty, nin;
2156
2157             /*
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).
2166              */
2167             nin = 0;
2168             tx = x - dy + dx;
2169             ty = y + dx + dy;
2170             nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2171                     dsf_canonify(dsf, ty*w+tx) == i);
2172             tx = x - dy;
2173             ty = y + dx;
2174             nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2175                     dsf_canonify(dsf, ty*w+tx) == i);
2176             if (nin == 0) {
2177                 /*
2178                  * Turn right.
2179                  */
2180                 int tmp;
2181                 tmp = dx;
2182                 dx = -dy;
2183                 dy = tmp;
2184             } else if (nin == 2) {
2185                 /*
2186                  * Turn left.
2187                  */
2188                 int tmp;
2189
2190                 x += dx;
2191                 y += dy;
2192
2193                 tmp = dx;
2194                 dx = dy;
2195                 dy = -tmp;
2196
2197                 x -= dx;
2198                 y -= dy;
2199             } else {
2200                 /*
2201                  * Go straight on.
2202                  */
2203                 x -= dy;
2204                 y += dx;
2205             }
2206
2207             /*
2208              * Now enforce by assertion that we ended up
2209              * somewhere sensible.
2210              */
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);
2215
2216             /*
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.
2222              */
2223             assert(n < 2*w+2);
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;
2228             n++;
2229
2230         } while (x != sx || y != sy || dx != sdx || dy != sdy);
2231
2232         /*
2233          * That's our polygon; now draw it.
2234          */
2235         draw_polygon(dr, coords, n, -1, ink);
2236     }
2237
2238     sfree(coords);
2239 }
2240
2241 static void game_print(drawing *dr, const game_state *state, int tilesize)
2242 {
2243     int w = state->par.w;
2244     int ink = print_mono_colour(dr, 0);
2245     int x, y;
2246     char *minus_sign, *times_sign, *divide_sign;
2247
2248     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2249     game_drawstate ads, *ds = &ads;
2250     game_set_size(dr, ds, NULL, tilesize);
2251
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));
2255
2256     /*
2257      * Border.
2258      */
2259     print_line_width(dr, 3 * TILESIZE / 40);
2260     draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);
2261
2262     /*
2263      * Main grid.
2264      */
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);
2269     }
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);
2274     }
2275
2276     /*
2277      * Thick lines between cells.
2278      */
2279     print_line_width(dr, 3 * TILESIZE / 40);
2280     outline_block_structure(dr, ds, w, state->clues->dsf, ink);
2281
2282     /*
2283      * Clues.
2284      */
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);
2291                 char str[64];
2292
2293                 /*
2294                  * As in the drawing code, we omit the operator for
2295                  * blocks of area 1.
2296                  */
2297                 sprintf (str, "%ld%s", clueval,
2298                          (size == 1 ? "" :
2299                           cluetype == C_ADD ? "+" :
2300                           cluetype == C_SUB ? minus_sign :
2301                           cluetype == C_MUL ? times_sign :
2302                           /* cluetype == C_DIV ? */ divide_sign));
2303
2304                 draw_text(dr,
2305                           BORDER+x*TILESIZE + 5*TILESIZE/80,
2306                           BORDER+y*TILESIZE + 20*TILESIZE/80,
2307                           FONT_VARIABLE, TILESIZE/4,
2308                           ALIGN_VNORMAL | ALIGN_HLEFT,
2309                           ink, str);
2310             }
2311
2312     /*
2313      * Numbers for the solution, if any.
2314      */
2315     for (y = 0; y < w; y++)
2316         for (x = 0; x < w; x++)
2317             if (state->grid[y*w+x]) {
2318                 char str[2];
2319                 str[1] = '\0';
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);
2325             }
2326
2327     sfree(minus_sign);
2328     sfree(times_sign);
2329     sfree(divide_sign);
2330 }
2331
2332 #ifdef COMBINED
2333 #define thegame keen
2334 #endif
2335
2336 const struct game thegame = {
2337     "Keen", "games.keen", "keen",
2338     default_params,
2339     game_fetch_preset, NULL,
2340     decode_params,
2341     encode_params,
2342     free_params,
2343     dup_params,
2344     TRUE, game_configure, custom_params,
2345     validate_params,
2346     new_game_desc,
2347     validate_desc,
2348     new_game,
2349     dup_game,
2350     free_game,
2351     TRUE, solve_game,
2352     FALSE, game_can_format_as_text_now, game_text_format,
2353     new_ui,
2354     free_ui,
2355     encode_ui,
2356     decode_ui,
2357     game_changed_state,
2358     interpret_move,
2359     execute_move,
2360     PREFERRED_TILESIZE, game_compute_size, game_set_size,
2361     game_colours,
2362     game_new_drawstate,
2363     game_free_drawstate,
2364     game_redraw,
2365     game_anim_length,
2366     game_flash_length,
2367     game_status,
2368     TRUE, FALSE, game_print_size, game_print,
2369     FALSE,                             /* wants_statusbar */
2370     FALSE, game_timing_state,
2371     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
2372 };
2373
2374 #ifdef STANDALONE_SOLVER
2375
2376 #include <stdarg.h>
2377
2378 int main(int argc, char **argv)
2379 {
2380     game_params *p;
2381     game_state *s;
2382     char *id = NULL, *desc;
2383     const char *err;
2384     int grade = FALSE;
2385     int ret, diff, really_show_working = FALSE;
2386
2387     while (--argc > 0) {
2388         char *p = *++argv;
2389         if (!strcmp(p, "-v")) {
2390             really_show_working = TRUE;
2391         } else if (!strcmp(p, "-g")) {
2392             grade = TRUE;
2393         } else if (*p == '-') {
2394             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2395             return 1;
2396         } else {
2397             id = p;
2398         }
2399     }
2400
2401     if (!id) {
2402         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2403         return 1;
2404     }
2405
2406     desc = strchr(id, ':');
2407     if (!desc) {
2408         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2409         return 1;
2410     }
2411     *desc++ = '\0';
2412
2413     p = default_params();
2414     decode_params(p, id);
2415     err = validate_desc(p, desc);
2416     if (err) {
2417         fprintf(stderr, "%s: %s\n", argv[0], err);
2418         return 1;
2419     }
2420     s = new_game(NULL, p, desc);
2421
2422     /*
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.
2426      */
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,
2432                      s->grid, diff);
2433         if (ret <= diff)
2434             break;
2435     }
2436
2437     if (diff == DIFFCOUNT) {
2438         if (grade)
2439             printf("Difficulty rating: ambiguous\n");
2440         else
2441             printf("Unable to find a unique solution\n");
2442     } else {
2443         if (grade) {
2444             if (ret == diff_impossible)
2445                 printf("Difficulty rating: impossible (no solution exists)\n");
2446             else
2447                 printf("Difficulty rating: %s\n", keen_diffnames[ret]);
2448         } else {
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,
2452                          s->grid, diff);
2453             if (ret != diff)
2454                 printf("Puzzle is inconsistent\n");
2455             else {
2456                 /*
2457                  * We don't have a game_text_format for this game,
2458                  * so we have to output the solution manually.
2459                  */
2460                 int x, y;
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]);
2464                     }
2465                     putchar('\n');
2466                 }
2467             }
2468         }
2469     }
2470
2471     return 0;
2472 }
2473
2474 #endif
2475
2476 /* vim: set shiftwidth=4 tabstop=8: */