chiark / gitweb /
Tents: mark squares as non-tents with {Shift,Control}-cursor keys.
[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].sval = dupstr(buf);
187     ret[0].ival = 0;
188
189     ret[1].name = "Difficulty";
190     ret[1].type = C_CHOICES;
191     ret[1].sval = DIFFCONFIG;
192     ret[1].ival = params->diff;
193
194     ret[2].name = "Multiplication only";
195     ret[2].type = C_BOOLEAN;
196     ret[2].sval = NULL;
197     ret[2].ival = params->multiplication_only;
198
199     ret[3].name = NULL;
200     ret[3].type = C_END;
201     ret[3].sval = NULL;
202     ret[3].ival = 0;
203
204     return ret;
205 }
206
207 static game_params *custom_params(const config_item *cfg)
208 {
209     game_params *ret = snew(game_params);
210
211     ret->w = atoi(cfg[0].sval);
212     ret->diff = cfg[1].ival;
213     ret->multiplication_only = cfg[2].ival;
214
215     return ret;
216 }
217
218 static char *validate_params(const game_params *params, int full)
219 {
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";
224     return NULL;
225 }
226
227 /* ----------------------------------------------------------------------
228  * Solver.
229  */
230
231 struct solver_ctx {
232     int w, diff;
233     int nboxes;
234     int *boxes, *boxlist, *whichbox;
235     long *clues;
236     digit *soln;
237     digit *dscratch;
238     int *iscratch;
239 };
240
241 static void solver_clue_candidate(struct solver_ctx *ctx, int diff, int box)
242 {
243     int w = ctx->w;
244     int n = ctx->boxes[box+1] - ctx->boxes[box];
245     int j;
246
247     /*
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.
254      */
255     if (diff == DIFF_EASY) {
256         unsigned mask = 0;
257         /*
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
261          * everywhere.
262          */
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) {
268         /*
269          * Normal-mode deductions: we process the information in
270          * dscratch in the obvious way.
271          */
272         for (j = 0; j < n; j++)
273             ctx->iscratch[j] |= 1 << ctx->dscratch[j];
274     } else if (diff == DIFF_HARD) {
275         /*
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.
281          */
282         int *sq = ctx->boxlist + ctx->boxes[box];
283
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];
290         }
291         for (j = 0; j < 2*w; j++)
292             ctx->iscratch[j] &= ctx->iscratch[2*w+j];
293     }
294 }
295
296 static int solver_common(struct latin_solver *solver, void *vctx, int diff)
297 {
298     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
299     int w = ctx->w;
300     int box, i, j, k;
301     int ret = 0, total;
302
303     /*
304      * Iterate over each clue box and deduce what we can.
305      */
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;
311
312         if (diff == DIFF_HARD) {
313             for (i = 0; i < n; i++)
314                 ctx->iscratch[i] = (1 << (w+1)) - (1 << 1);
315         } else {
316             for (i = 0; i < n; i++)
317                 ctx->iscratch[i] = 0;
318         }
319
320         switch (op) {
321           case C_SUB:
322           case C_DIV:
323             /*
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.
333              */
334             assert(n == 2);
335
336             for (i = 1; i <= w; i++) {
337                 j = (op == C_SUB ? i + value : i * value);
338                 if (j > w) break;
339
340                 /* (i,j) is a valid digit pair. Try it both ways round. */
341
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);
347                 }
348
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);
354                 }
355             }
356
357             break;
358
359           case C_ADD:
360           case C_MUL:
361             /*
362              * For these clue types, I have no alternative but to go
363              * through all possible number combinations.
364              *
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.
369              */
370             i = 0;
371             ctx->dscratch[i] = 0;
372             total = value;             /* start with the identity */
373             while (1) {
374                 if (i < n) {
375                     /*
376                      * Find the next valid value for cell i.
377                      */
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 */
388                         if (k < i)
389                             continue;
390
391                         /* Found one. */
392                         break;
393                     }
394
395                     if (j > w) {
396                         /* No valid values left; drop back. */
397                         i--;
398                         if (i < 0)
399                             break;     /* overall iteration is finished */
400                         if (op == C_ADD)
401                             total += ctx->dscratch[i];
402                         else
403                             total *= ctx->dscratch[i];
404                     } else {
405                         /* Got a valid value; store it and move on. */
406                         ctx->dscratch[i++] = j;
407                         if (op == C_ADD)
408                             total -= j;
409                         else
410                             total /= j;
411                         ctx->dscratch[i] = 0;
412                     }
413                 } else {
414                     if (total == (op == C_ADD ? 0 : 1))
415                         solver_clue_candidate(ctx, diff, box);
416                     i--;
417                     if (op == C_ADD)
418                         total += ctx->dscratch[i];
419                     else
420                         total *= ctx->dscratch[i];
421                 }
422             }
423
424             break;
425         }
426
427         if (diff < DIFF_HARD) {
428 #ifdef STANDALONE_SOLVER
429             char prefix[256];
430
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);
435             else
436                 prefix[0] = '\0';              /* placate optimiser */
437 #endif
438
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);
448                             prefix[0] = '\0';
449                         }
450 #endif
451                         solver->cube[sq[i]*w+j-1] = 0;
452                         ret = 1;
453                     }
454                 }
455         } else {
456 #ifdef STANDALONE_SOLVER
457             char prefix[256];
458
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);
463             else
464                 prefix[0] = '\0';              /* placate optimiser */
465 #endif
466
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
472                     char prefix2[256];
473
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);
478                     else
479                         prefix2[0] = '\0';   /* placate optimiser */
480 #endif
481
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",
489                                        prefix, prefix2,
490                                        solver_recurse_depth*4, "",
491                                        j, pos/w+1, pos%w+1);
492                                 prefix[0] = prefix2[0] = '\0';
493                             }
494 #endif
495                             solver->cube[pos*w+j-1] = 0;
496                             ret = 1;
497                         }
498                     }
499                 }
500             }
501
502             /*
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.)
509              */
510             if (ret)
511                 return ret;
512         }
513     }
514
515     return ret;
516 }
517
518 static int solver_easy(struct latin_solver *solver, void *vctx)
519 {
520     /*
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.
524      *
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.
534      */
535     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
536     if (ctx->diff > DIFF_EASY)
537         return 0;
538     return solver_common(solver, vctx, DIFF_EASY);
539 }
540
541 static int solver_normal(struct latin_solver *solver, void *vctx)
542 {
543     return solver_common(solver, vctx, DIFF_NORMAL);
544 }
545
546 static int solver_hard(struct latin_solver *solver, void *vctx)
547 {
548     return solver_common(solver, vctx, DIFF_HARD);
549 }
550
551 #define SOLVER(upper,title,func,lower) func,
552 static usersolver_t const keen_solvers[] = { DIFFLIST(SOLVER) };
553
554 static int solver(int w, int *dsf, long *clues, digit *soln, int maxdiff)
555 {
556     int a = w*w;
557     struct solver_ctx ctx;
558     int ret;
559     int i, j, n, m;
560     
561     ctx.w = w;
562     ctx.soln = soln;
563     ctx.diff = maxdiff;
564
565     /*
566      * Transform the dsf-formatted clue list into one over which we
567      * can iterate more easily.
568      *
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).
572      */
573     for (ctx.nboxes = i = 0; i < a; i++)
574         if (dsf_canonify(dsf, i) == i)
575             ctx.nboxes++;
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];
583             ctx.boxes[n] = m;
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;
588                 }
589             n++;
590         }
591     assert(n == ctx.nboxes);
592     assert(m == a);
593     ctx.boxes[n] = m;
594
595     ctx.dscratch = snewn(a+1, digit);
596     ctx.iscratch = snewn(max(a+1, 4*w), int);
597
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);
602
603     sfree(ctx.dscratch);
604     sfree(ctx.iscratch);
605     sfree(ctx.whichbox);
606     sfree(ctx.boxlist);
607     sfree(ctx.boxes);
608     sfree(ctx.clues);
609
610     return ret;
611 }
612
613 /* ----------------------------------------------------------------------
614  * Grid generation.
615  */
616
617 static char *encode_block_structure(char *p, int w, int *dsf)
618 {
619     int i, currrun = 0;
620     char *orig, *q, *r, c;
621
622     orig = p;
623
624     /*
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
629      * reading order.
630      *
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).
635      */
636     for (i = 0; i <= 2*w*(w-1); i++) {
637         int x, y, p0, p1, edge;
638
639         if (i == 2*w*(w-1)) {
640             edge = TRUE;       /* terminating virtual edge */
641         } else {
642             if (i < w*(w-1)) {
643                 y = i/(w-1);
644                 x = i%(w-1);
645                 p0 = y*w+x;
646                 p1 = y*w+x+1;
647             } else {
648                 x = i/(w-1) - w;
649                 y = i%(w-1);
650                 p0 = y*w+x;
651                 p1 = (y+1)*w+x;
652             }
653             edge = (dsf_canonify(dsf, p0) != dsf_canonify(dsf, p1));
654         }
655
656         if (edge) {
657             while (currrun > 25)
658                 *p++ = 'z', currrun -= 25;
659             if (currrun)
660                 *p++ = 'a'-1 + currrun;
661             else
662                 *p++ = '_';
663             currrun = 0;
664         } else
665             currrun++;
666     }
667
668     /*
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
673      * worthwhile step.)
674      */
675     for (q = r = orig; r < p ;) {
676         *q++ = c = *r;
677
678         for (i = 0; r+i < p && r[i] == c; i++);
679         r += i;
680
681         if (i == 2) {
682             *q++ = c;
683         } else if (i > 2) {
684             q += sprintf(q, "%d", i);
685         }
686     }
687     
688     return q;
689 }
690
691 static char *parse_block_structure(const char **p, int w, int *dsf)
692 {
693     int a = w*w;
694     int pos = 0;
695     int repc = 0, repn = 0;
696
697     dsf_init(dsf, a);
698
699     while (**p && (repn > 0 || **p != ',')) {
700         int c, adv;
701
702         if (repn > 0) {
703             repn--;
704             c = repc;
705         } else if (**p == '_' || (**p >= 'a' && **p <= 'z')) {
706             c = (**p == '_' ? 0 : **p - 'a' + 1);
707             (*p)++;
708             if (**p && isdigit((unsigned char)**p)) {
709                 repc = c;
710                 repn = atoi(*p)-1;
711                 while (**p && isdigit((unsigned char)**p)) (*p)++;
712             }
713         } else
714             return "Invalid character in game description";
715
716         adv = (c != 25);               /* 'z' is a special case */
717
718         while (c-- > 0) {
719             int p0, p1;
720
721             /*
722              * Non-edge; merge the two dsf classes on either
723              * side of it.
724              */
725             if (pos >= 2*w*(w-1))
726                 return "Too much data in block structure specification";
727             if (pos < w*(w-1)) {
728                 int y = pos/(w-1);
729                 int x = pos%(w-1);
730                 p0 = y*w+x;
731                 p1 = y*w+x+1;
732             } else {
733                 int x = pos/(w-1) - w;
734                 int y = pos%(w-1);
735                 p0 = y*w+x;
736                 p1 = (y+1)*w+x;
737             }
738             dsf_merge(dsf, p0, p1);
739
740             pos++;
741         }
742         if (adv) {
743             pos++;
744             if (pos > 2*w*(w-1)+1)
745                 return "Too much data in block structure specification";
746         }
747     }
748
749     /*
750      * When desc is exhausted, we expect to have gone exactly
751      * one space _past_ the end of the grid, due to the dummy
752      * edge at the end.
753      */
754     if (pos != 2*w*(w-1)+1)
755         return "Not enough data in block structure specification";
756
757     return NULL;
758 }
759
760 static char *new_game_desc(const game_params *params, random_state *rs,
761                            char **aux, int interactive)
762 {
763     int w = params->w, a = w*w;
764     digit *grid, *soln;
765     int *order, *revorder, *singletons, *dsf;
766     long *clues, *cluevals;
767     int i, j, k, n, x, y, ret;
768     int diff = params->diff;
769     char *desc, *p;
770
771     /*
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.
776      *
777      * Remember to re-test this whenever a change is made to the
778      * solver logic!
779      *
780      * I tested it using the following shell command:
781
782 for d in e n h x u; do
783   for i in {3..9}; do
784     echo ./keen --generate 1 ${i}d${d}
785     perl -e 'alarm 30; exec @ARGV' ./keen --generate 5 ${i}d${d} >/dev/null \
786       || echo broken
787   done
788 done
789
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.
793      */
794     if (w == 3 && diff > DIFF_NORMAL)
795         diff = DIFF_NORMAL;
796
797     grid = NULL;
798
799     order = snewn(a, int);
800     revorder = snewn(a, int);
801     singletons = snewn(a, int);
802     dsf = snew_dsf(a);
803     clues = snewn(a, long);
804     cluevals = snewn(a, long);
805     soln = snewn(a, digit);
806
807     while (1) {
808         /*
809          * First construct a latin square to be the solution.
810          */
811         sfree(grid);
812         grid = latin_generate(w, rs);
813
814         /*
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.
820          */
821         for (i = 0; i < a; i++)
822             order[i] = i;
823         shuffle(order, a, sizeof(*order), rs);
824         for (i = 0; i < a; i++)
825             revorder[order[i]] = i;
826
827         for (i = 0; i < a; i++)
828             singletons[i] = TRUE;
829
830         dsf_init(dsf, a);
831
832         /* Place dominoes. */
833         for (i = 0; i < a; i++) {
834             if (singletons[i]) {
835                 int best = -1;
836
837                 x = i % w;
838                 y = i / w;
839
840                 if (x > 0 && singletons[i-1] &&
841                     (best == -1 || revorder[i-1] < revorder[best]))
842                     best = i-1;
843                 if (x+1 < w && singletons[i+1] &&
844                     (best == -1 || revorder[i+1] < revorder[best]))
845                     best = i+1;
846                 if (y > 0 && singletons[i-w] &&
847                     (best == -1 || revorder[i-w] < revorder[best]))
848                     best = i-w;
849                 if (y+1 < w && singletons[i+w] &&
850                     (best == -1 || revorder[i+w] < revorder[best]))
851                     best = i+w;
852
853                 /*
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
858                  * shapes.
859                  */
860                 if (best >= 0 && random_upto(rs, 4)) {
861                     singletons[i] = singletons[best] = FALSE;
862                     dsf_merge(dsf, i, best);
863                 }
864             }
865         }
866
867         /* Fold in singletons. */
868         for (i = 0; i < a; i++) {
869             if (singletons[i]) {
870                 int best = -1;
871
872                 x = i % w;
873                 y = i / w;
874
875                 if (x > 0 && dsf_size(dsf, i-1) < MAXBLK &&
876                     (best == -1 || revorder[i-1] < revorder[best]))
877                     best = i-1;
878                 if (x+1 < w && dsf_size(dsf, i+1) < MAXBLK &&
879                     (best == -1 || revorder[i+1] < revorder[best]))
880                     best = i+1;
881                 if (y > 0 && dsf_size(dsf, i-w) < MAXBLK &&
882                     (best == -1 || revorder[i-w] < revorder[best]))
883                     best = i-w;
884                 if (y+1 < w && dsf_size(dsf, i+w) < MAXBLK &&
885                     (best == -1 || revorder[i+w] < revorder[best]))
886                     best = i+w;
887
888                 if (best >= 0) {
889                     singletons[i] = singletons[best] = FALSE;
890                     dsf_merge(dsf, i, best);
891                 }
892             }
893         }
894
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++)
898             if (singletons[i])
899                 break;
900         if (i < a)
901             continue;
902
903         /*
904          * Decide what would be acceptable clues for each block.
905          *
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.
911          *
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.
917          *
918          * We reuse the 'singletons' array (finished with in the
919          * above loop) to hold information about which blocks are
920          * suitable for what.
921          */
922 #define F_ADD     0x01
923 #define F_SUB     0x02
924 #define F_MUL     0x04
925 #define F_DIV     0x08
926 #define BAD_SHIFT 4
927
928         for (i = 0; i < a; i++) {
929             singletons[i] = 0;
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;
939                 if (p < q) {
940                     int t = p; p = q; q = t;
941                 }
942
943                 /*
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.
948                  */
949                 v = p + q;
950                 if (v > 4 && v < 2*w-2)
951                     singletons[j] |= F_ADD;
952                 else
953                     singletons[j] |= F_ADD << BAD_SHIFT;
954
955                 /*
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.
959                  */
960                 v = p * q;
961                 n = 0;
962                 for (k = 1; k <= w; k++)
963                     if (v % k == 0 && v / k <= w && v / k != k)
964                         n++;
965                 if (n <= 2 && diff > DIFF_NORMAL)
966                     singletons[j] |= F_MUL << BAD_SHIFT;
967                 else
968                     singletons[j] |= F_MUL;
969
970                 /*
971                  * Subtraction: we completely avoid a difference of
972                  * w-1.
973                  */
974                 v = p - q;
975                 if (v < w-1)
976                     singletons[j] |= F_SUB;
977
978                 /*
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
983                  * inelegant.
984                  */
985                 if (p % q == 0 && 2 * (p / q) <= w)
986                     singletons[j] |= F_DIV;
987             }
988         }
989
990         /*
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.
994          *
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
998          * square.
999          */
1000         shuffle(order, a, sizeof(*order), rs);
1001         for (i = 0; i < a; i++)
1002             clues[i] = 0;
1003         while (1) {
1004             int done_something = FALSE;
1005
1006             for (k = 0; k < 4; k++) {
1007                 long clue;
1008                 int good, bad;
1009                 switch (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;
1014                 }
1015
1016                 for (i = 0; i < a; i++) {
1017                     j = order[i];
1018                     if (singletons[j] & good) {
1019                         clues[j] = clue;
1020                         singletons[j] = 0;
1021                         break;
1022                     }
1023                 }
1024                 if (i == a) {
1025                     /* didn't find a nice one, use a nasty one */
1026                     bad = good << BAD_SHIFT;
1027                     for (i = 0; i < a; i++) {
1028                         j = order[i];
1029                         if (singletons[j] & bad) {
1030                             clues[j] = clue;
1031                             singletons[j] = 0;
1032                             break;
1033                         }
1034                     }
1035                 }
1036                 if (i < a)
1037                     done_something = TRUE;
1038             }
1039
1040             if (!done_something)
1041                 break;
1042         }
1043 #undef F_ADD
1044 #undef F_SUB
1045 #undef F_MUL
1046 #undef F_DIV
1047 #undef BAD_SHIFT
1048
1049         /*
1050          * Having chosen the clue types, calculate the clue values.
1051          */
1052         for (i = 0; i < a; i++) {
1053             j = dsf_canonify(dsf, i);
1054             if (j == i) {
1055                 cluevals[j] = grid[i];
1056             } else {
1057                 switch (clues[j]) {
1058                   case C_ADD:
1059                     cluevals[j] += grid[i];
1060                     break;
1061                   case C_MUL:
1062                     cluevals[j] *= grid[i];
1063                     break;
1064                   case C_SUB:
1065                     cluevals[j] = abs(cluevals[j] - grid[i]);
1066                     break;
1067                   case C_DIV:
1068                     {
1069                         int d1 = cluevals[j], d2 = grid[i];
1070                         if (d1 == 0 || d2 == 0)
1071                             cluevals[j] = 0;
1072                         else
1073                             cluevals[j] = d2/d1 + d1/d2;/* one is 0 :-) */
1074                     }
1075                     break;
1076                 }
1077             }
1078         }
1079
1080         for (i = 0; i < a; i++) {
1081             j = dsf_canonify(dsf, i);
1082             if (j == i) {
1083                 clues[j] |= cluevals[j];
1084             }
1085         }
1086
1087         /*
1088          * See if the game can be solved at the specified difficulty
1089          * level, but not at the one below.
1090          */
1091         if (diff > 0) {
1092             memset(soln, 0, a);
1093             ret = solver(w, dsf, clues, soln, diff-1);
1094             if (ret <= diff-1)
1095                 continue;
1096         }
1097         memset(soln, 0, a);
1098         ret = solver(w, dsf, clues, soln, diff);
1099         if (ret != diff)
1100             continue;                  /* go round again */
1101
1102         /*
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
1107          * being successful.
1108          *
1109          * It doesn't seem to be critical for the generation speed,
1110          * though, so for the moment I'm leaving it out.
1111          */
1112
1113         /*
1114          * We've got a usable puzzle!
1115          */
1116         break;
1117     }
1118
1119     /*
1120      * Encode the puzzle description.
1121      */
1122     desc = snewn(40*a, char);
1123     p = desc;
1124     p = encode_block_structure(p, w, dsf);
1125     *p++ = ',';
1126     for (i = 0; i < a; i++) {
1127         j = dsf_canonify(dsf, i);
1128         if (j == 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;
1134             }
1135             p += sprintf(p, "%ld", clues[j] & ~CMASK);
1136         }
1137     }
1138     *p++ = '\0';
1139     desc = sresize(desc, p - desc, char);
1140
1141     /*
1142      * Encode the solution.
1143      */
1144     assert(memcmp(soln, grid, a) == 0);
1145     *aux = snewn(a+2, char);
1146     (*aux)[0] = 'S';
1147     for (i = 0; i < a; i++)
1148         (*aux)[i+1] = '0' + soln[i];
1149     (*aux)[a+1] = '\0';
1150
1151     sfree(grid);
1152     sfree(order);
1153     sfree(revorder);
1154     sfree(singletons);
1155     sfree(dsf);
1156     sfree(clues);
1157     sfree(cluevals);
1158     sfree(soln);
1159
1160     return desc;
1161 }
1162
1163 /* ----------------------------------------------------------------------
1164  * Gameplay.
1165  */
1166
1167 static char *validate_desc(const game_params *params, const char *desc)
1168 {
1169     int w = params->w, a = w*w;
1170     int *dsf;
1171     char *ret;
1172     const char *p = desc;
1173     int i;
1174
1175     /*
1176      * Verify that the block structure makes sense.
1177      */
1178     dsf = snew_dsf(a);
1179     ret = parse_block_structure(&p, w, dsf);
1180     if (ret) {
1181         sfree(dsf);
1182         return ret;
1183     }
1184
1185     if (*p != ',')
1186         return "Expected ',' after block structure description";
1187     p++;
1188
1189     /*
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.
1192      */
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";
1200             } else if (!*p) {
1201                 return "Too few clues for block structure";
1202             } else {
1203                 return "Unrecognised clue type";
1204             }
1205             p++;
1206             while (*p && isdigit((unsigned char)*p)) p++;
1207         }
1208     }
1209     if (*p)
1210         return "Too many clues for block structure";
1211
1212     return NULL;
1213 }
1214
1215 static game_state *new_game(midend *me, const game_params *params,
1216                             const char *desc)
1217 {
1218     int w = params->w, a = w*w;
1219     game_state *state = snew(game_state);
1220     const char *p = desc;
1221     int i;
1222
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);
1229
1230     assert(*p == ',');
1231     p++;
1232
1233     state->clues->clues = snewn(a, long);
1234     for (i = 0; i < a; i++) {
1235         if (dsf_canonify(state->clues->dsf, i) == i) {
1236             long clue = 0;
1237             switch (*p) {
1238               case 'a':
1239                 clue = C_ADD;
1240                 break;
1241               case 'm':
1242                 clue = C_MUL;
1243                 break;
1244               case 's':
1245                 clue = C_SUB;
1246                 assert(dsf_size(state->clues->dsf, i) == 2);
1247                 break;
1248               case 'd':
1249                 clue = C_DIV;
1250                 assert(dsf_size(state->clues->dsf, i) == 2);
1251                 break;
1252               default:
1253                 assert(!"Bad description in new_game");
1254             }
1255             p++;
1256             clue |= atol(p);
1257             while (*p && isdigit((unsigned char)*p)) p++;
1258             state->clues->clues[i] = clue;
1259         } else
1260             state->clues->clues[i] = 0;
1261     }
1262
1263     state->grid = snewn(a, digit);
1264     state->pencil = snewn(a, int);
1265     for (i = 0; i < a; i++) {
1266         state->grid[i] = 0;
1267         state->pencil[i] = 0;
1268     }
1269
1270     state->completed = state->cheated = FALSE;
1271
1272     return state;
1273 }
1274
1275 static game_state *dup_game(const game_state *state)
1276 {
1277     int w = state->par.w, a = w*w;
1278     game_state *ret = snew(game_state);
1279
1280     ret->par = state->par;             /* structure copy */
1281
1282     ret->clues = state->clues;
1283     ret->clues->refcount++;
1284
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));
1289
1290     ret->completed = state->completed;
1291     ret->cheated = state->cheated;
1292
1293     return ret;
1294 }
1295
1296 static void free_game(game_state *state)
1297 {
1298     sfree(state->grid);
1299     sfree(state->pencil);
1300     if (--state->clues->refcount <= 0) {
1301         sfree(state->clues->dsf);
1302         sfree(state->clues->clues);
1303         sfree(state->clues);
1304     }
1305     sfree(state);
1306 }
1307
1308 static char *solve_game(const game_state *state, const game_state *currstate,
1309                         const char *aux, char **error)
1310 {
1311     int w = state->par.w, a = w*w;
1312     int i, ret;
1313     digit *soln;
1314     char *out;
1315
1316     if (aux)
1317         return dupstr(aux);
1318
1319     soln = snewn(a, digit);
1320     memset(soln, 0, a);
1321
1322     ret = solver(w, state->clues->dsf, state->clues->clues,
1323                  soln, DIFFCOUNT-1);
1324
1325     if (ret == diff_impossible) {
1326         *error = "No solution exists for this puzzle";
1327         out = NULL;
1328     } else if (ret == diff_ambiguous) {
1329         *error = "Multiple solutions exist for this puzzle";
1330         out = NULL;
1331     } else {
1332         out = snewn(a+2, char);
1333         out[0] = 'S';
1334         for (i = 0; i < a; i++)
1335             out[i+1] = '0' + soln[i];
1336         out[a+1] = '\0';
1337     }
1338
1339     sfree(soln);
1340     return out;
1341 }
1342
1343 static int game_can_format_as_text_now(const game_params *params)
1344 {
1345     return TRUE;
1346 }
1347
1348 static char *game_text_format(const game_state *state)
1349 {
1350     return NULL;
1351 }
1352
1353 struct game_ui {
1354     /*
1355      * These are the coordinates of the currently highlighted
1356      * square on the grid, if hshow = 1.
1357      */
1358     int hx, hy;
1359     /*
1360      * This indicates whether the current highlight is a
1361      * pencil-mark one or a real one.
1362      */
1363     int hpencil;
1364     /*
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.
1370      */
1371     int hshow;
1372     /*
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.
1376      */
1377     int hcursor;
1378 };
1379
1380 static game_ui *new_ui(const game_state *state)
1381 {
1382     game_ui *ui = snew(game_ui);
1383
1384     ui->hx = ui->hy = 0;
1385     ui->hpencil = ui->hshow = ui->hcursor = 0;
1386
1387     return ui;
1388 }
1389
1390 static void free_ui(game_ui *ui)
1391 {
1392     sfree(ui);
1393 }
1394
1395 static char *encode_ui(const game_ui *ui)
1396 {
1397     return NULL;
1398 }
1399
1400 static void decode_ui(game_ui *ui, const char *encoding)
1401 {
1402 }
1403
1404 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1405                                const game_state *newstate)
1406 {
1407     int w = newstate->par.w;
1408     /*
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.
1413      */
1414     if (ui->hshow && ui->hpencil && !ui->hcursor &&
1415         newstate->grid[ui->hy * w + ui->hx] != 0) {
1416         ui->hshow = 0;
1417     }
1418 }
1419
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)
1426
1427 #define FLASH_TIME 0.4F
1428
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
1435
1436 struct game_drawstate {
1437     int tilesize;
1438     int started;
1439     long *tiles;
1440     long *errors;
1441     char *minus_sign, *times_sign, *divide_sign;
1442 };
1443
1444 static int check_errors(const game_state *state, long *errors)
1445 {
1446     int w = state->par.w, a = w*w;
1447     int i, j, x, y, errs = FALSE;
1448     long *cluevals;
1449     int *full;
1450
1451     cluevals = snewn(a, long);
1452     full = snewn(a, int);
1453
1454     if (errors)
1455         for (i = 0; i < a; i++) {
1456             errors[i] = 0;
1457             full[i] = TRUE;
1458         }
1459
1460     for (i = 0; i < a; i++) {
1461         long clue;
1462
1463         j = dsf_canonify(state->clues->dsf, i);
1464         if (j == i) {
1465             cluevals[i] = state->grid[i];
1466         } else {
1467             clue = state->clues->clues[j] & CMASK;
1468
1469             switch (clue) {
1470               case C_ADD:
1471                 cluevals[j] += state->grid[i];
1472                 break;
1473               case C_MUL:
1474                 cluevals[j] *= state->grid[i];
1475                 break;
1476               case C_SUB:
1477                 cluevals[j] = abs(cluevals[j] - state->grid[i]);
1478                 break;
1479               case C_DIV:
1480                 {
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)
1484                         cluevals[j] = 0;
1485                     else
1486                         cluevals[j] = d2 / d1;
1487                 }
1488                 break;
1489             }
1490         }
1491
1492         if (!state->grid[i])
1493             full[j] = FALSE;
1494     }
1495
1496     for (i = 0; i < a; i++) {
1497         j = dsf_canonify(state->clues->dsf, i);
1498         if (j == i) {
1499             if ((state->clues->clues[j] & ~CMASK) != cluevals[i]) {
1500                 errs = TRUE;
1501                 if (errors && full[j])
1502                     errors[j] |= DF_ERR_CLUE;
1503             }
1504         }
1505     }
1506
1507     sfree(cluevals);
1508     sfree(full);
1509
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);
1515             mask |= bit;
1516         }
1517
1518         if (mask != (1 << (w+1)) - (1 << 1)) {
1519             errs = TRUE;
1520             errmask &= ~1;
1521             if (errors) {
1522                 for (x = 0; x < w; x++)
1523                     if (errmask & (1 << state->grid[y*w+x]))
1524                         errors[y*w+x] |= DF_ERR_LATIN;
1525             }
1526         }
1527     }
1528
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);
1534             mask |= bit;
1535         }
1536
1537         if (mask != (1 << (w+1)) - (1 << 1)) {
1538             errs = TRUE;
1539             errmask &= ~1;
1540             if (errors) {
1541                 for (y = 0; y < w; y++)
1542                     if (errmask & (1 << state->grid[y*w+x]))
1543                         errors[y*w+x] |= DF_ERR_LATIN;
1544             }
1545         }
1546     }
1547
1548     return errs;
1549 }
1550
1551 static char *interpret_move(const game_state *state, game_ui *ui,
1552                             const game_drawstate *ds,
1553                             int x, int y, int button)
1554 {
1555     int w = state->par.w;
1556     int tx, ty;
1557     char buf[80];
1558
1559     button &= ~MOD_MASK;
1560
1561     tx = FROMCOORD(x);
1562     ty = FROMCOORD(y);
1563
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) {
1568                 ui->hshow = 0;
1569             } else {
1570                 ui->hx = tx;
1571                 ui->hy = ty;
1572                 ui->hshow = 1;
1573                 ui->hpencil = 0;
1574             }
1575             ui->hcursor = 0;
1576             return "";                 /* UI activity occurred */
1577         }
1578         if (button == RIGHT_BUTTON) {
1579             /*
1580              * Pencil-mode highlighting for non filled squares.
1581              */
1582             if (state->grid[ty*w+tx] == 0) {
1583                 if (tx == ui->hx && ty == ui->hy &&
1584                     ui->hshow && ui->hpencil) {
1585                     ui->hshow = 0;
1586                 } else {
1587                     ui->hpencil = 1;
1588                     ui->hx = tx;
1589                     ui->hy = ty;
1590                     ui->hshow = 1;
1591                 }
1592             } else {
1593                 ui->hshow = 0;
1594             }
1595             ui->hcursor = 0;
1596             return "";                 /* UI activity occurred */
1597         }
1598     }
1599     if (IS_CURSOR_MOVE(button)) {
1600         move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
1601         ui->hshow = ui->hcursor = 1;
1602         return "";
1603     }
1604     if (ui->hshow &&
1605         (button == CURSOR_SELECT)) {
1606         ui->hpencil = 1 - ui->hpencil;
1607         ui->hcursor = 1;
1608         return "";
1609     }
1610
1611     if (ui->hshow &&
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')
1616             n = 0;
1617
1618         /*
1619          * Can't make pencil marks in a filled square. This can only
1620          * become highlighted if we're using cursor keys.
1621          */
1622         if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1623             return NULL;
1624
1625         sprintf(buf, "%c%d,%d,%d",
1626                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1627
1628         if (!ui->hcursor) ui->hshow = 0;
1629
1630         return dupstr(buf);
1631     }
1632
1633     if (button == 'M' || button == 'm')
1634         return dupstr("M");
1635
1636     return NULL;
1637 }
1638
1639 static game_state *execute_move(const game_state *from, const char *move)
1640 {
1641     int w = from->par.w, a = w*w;
1642     game_state *ret;
1643     int x, y, i, n;
1644
1645     if (move[0] == 'S') {
1646         ret = dup_game(from);
1647         ret->completed = ret->cheated = TRUE;
1648
1649         for (i = 0; i < a; i++) {
1650             if (move[i+1] < '1' || move[i+1] > '0'+w) {
1651                 free_game(ret);
1652                 return NULL;
1653             }
1654             ret->grid[i] = move[i+1] - '0';
1655             ret->pencil[i] = 0;
1656         }
1657
1658         if (move[a+1] != '\0') {
1659             free_game(ret);
1660             return NULL;
1661         }
1662
1663         return ret;
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) {
1667
1668         ret = dup_game(from);
1669         if (move[0] == 'P' && n > 0) {
1670             ret->pencil[y*w+x] ^= 1 << n;
1671         } else {
1672             ret->grid[y*w+x] = n;
1673             ret->pencil[y*w+x] = 0;
1674
1675             if (!ret->completed && !check_errors(ret, NULL))
1676                 ret->completed = TRUE;
1677         }
1678         return ret;
1679     } else if (move[0] == 'M') {
1680         /*
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.)
1685          */
1686         ret = dup_game(from);
1687         for (i = 0; i < a; i++) {
1688             if (!ret->grid[i])
1689                 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1690         }
1691         return ret;
1692     } else
1693         return NULL;                   /* couldn't parse move string */
1694 }
1695
1696 /* ----------------------------------------------------------------------
1697  * Drawing routines.
1698  */
1699
1700 #define SIZE(w) ((w) * TILESIZE + 2*BORDER)
1701
1702 static void game_compute_size(const game_params *params, int tilesize,
1703                               int *x, int *y)
1704 {
1705     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1706     struct { int tilesize; } ads, *ds = &ads;
1707     ads.tilesize = tilesize;
1708
1709     *x = *y = SIZE(params->w);
1710 }
1711
1712 static void game_set_size(drawing *dr, game_drawstate *ds,
1713                           const game_params *params, int tilesize)
1714 {
1715     ds->tilesize = tilesize;
1716 }
1717
1718 static float *game_colours(frontend *fe, int *ncolours)
1719 {
1720     float *ret = snewn(3 * NCOLOURS, float);
1721
1722     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1723
1724     ret[COL_GRID * 3 + 0] = 0.0F;
1725     ret[COL_GRID * 3 + 1] = 0.0F;
1726     ret[COL_GRID * 3 + 2] = 0.0F;
1727
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;
1731
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];
1735
1736     ret[COL_ERROR * 3 + 0] = 1.0F;
1737     ret[COL_ERROR * 3 + 1] = 0.0F;
1738     ret[COL_ERROR * 3 + 2] = 0.0F;
1739
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];
1743
1744     *ncolours = NCOLOURS;
1745     return ret;
1746 }
1747
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", "/" };
1751
1752 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1753 {
1754     int w = state->par.w, a = w*w;
1755     struct game_drawstate *ds = snew(struct game_drawstate);
1756     int i;
1757
1758     ds->tilesize = 0;
1759     ds->started = FALSE;
1760     ds->tiles = snewn(a, long);
1761     for (i = 0; i < a; i++)
1762         ds->tiles[i] = -1;
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));
1767
1768     return ds;
1769 }
1770
1771 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1772 {
1773     sfree(ds->tiles);
1774     sfree(ds->errors);
1775     sfree(ds->minus_sign);
1776     sfree(ds->times_sign);
1777     sfree(ds->divide_sign);
1778     sfree(ds);
1779 }
1780
1781 static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
1782                       int x, int y, long tile, int only_one_op)
1783 {
1784     int w = clues->w /* , a = w*w */;
1785     int tx, ty, tw, th;
1786     int cx, cy, cw, ch;
1787     char str[64];
1788
1789     tx = BORDER + x * TILESIZE + 1 + GRIDEXTRA;
1790     ty = BORDER + y * TILESIZE + 1 + GRIDEXTRA;
1791
1792     cx = tx;
1793     cy = ty;
1794     cw = tw = TILESIZE-1-2*GRIDEXTRA;
1795     ch = th = TILESIZE-1-2*GRIDEXTRA;
1796
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))
1800         cw += GRIDEXTRA;
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))
1804         ch += GRIDEXTRA;
1805
1806     clip(dr, cx, cy, cw, ch);
1807
1808     /* background needs erasing */
1809     draw_rect(dr, cx, cy, cw, ch,
1810               (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
1811
1812     /* pencil-mode highlight */
1813     if (tile & DF_HIGHLIGHT_PENCIL) {
1814         int coords[6];
1815         coords[0] = cx;
1816         coords[1] = cy;
1817         coords[2] = cx+cw/2;
1818         coords[3] = cy;
1819         coords[4] = cx;
1820         coords[5] = cy+ch/2;
1821         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1822     }
1823
1824     /*
1825      * Draw the corners of thick lines in corner-adjacent squares,
1826      * which jut into this square by one pixel.
1827      */
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);
1836
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);
1842         /*
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.
1850          */
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);
1860     }
1861
1862     /* new number needs drawing? */
1863     if (tile & DF_DIGIT_MASK) {
1864         str[1] = '\0';
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);
1869     } else {
1870         int i, j, npencil;
1871         int pl, pr, pt, pb;
1872         float bestsize;
1873         int pw, ph, minph, pbest, fontsize;
1874
1875         /* Count the pencil marks required. */
1876         for (i = 1, npencil = 0; i <= w; i++)
1877             if (tile & (1L << (i + DF_PENCIL_SHIFT)))
1878                 npencil++;
1879         if (npencil) {
1880
1881             minph = 2;
1882
1883             /*
1884              * Determine the bounding rectangle within which we're going
1885              * to put the pencil marks.
1886              */
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) {
1893                 /*
1894                  * Make space for the clue text.
1895                  */
1896                 pt += TILESIZE/4;
1897                 /* minph--; */
1898             }
1899
1900             /*
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.
1904              *
1905              * So now we work out what the grid size ought to be.
1906              */
1907             bestsize = 0.0;
1908             pbest = 0;
1909             /* Minimum */
1910             for (pw = 3; pw < max(npencil,4); pw++) {
1911                 float fw, fh, fs;
1912
1913                 ph = (npencil + pw - 1) / pw;
1914                 ph = max(ph, minph);
1915                 fw = (pr - pl) / (float)pw;
1916                 fh = (pb - pt) / (float)ph;
1917                 fs = min(fw, fh);
1918                 if (fs > bestsize) {
1919                     bestsize = fs;
1920                     pbest = pw;
1921                 }
1922             }
1923             assert(pbest > 0);
1924             pw = pbest;
1925             ph = (npencil + pw - 1) / pw;
1926             ph = max(ph, minph);
1927
1928             /*
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.)
1933              */
1934             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1935
1936             /*
1937              * Centre the resulting figure in the square.
1938              */
1939             pl = tx + (TILESIZE - fontsize * pw) / 2;
1940             pt = ty + (TILESIZE - fontsize * ph) / 2;
1941
1942             /*
1943              * And move it down a bit if it's collided with some
1944              * clue text.
1945              */
1946             if (dsf_canonify(clues->dsf, y*w+x) == y*w+x) {
1947                 pt = max(pt, ty + GRIDEXTRA * 3 + TILESIZE/4);
1948             }
1949
1950             /*
1951              * Now actually draw the pencil marks.
1952              */
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;
1956
1957                     str[1] = '\0';
1958                     str[0] = i + '0';
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);
1963                     j++;
1964                 }
1965         }
1966     }
1967
1968     unclip(dr);
1969
1970     draw_update(dr, cx, cy, cw, ch);
1971 }
1972
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)
1977 {
1978     int w = state->par.w /*, a = w*w */;
1979     int x, y;
1980
1981     if (!ds->started) {
1982         /*
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.
1987          */
1988         draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1989
1990         /*
1991          * Big containing rectangle.
1992          */
1993         draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1994                   w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1995                   COL_GRID);
1996
1997         draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1998
1999         ds->started = TRUE;
2000     }
2001
2002     check_errors(state, ds->errors);
2003
2004     for (y = 0; y < w; y++) {
2005         for (x = 0; x < w; x++) {
2006             long tile = 0L;
2007
2008             if (state->grid[y*w+x])
2009                 tile = state->grid[y*w+x];
2010             else
2011                 tile = (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;
2012
2013             if (ui->hshow && ui->hx == x && ui->hy == y)
2014                 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
2015
2016             if (flashtime > 0 &&
2017                 (flashtime <= FLASH_TIME/3 ||
2018                  flashtime >= FLASH_TIME*2/3))
2019                 tile |= DF_HIGHLIGHT;  /* completion flash */
2020
2021             tile |= ds->errors[y*w+x];
2022
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);
2027             }
2028         }
2029     }
2030 }
2031
2032 static float game_anim_length(const game_state *oldstate,
2033                               const game_state *newstate, int dir, game_ui *ui)
2034 {
2035     return 0.0F;
2036 }
2037
2038 static float game_flash_length(const game_state *oldstate,
2039                                const game_state *newstate, int dir, game_ui *ui)
2040 {
2041     if (!oldstate->completed && newstate->completed &&
2042         !oldstate->cheated && !newstate->cheated)
2043         return FLASH_TIME;
2044     return 0.0F;
2045 }
2046
2047 static int game_status(const game_state *state)
2048 {
2049     return state->completed ? +1 : 0;
2050 }
2051
2052 static int game_timing_state(const game_state *state, game_ui *ui)
2053 {
2054     if (state->completed)
2055         return FALSE;
2056     return TRUE;
2057 }
2058
2059 static void game_print_size(const game_params *params, float *x, float *y)
2060 {
2061     int pw, ph;
2062
2063     /*
2064      * We use 9mm squares by default, like Solo.
2065      */
2066     game_compute_size(params, 900, &pw, &ph);
2067     *x = pw / 100.0F;
2068     *y = ph / 100.0F;
2069 }
2070
2071 /*
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
2077  * single polygon.
2078  */
2079 static void outline_block_structure(drawing *dr, game_drawstate *ds,
2080                                     int w, int *dsf, int ink)
2081 {
2082     int a = w*w;
2083     int *coords;
2084     int i, n;
2085     int x, y, dx, dy, sx, sy, sdx, sdy;
2086
2087     coords = snewn(4*a, int);
2088
2089     /*
2090      * Iterate over all the blocks.
2091      */
2092     for (i = 0; i < a; i++) {
2093         if (dsf_canonify(dsf, i) != i)
2094             continue;
2095
2096         /*
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.
2100          */
2101         x = i % w;
2102         y = i / w;
2103         dx = -1;
2104         dy = 0;
2105
2106         /*
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.
2112          */
2113         sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
2114         n = 0;
2115         do {
2116             int cx, cy, tx, ty, nin;
2117
2118             /*
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).
2127              */
2128             nin = 0;
2129             tx = x - dy + dx;
2130             ty = y + dx + dy;
2131             nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2132                     dsf_canonify(dsf, ty*w+tx) == i);
2133             tx = x - dy;
2134             ty = y + dx;
2135             nin += (tx >= 0 && tx < w && ty >= 0 && ty < w &&
2136                     dsf_canonify(dsf, ty*w+tx) == i);
2137             if (nin == 0) {
2138                 /*
2139                  * Turn right.
2140                  */
2141                 int tmp;
2142                 tmp = dx;
2143                 dx = -dy;
2144                 dy = tmp;
2145             } else if (nin == 2) {
2146                 /*
2147                  * Turn left.
2148                  */
2149                 int tmp;
2150
2151                 x += dx;
2152                 y += dy;
2153
2154                 tmp = dx;
2155                 dx = dy;
2156                 dy = -tmp;
2157
2158                 x -= dx;
2159                 y -= dy;
2160             } else {
2161                 /*
2162                  * Go straight on.
2163                  */
2164                 x -= dy;
2165                 y += dx;
2166             }
2167
2168             /*
2169              * Now enforce by assertion that we ended up
2170              * somewhere sensible.
2171              */
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);
2176
2177             /*
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.
2183              */
2184             assert(n < 2*w+2);
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;
2189             n++;
2190
2191         } while (x != sx || y != sy || dx != sdx || dy != sdy);
2192
2193         /*
2194          * That's our polygon; now draw it.
2195          */
2196         draw_polygon(dr, coords, n, -1, ink);
2197     }
2198
2199     sfree(coords);
2200 }
2201
2202 static void game_print(drawing *dr, const game_state *state, int tilesize)
2203 {
2204     int w = state->par.w;
2205     int ink = print_mono_colour(dr, 0);
2206     int x, y;
2207     char *minus_sign, *times_sign, *divide_sign;
2208
2209     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2210     game_drawstate ads, *ds = &ads;
2211     game_set_size(dr, ds, NULL, tilesize);
2212
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));
2216
2217     /*
2218      * Border.
2219      */
2220     print_line_width(dr, 3 * TILESIZE / 40);
2221     draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);
2222
2223     /*
2224      * Main grid.
2225      */
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);
2230     }
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);
2235     }
2236
2237     /*
2238      * Thick lines between cells.
2239      */
2240     print_line_width(dr, 3 * TILESIZE / 40);
2241     outline_block_structure(dr, ds, w, state->clues->dsf, ink);
2242
2243     /*
2244      * Clues.
2245      */
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);
2252                 char str[64];
2253
2254                 /*
2255                  * As in the drawing code, we omit the operator for
2256                  * blocks of area 1.
2257                  */
2258                 sprintf (str, "%ld%s", clueval,
2259                          (size == 1 ? "" :
2260                           cluetype == C_ADD ? "+" :
2261                           cluetype == C_SUB ? minus_sign :
2262                           cluetype == C_MUL ? times_sign :
2263                           /* cluetype == C_DIV ? */ divide_sign));
2264
2265                 draw_text(dr,
2266                           BORDER+x*TILESIZE + 5*TILESIZE/80,
2267                           BORDER+y*TILESIZE + 20*TILESIZE/80,
2268                           FONT_VARIABLE, TILESIZE/4,
2269                           ALIGN_VNORMAL | ALIGN_HLEFT,
2270                           ink, str);
2271             }
2272
2273     /*
2274      * Numbers for the solution, if any.
2275      */
2276     for (y = 0; y < w; y++)
2277         for (x = 0; x < w; x++)
2278             if (state->grid[y*w+x]) {
2279                 char str[2];
2280                 str[1] = '\0';
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);
2286             }
2287
2288     sfree(minus_sign);
2289     sfree(times_sign);
2290     sfree(divide_sign);
2291 }
2292
2293 #ifdef COMBINED
2294 #define thegame keen
2295 #endif
2296
2297 const struct game thegame = {
2298     "Keen", "games.keen", "keen",
2299     default_params,
2300     game_fetch_preset,
2301     decode_params,
2302     encode_params,
2303     free_params,
2304     dup_params,
2305     TRUE, game_configure, custom_params,
2306     validate_params,
2307     new_game_desc,
2308     validate_desc,
2309     new_game,
2310     dup_game,
2311     free_game,
2312     TRUE, solve_game,
2313     FALSE, game_can_format_as_text_now, game_text_format,
2314     new_ui,
2315     free_ui,
2316     encode_ui,
2317     decode_ui,
2318     game_changed_state,
2319     interpret_move,
2320     execute_move,
2321     PREFERRED_TILESIZE, game_compute_size, game_set_size,
2322     game_colours,
2323     game_new_drawstate,
2324     game_free_drawstate,
2325     game_redraw,
2326     game_anim_length,
2327     game_flash_length,
2328     game_status,
2329     TRUE, FALSE, game_print_size, game_print,
2330     FALSE,                             /* wants_statusbar */
2331     FALSE, game_timing_state,
2332     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
2333 };
2334
2335 #ifdef STANDALONE_SOLVER
2336
2337 #include <stdarg.h>
2338
2339 int main(int argc, char **argv)
2340 {
2341     game_params *p;
2342     game_state *s;
2343     char *id = NULL, *desc, *err;
2344     int grade = FALSE;
2345     int ret, diff, really_show_working = FALSE;
2346
2347     while (--argc > 0) {
2348         char *p = *++argv;
2349         if (!strcmp(p, "-v")) {
2350             really_show_working = TRUE;
2351         } else if (!strcmp(p, "-g")) {
2352             grade = TRUE;
2353         } else if (*p == '-') {
2354             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2355             return 1;
2356         } else {
2357             id = p;
2358         }
2359     }
2360
2361     if (!id) {
2362         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2363         return 1;
2364     }
2365
2366     desc = strchr(id, ':');
2367     if (!desc) {
2368         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2369         return 1;
2370     }
2371     *desc++ = '\0';
2372
2373     p = default_params();
2374     decode_params(p, id);
2375     err = validate_desc(p, desc);
2376     if (err) {
2377         fprintf(stderr, "%s: %s\n", argv[0], err);
2378         return 1;
2379     }
2380     s = new_game(NULL, p, desc);
2381
2382     /*
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.
2386      */
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,
2392                      s->grid, diff);
2393         if (ret <= diff)
2394             break;
2395     }
2396
2397     if (diff == DIFFCOUNT) {
2398         if (grade)
2399             printf("Difficulty rating: ambiguous\n");
2400         else
2401             printf("Unable to find a unique solution\n");
2402     } else {
2403         if (grade) {
2404             if (ret == diff_impossible)
2405                 printf("Difficulty rating: impossible (no solution exists)\n");
2406             else
2407                 printf("Difficulty rating: %s\n", keen_diffnames[ret]);
2408         } else {
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,
2412                          s->grid, diff);
2413             if (ret != diff)
2414                 printf("Puzzle is inconsistent\n");
2415             else {
2416                 /*
2417                  * We don't have a game_text_format for this game,
2418                  * so we have to output the solution manually.
2419                  */
2420                 int x, y;
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]);
2424                     }
2425                     putchar('\n');
2426                 }
2427             }
2428         }
2429     }
2430
2431     return 0;
2432 }
2433
2434 #endif
2435
2436 /* vim: set shiftwidth=4 tabstop=8: */