chiark / gitweb /
Faintly highlight the leading diagonal of Group's grid.
[sgt-puzzles.git] / unfinished / group.c
1 /*
2  * group.c: a Latin-square puzzle, but played with groups' Cayley
3  * tables. That is, you are given a Cayley table of a group with
4  * most elements blank and a few clues, and you must fill it in
5  * so as to preserve the group axioms.
6  *
7  * This is a perfectly playable and fully working puzzle, but I'm
8  * leaving it for the moment in the 'unfinished' directory because
9  * it's just too esoteric (not to mention _hard_) for me to be
10  * comfortable presenting it to the general public as something they
11  * might (implicitly) actually want to play.
12  *
13  * TODO:
14  *
15  *  - more solver techniques?
16  *     * Inverses: once we know that gh = e, we can immediately
17  *       deduce hg = e as well; then for any gx=y we can deduce
18  *       hy=x, and for any xg=y we have yh=x.
19  *     * Hard-mode associativity: we currently deduce based on
20  *       definite numbers in the grid, but we could also winnow
21  *       based on _possible_ numbers.
22  *     * My overambitious original thoughts included wondering if we
23  *       could infer that there must be elements of certain orders
24  *       (e.g. a group of order divisible by 5 must contain an
25  *       element of order 5), but I think in fact this is probably
26  *       silly.
27  */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <assert.h>
33 #include <ctype.h>
34 #include <math.h>
35
36 #include "puzzles.h"
37 #include "latin.h"
38
39 /*
40  * Difficulty levels. I do some macro ickery here to ensure that my
41  * enum and the various forms of my name list always match up.
42  */
43 #define DIFFLIST(A) \
44     A(TRIVIAL,Trivial,NULL,t) \
45     A(NORMAL,Normal,solver_normal,n) \
46     A(HARD,Hard,NULL,h) \
47     A(EXTREME,Extreme,NULL,x) \
48     A(UNREASONABLE,Unreasonable,NULL,u)
49 #define ENUM(upper,title,func,lower) DIFF_ ## upper,
50 #define TITLE(upper,title,func,lower) #title,
51 #define ENCODE(upper,title,func,lower) #lower
52 #define CONFIG(upper,title,func,lower) ":" #title
53 enum { DIFFLIST(ENUM) DIFFCOUNT };
54 static char const *const group_diffnames[] = { DIFFLIST(TITLE) };
55 static char const group_diffchars[] = DIFFLIST(ENCODE);
56 #define DIFFCONFIG DIFFLIST(CONFIG)
57
58 enum {
59     COL_BACKGROUND,
60     COL_GRID,
61     COL_USER,
62     COL_HIGHLIGHT,
63     COL_ERROR,
64     COL_PENCIL,
65     COL_DIAGONAL,
66     NCOLOURS
67 };
68
69 /*
70  * In identity mode, we number the elements e,a,b,c,d,f,g,h,...
71  * Otherwise, they're a,b,c,d,e,f,g,h,... in the obvious way.
72  */
73 #define E_TO_FRONT(c,id) ( (id) && (c)<=5 ? (c) % 5 + 1 : (c) )
74 #define E_FROM_FRONT(c,id) ( (id) && (c)<=5 ? ((c) + 3) % 5 + 1 : (c) )
75
76 #define FROMCHAR(c,id) E_TO_FRONT((((c)-('A'-1)) & ~0x20), id)
77 #define ISCHAR(c) (((c)>='A'&&(c)<='Z') || ((c)>='a'&&(c)<='z'))
78 #define TOCHAR(c,id) (E_FROM_FRONT(c,id) + ('a'-1))
79
80 struct game_params {
81     int w, diff, id;
82 };
83
84 struct game_state {
85     game_params par;
86     digit *grid;
87     unsigned char *immutable;
88     int *pencil;                       /* bitmaps using bits 1<<1..1<<n */
89     int completed, cheated;
90     digit *sequence;                   /* sequence of group elements shown */
91
92     /*
93      * This array indicates thick lines separating rows and columns
94      * placed and unplaced manually by the user as a visual aid, e.g.
95      * to delineate a subgroup and its cosets.
96      *
97      * When a line is placed, it's deemed to be between the two
98      * particular group elements that are on either side of it at the
99      * time; dragging those two away from each other automatically
100      * gets rid of the line. Hence, for a given element i, dividers[i]
101      * is either -1 (indicating no divider to the right of i), or some
102      * other element (indicating a divider to the right of i iff that
103      * element is the one right of it). These are eagerly cleared
104      * during drags.
105      */
106     int *dividers;                     /* thick lines between rows/cols */
107 };
108
109 static game_params *default_params(void)
110 {
111     game_params *ret = snew(game_params);
112
113     ret->w = 6;
114     ret->diff = DIFF_NORMAL;
115     ret->id = TRUE;
116
117     return ret;
118 }
119
120 const static struct game_params group_presets[] = {
121     {  6, DIFF_NORMAL, TRUE },
122     {  6, DIFF_NORMAL, FALSE },
123     {  8, DIFF_NORMAL, TRUE },
124     {  8, DIFF_NORMAL, FALSE },
125     {  8, DIFF_HARD, TRUE },
126     {  8, DIFF_HARD, FALSE },
127     { 12, DIFF_NORMAL, TRUE },
128 };
129
130 static int game_fetch_preset(int i, char **name, game_params **params)
131 {
132     game_params *ret;
133     char buf[80];
134
135     if (i < 0 || i >= lenof(group_presets))
136         return FALSE;
137
138     ret = snew(game_params);
139     *ret = group_presets[i]; /* structure copy */
140
141     sprintf(buf, "%dx%d %s%s", ret->w, ret->w, group_diffnames[ret->diff],
142             ret->id ? "" : ", identity hidden");
143
144     *name = dupstr(buf);
145     *params = ret;
146     return TRUE;
147 }
148
149 static void free_params(game_params *params)
150 {
151     sfree(params);
152 }
153
154 static game_params *dup_params(const game_params *params)
155 {
156     game_params *ret = snew(game_params);
157     *ret = *params;                    /* structure copy */
158     return ret;
159 }
160
161 static void decode_params(game_params *params, char const *string)
162 {
163     char const *p = string;
164
165     params->w = atoi(p);
166     while (*p && isdigit((unsigned char)*p)) p++;
167     params->diff = DIFF_NORMAL;
168     params->id = TRUE;
169
170     while (*p) {
171         if (*p == 'd') {
172             int i;
173             p++;
174             params->diff = DIFFCOUNT+1; /* ...which is invalid */
175             if (*p) {
176                 for (i = 0; i < DIFFCOUNT; i++) {
177                     if (*p == group_diffchars[i])
178                         params->diff = i;
179                 }
180                 p++;
181             }
182         } else if (*p == 'i') {
183             params->id = FALSE;
184             p++;
185         } else {
186             /* unrecognised character */
187             p++;
188         }
189     }
190 }
191
192 static char *encode_params(const game_params *params, int full)
193 {
194     char ret[80];
195
196     sprintf(ret, "%d", params->w);
197     if (full)
198         sprintf(ret + strlen(ret), "d%c", group_diffchars[params->diff]);
199     if (!params->id)
200         sprintf(ret + strlen(ret), "i");
201
202     return dupstr(ret);
203 }
204
205 static config_item *game_configure(const game_params *params)
206 {
207     config_item *ret;
208     char buf[80];
209
210     ret = snewn(4, config_item);
211
212     ret[0].name = "Grid size";
213     ret[0].type = C_STRING;
214     sprintf(buf, "%d", params->w);
215     ret[0].sval = dupstr(buf);
216     ret[0].ival = 0;
217
218     ret[1].name = "Difficulty";
219     ret[1].type = C_CHOICES;
220     ret[1].sval = DIFFCONFIG;
221     ret[1].ival = params->diff;
222
223     ret[2].name = "Show identity";
224     ret[2].type = C_BOOLEAN;
225     ret[2].sval = NULL;
226     ret[2].ival = params->id;
227
228     ret[3].name = NULL;
229     ret[3].type = C_END;
230     ret[3].sval = NULL;
231     ret[3].ival = 0;
232
233     return ret;
234 }
235
236 static game_params *custom_params(const config_item *cfg)
237 {
238     game_params *ret = snew(game_params);
239
240     ret->w = atoi(cfg[0].sval);
241     ret->diff = cfg[1].ival;
242     ret->id = cfg[2].ival;
243
244     return ret;
245 }
246
247 static char *validate_params(const game_params *params, int full)
248 {
249     if (params->w < 3 || params->w > 26)
250         return "Grid size must be between 3 and 26";
251     if (params->diff >= DIFFCOUNT)
252         return "Unknown difficulty rating";
253     if (!params->id && params->diff == DIFF_TRIVIAL) {
254         /*
255          * We can't have a Trivial-difficulty puzzle (i.e. latin
256          * square deductions only) without a clear identity, because
257          * identityless puzzles always have two rows and two columns
258          * entirely blank, and no latin-square deduction permits the
259          * distinguishing of two such rows.
260          */
261         return "Trivial puzzles must have an identity";
262     }
263     if (!params->id && params->w == 3) {
264         /*
265          * We can't have a 3x3 puzzle without an identity either,
266          * because 3x3 puzzles can't ever be harder than Trivial
267          * (there are no 3x3 latin squares which aren't also valid
268          * group tables, so enabling group-based deductions doesn't
269          * rule out any possible solutions) and - as above - Trivial
270          * puzzles can't not have an identity.
271          */
272         return "3x3 puzzles must have an identity";
273     }
274     return NULL;
275 }
276
277 /* ----------------------------------------------------------------------
278  * Solver.
279  */
280
281 static int solver_normal(struct latin_solver *solver, void *vctx)
282 {
283     int w = solver->o;
284 #ifdef STANDALONE_SOLVER
285     char **names = solver->names;
286 #endif
287     digit *grid = solver->grid;
288     int i, j, k;
289
290     /*
291      * Deduce using associativity: (ab)c = a(bc).
292      *
293      * So we pick any a,b,c we like; then if we know ab, bc, and
294      * (ab)c we can fill in a(bc).
295      */
296     for (i = 1; i < w; i++)
297         for (j = 1; j < w; j++)
298             for (k = 1; k < w; k++) {
299                 if (!grid[i*w+j] || !grid[j*w+k])
300                     continue;
301                 if (grid[(grid[i*w+j]-1)*w+k] &&
302                     !grid[i*w+(grid[j*w+k]-1)]) {
303                     int x = grid[j*w+k]-1, y = i;
304                     int n = grid[(grid[i*w+j]-1)*w+k];
305 #ifdef STANDALONE_SOLVER
306                     if (solver_show_working) {
307                         printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
308                                solver_recurse_depth*4, "",
309                                names[i], names[j], names[k],
310                                names[grid[i*w+j]-1], names[k],
311                                names[i], names[grid[j*w+k]-1]);
312                         printf("%*s  placing %s at (%d,%d)\n",
313                                solver_recurse_depth*4, "",
314                                names[n-1], x+1, y+1);
315                     }
316 #endif
317                     if (solver->cube[(x*w+y)*w+n-1]) {
318                         latin_solver_place(solver, x, y, n);
319                         return 1;
320                     } else {
321 #ifdef STANDALONE_SOLVER
322                         if (solver_show_working)
323                             printf("%*s  contradiction!\n",
324                                    solver_recurse_depth*4, "");
325                         return -1;
326 #endif
327                     }
328                 }
329                 if (!grid[(grid[i*w+j]-1)*w+k] &&
330                     grid[i*w+(grid[j*w+k]-1)]) {
331                     int x = k, y = grid[i*w+j]-1;
332                     int n = grid[i*w+(grid[j*w+k]-1)];
333 #ifdef STANDALONE_SOLVER
334                     if (solver_show_working) {
335                         printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
336                                solver_recurse_depth*4, "",
337                                names[i], names[j], names[k],
338                                names[grid[i*w+j]-1], names[k],
339                                names[i], names[grid[j*w+k]-1]);
340                         printf("%*s  placing %s at (%d,%d)\n",
341                                solver_recurse_depth*4, "",
342                                names[n-1], x+1, y+1);
343                     }
344 #endif
345                     if (solver->cube[(x*w+y)*w+n-1]) {
346                         latin_solver_place(solver, x, y, n);
347                         return 1;
348                     } else {
349 #ifdef STANDALONE_SOLVER
350                         if (solver_show_working)
351                             printf("%*s  contradiction!\n",
352                                    solver_recurse_depth*4, "");
353                         return -1;
354 #endif
355                     }
356                 }
357             }
358
359     return 0;
360 }
361
362 #define SOLVER(upper,title,func,lower) func,
363 static usersolver_t const group_solvers[] = { DIFFLIST(SOLVER) };
364
365 static int solver(const game_params *params, digit *grid, int maxdiff)
366 {
367     int w = params->w;
368     int ret;
369     struct latin_solver solver;
370 #ifdef STANDALONE_SOLVER
371     char *p, text[100], *names[50];
372     int i;
373 #endif
374
375     latin_solver_alloc(&solver, grid, w);
376 #ifdef STANDALONE_SOLVER
377     for (i = 0, p = text; i < w; i++) {
378         names[i] = p;
379         *p++ = TOCHAR(i+1, params->id);
380         *p++ = '\0';
381     }
382     solver.names = names;
383 #endif
384
385     ret = latin_solver_main(&solver, maxdiff,
386                             DIFF_TRIVIAL, DIFF_HARD, DIFF_EXTREME,
387                             DIFF_EXTREME, DIFF_UNREASONABLE,
388                             group_solvers, NULL, NULL, NULL);
389
390     latin_solver_free(&solver);
391
392     return ret;
393 }
394
395 /* ----------------------------------------------------------------------
396  * Grid generation.
397  */
398
399 static char *encode_grid(char *desc, digit *grid, int area)
400 {
401     int run, i;
402     char *p = desc;
403
404     run = 0;
405     for (i = 0; i <= area; i++) {
406         int n = (i < area ? grid[i] : -1);
407
408         if (!n)
409             run++;
410         else {
411             if (run) {
412                 while (run > 0) {
413                     int c = 'a' - 1 + run;
414                     if (run > 26)
415                         c = 'z';
416                     *p++ = c;
417                     run -= c - ('a' - 1);
418                 }
419             } else {
420                 /*
421                  * If there's a number in the very top left or
422                  * bottom right, there's no point putting an
423                  * unnecessary _ before or after it.
424                  */
425                 if (p > desc && n > 0)
426                     *p++ = '_';
427             }
428             if (n > 0)
429                 p += sprintf(p, "%d", n);
430             run = 0;
431         }
432     }
433     return p;
434 }
435
436 /* ----- data generated by group.gap begins ----- */
437
438 struct group {
439     unsigned long autosize;
440     int order, ngens;
441     const char *gens;
442 };
443 struct groups {
444     int ngroups;
445     const struct group *groups;
446 };
447
448 static const struct group groupdata[] = {
449     /* order 2 */
450     {1L, 2, 1, "BA"},
451     /* order 3 */
452     {2L, 3, 1, "BCA"},
453     /* order 4 */
454     {2L, 4, 1, "BCDA"},
455     {6L, 4, 2, "BADC" "CDAB"},
456     /* order 5 */
457     {4L, 5, 1, "BCDEA"},
458     /* order 6 */
459     {6L, 6, 2, "CFEBAD" "BADCFE"},
460     {2L, 6, 1, "DCFEBA"},
461     /* order 7 */
462     {6L, 7, 1, "BCDEFGA"},
463     /* order 8 */
464     {4L, 8, 1, "BCEFDGHA"},
465     {8L, 8, 2, "BDEFGAHC" "EGBHDCFA"},
466     {8L, 8, 2, "EGBHDCFA" "BAEFCDHG"},
467     {24L, 8, 2, "BDEFGAHC" "CHDGBEAF"},
468     {168L, 8, 3, "BAEFCDHG" "CEAGBHDF" "DFGAHBCE"},
469     /* order 9 */
470     {6L, 9, 1, "BDECGHFIA"},
471     {48L, 9, 2, "BDEAGHCIF" "CEFGHAIBD"},
472     /* order 10 */
473     {20L, 10, 2, "CJEBGDIFAH" "BADCFEHGJI"},
474     {4L, 10, 1, "DCFEHGJIBA"},
475     /* order 11 */
476     {10L, 11, 1, "BCDEFGHIJKA"},
477     /* order 12 */
478     {12L, 12, 2, "GLDKJEHCBIAF" "BCEFAGIJDKLH"},
479     {4L, 12, 1, "EHIJKCBLDGFA"},
480     {24L, 12, 2, "BEFGAIJKCDLH" "FJBKHLEGDCIA"},
481     {12L, 12, 2, "GLDKJEHCBIAF" "BAEFCDIJGHLK"},
482     {12L, 12, 2, "FDIJGHLBKAEC" "GIDKFLHCJEAB"},
483     /* order 13 */
484     {12L, 13, 1, "BCDEFGHIJKLMA"},
485     /* order 14 */
486     {42L, 14, 2, "ELGNIBKDMFAHCJ" "BADCFEHGJILKNM"},
487     {6L, 14, 1, "FEHGJILKNMBADC"},
488     /* order 15 */
489     {8L, 15, 1, "EGHCJKFMNIOBLDA"},
490     /* order 16 */
491     {8L, 16, 1, "MKNPFOADBGLCIEHJ"},
492     {96L, 16, 2, "ILKCONFPEDJHGMAB" "BDFGHIAKLMNCOEPJ"},
493     {32L, 16, 2, "MIHPFDCONBLAKJGE" "BEFGHJKALMNOCDPI"},
494     {32L, 16, 2, "IFACOGLMDEJBNPKH" "BEFGHJKALMNOCDPI"},
495     {16L, 16, 2, "MOHPFKCINBLADJGE" "BDFGHIEKLMNJOAPC"},
496     {16L, 16, 2, "MIHPFDJONBLEKCGA" "BDFGHIEKLMNJOAPC"},
497     {32L, 16, 2, "MOHPFDCINBLEKJGA" "BAFGHCDELMNIJKPO"},
498     {16L, 16, 2, "MIHPFKJONBLADCGE" "GDPHNOEKFLBCIAMJ"},
499     {32L, 16, 2, "MIBPFDJOGHLEKCNA" "CLEIJGMPKAOHNFDB"},
500     {192L, 16, 3,
501      "MCHPFAIJNBLDEOGK" "BEFGHJKALMNOCDPI" "GKLBNOEDFPHJIAMC"},
502     {64L, 16, 3, "MCHPFAIJNBLDEOGK" "LOGFPKJIBNMEDCHA" "CMAIJHPFDEONBLKG"},
503     {192L, 16, 3,
504      "IPKCOGMLEDJBNFAH" "BEFGHJKALMNOCDPI" "CMEIJBPFKAOGHLDN"},
505     {48L, 16, 3, "IPDJONFLEKCBGMAH" "FJBLMEOCGHPKAIND" "DGIEKLHNJOAMPBCF"},
506     {20160L, 16, 4,
507      "EHJKAMNBOCDPFGIL" "BAFGHCDELMNIJKPO" "CFAIJBLMDEOGHPKN"
508      "DGIAKLBNCOEFPHJM"},
509     /* order 17 */
510     {16L, 17, 1, "EFGHIJKLMNOPQABCD"},
511     /* order 18 */
512     {54L, 18, 2, "MKIQOPNAGLRECDBJHF" "BAEFCDJKLGHIOPMNRQ"},
513     {6L, 18, 1, "ECJKGHFOPDMNLRIQBA"},
514     {12L, 18, 2, "ECJKGHBOPAMNFRDQLI" "KNOPQCFREIGHLJAMBD"},
515     {432L, 18, 3,
516      "IFNAKLQCDOPBGHREMJ" "NOQCFRIGHKLJAMPBDE" "BAEFCDJKLGHIOPMNRQ"},
517     {48L, 18, 2, "ECJKGHBOPAMNFRDQLI" "FDKLHIOPBMNAREQCJG"},
518     /* order 19 */
519     {18L, 19, 1, "EFGHIJKLMNOPQRSABCD"},
520     /* order 20 */
521     {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "EABICDFMGHJQKLNTOPRS"},
522     {8L, 20, 1, "EHIJLCMNPGQRSKBTDOFA"},
523     {20L, 20, 2, "DJSHQNCLTRGPEBKAIFOM" "EABICDFMGHJQKLNTOPRS"},
524     {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "ECBIAGFMDKJQHONTLSRP"},
525     {24L, 20, 2, "IGFMDKJQHONTLSREPCBA" "FDIJGHMNKLQROPTBSAEC"},
526     /* order 21 */
527     {42L, 21, 2, "ITLSBOUERDHAGKCJNFMQP" "EJHLMKOPNRSQAUTCDBFGI"},
528     {12L, 21, 1, "EGHCJKFMNIPQLSTOUBRDA"},
529     /* order 22 */
530     {110L, 22, 2, "ETGVIBKDMFOHQJSLUNAPCR" "BADCFEHGJILKNMPORQTSVU"},
531     {10L, 22, 1, "FEHGJILKNMPORQTSVUBADC"},
532     /* order 23 */
533     {22L, 23, 1, "EFGHIJKLMNOPQRSTUVWABCD"},
534     /* order 24 */
535     {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "HRNOPSWCTUVBLDIJXFGAKQME"},
536     {8L, 24, 1, "MQBTUDRWFGHXJELINOPKSAVC"},
537     {24L, 24, 2, "IOQRBEUVFWGHKLAXMNPSCDTJ" "NJXOVGDKSMTFIPQELCURBWAH"},
538     {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "HSNOPWLDTUVBRIAKXFGCQEMJ"},
539     {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "TWHNXLRIOPUMSACQVBFDEJGK"},
540     {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "BAFGHCDEMNOPIJKLTUVQRSXW"},
541     {48L, 24, 3,
542      "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
543      "HSNOPWLDTUVBRIAKXFGCQEMJ"},
544     {24L, 24, 3,
545      "QUKJWPXFESRIVBMNLDCGHTAO" "JXEQRVUMKLWCPGFTSAIBONDH"
546      "TRONXLWCHVUMSAIJPGFDEQBK"},
547     {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "VKXHOQASNTPBCWDEUFGIJLMR"},
548     {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "RMLWIGTUSDJQOPFXEKCBVNAH"},
549     {48L, 24, 2, "IULQRGXMSDCWOPNTEKJBVFAH" "GLMOPRSDTUBVWIEKFXHJQANC"},
550     {24L, 24, 2, "UJPXMRCSNHGTLWIKFVBEDQOA" "NRUFVLWIPXMOJEDQHGTCSABK"},
551     {24L, 24, 2, "MIBTUAQRFGHXCDEWNOPJKLVS" "OKXVFWSCGUTNDRQJBPMALIHE"},
552     {144L, 24, 3,
553      "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
554      "BAFGHCDEMNOPIJKLTUVQRSXW"},
555     {336L, 24, 3,
556      "QTKJWONXESRIHVUMLDCPGFAB" "JNEQRHTUKLWCOPXFSAIVBMDG"
557      "HENOPJKLTUVBQRSAXFGWCDMI"},
558     /* order 25 */
559     {20L, 25, 1, "EHILMNPQRSFTUVBJWXDOYGAKC"},
560     {480L, 25, 2, "EHILMNPQRSCTUVBFWXDJYGOKA" "BDEGHIKLMNAPQRSCTUVFWXJYO"},
561     /* order 26 */
562     {156L, 26, 2,
563      "EXGZIBKDMFOHQJSLUNWPYRATCV" "BADCFEHGJILKNMPORQTSVUXWZY"},
564     {12L, 26, 1, "FEHGJILKNMPORQTSVUXWZYBADC"},
565 };
566
567 static const struct groups groups[] = {
568     {0, NULL},                  /* trivial case: 0 */
569     {0, NULL},                  /* trivial case: 1 */
570     {1, groupdata + 0},         /* 2 */
571     {1, groupdata + 1},         /* 3 */
572     {2, groupdata + 2},         /* 4 */
573     {1, groupdata + 4},         /* 5 */
574     {2, groupdata + 5},         /* 6 */
575     {1, groupdata + 7},         /* 7 */
576     {5, groupdata + 8},         /* 8 */
577     {2, groupdata + 13},        /* 9 */
578     {2, groupdata + 15},        /* 10 */
579     {1, groupdata + 17},        /* 11 */
580     {5, groupdata + 18},        /* 12 */
581     {1, groupdata + 23},        /* 13 */
582     {2, groupdata + 24},        /* 14 */
583     {1, groupdata + 26},        /* 15 */
584     {14, groupdata + 27},       /* 16 */
585     {1, groupdata + 41},        /* 17 */
586     {5, groupdata + 42},        /* 18 */
587     {1, groupdata + 47},        /* 19 */
588     {5, groupdata + 48},        /* 20 */
589     {2, groupdata + 53},        /* 21 */
590     {2, groupdata + 55},        /* 22 */
591     {1, groupdata + 57},        /* 23 */
592     {15, groupdata + 58},       /* 24 */
593     {2, groupdata + 73},        /* 25 */
594     {2, groupdata + 75},        /* 26 */
595 };
596
597 /* ----- data generated by group.gap ends ----- */
598
599 static char *new_game_desc(const game_params *params, random_state *rs,
600                            char **aux, int interactive)
601 {
602     int w = params->w, a = w*w;
603     digit *grid, *soln, *soln2;
604     int *indices;
605     int i, j, k, qh, qt;
606     int diff = params->diff;
607     const struct group *group;
608     char *desc, *p;
609
610     /*
611      * Difficulty exceptions: some combinations of size and
612      * difficulty cannot be satisfied, because all puzzles of at
613      * most that difficulty are actually even easier.
614      *
615      * Remember to re-test this whenever a change is made to the
616      * solver logic!
617      *
618      * I tested it using the following shell command:
619
620 for d in t n h x u; do
621   for id in '' i; do
622     for i in {3..9}; do
623       echo -n "./group --generate 1 ${i}d${d}${id}: "
624       perl -e 'alarm 30; exec @ARGV' \
625         ./group --generate 1 ${i}d${d}${id} >/dev/null && echo ok
626     done
627   done
628 done
629
630      * Of course, it's better to do that after taking the exceptions
631      * _out_, so as to detect exceptions that should be removed as
632      * well as those which should be added.
633      */
634     if (w < 5 && diff == DIFF_UNREASONABLE)
635         diff--;
636     if ((w < 5 || ((w == 6 || w == 8) && params->id)) && diff == DIFF_EXTREME)
637         diff--;
638     if ((w < 6 || (w == 6 && params->id)) && diff == DIFF_HARD)
639         diff--;
640     if ((w < 4 || (w == 4 && params->id)) && diff == DIFF_NORMAL)
641         diff--;
642
643     grid = snewn(a, digit);
644     soln = snewn(a, digit);
645     soln2 = snewn(a, digit);
646     indices = snewn(a, int);
647
648     while (1) {
649         /*
650          * Construct a valid group table, by picking a group from
651          * the above data table, decompressing it into a full
652          * representation by BFS, and then randomly permuting its
653          * non-identity elements.
654          *
655          * We build the canonical table in 'soln' (and use 'grid' as
656          * our BFS queue), then transfer the table into 'grid'
657          * having shuffled the rows.
658          */
659         assert(w >= 2);
660         assert(w < lenof(groups));
661         group = groups[w].groups + random_upto(rs, groups[w].ngroups);
662         assert(group->order == w);
663         memset(soln, 0, a);
664         for (i = 0; i < w; i++)
665             soln[i] = i+1;
666         qh = qt = 0;
667         grid[qt++] = 1;
668         while (qh < qt) {
669             digit *row, *newrow;
670
671             i = grid[qh++];
672             row = soln + (i-1)*w;
673
674             for (j = 0; j < group->ngens; j++) {
675                 int nri;
676                 const char *gen = group->gens + j*w;
677
678                 /*
679                  * Apply each group generator to row, constructing a
680                  * new row.
681                  */
682                 nri = gen[row[0]-1] - 'A' + 1;   /* which row is it? */
683                 newrow = soln + (nri-1)*w;
684                 if (!newrow[0]) {   /* not done yet */
685                     for (k = 0; k < w; k++)
686                         newrow[k] = gen[row[k]-1] - 'A' + 1;
687                     grid[qt++] = nri;
688                 }
689             }
690         }
691         /* That's got the canonical table. Now shuffle it. */
692         for (i = 0; i < w; i++)
693             soln2[i] = i;
694         if (params->id)                /* do we shuffle in the identity? */
695             shuffle(soln2+1, w-1, sizeof(*soln2), rs);
696         else
697             shuffle(soln2, w, sizeof(*soln2), rs);
698         for (i = 0; i < w; i++)
699             for (j = 0; j < w; j++)
700                 grid[(soln2[i])*w+(soln2[j])] = soln2[soln[i*w+j]-1]+1;
701
702         /*
703          * Remove entries one by one while the puzzle is still
704          * soluble at the appropriate difficulty level.
705          */
706         memcpy(soln, grid, a);
707         if (!params->id) {
708             /*
709              * Start by blanking the entire identity row and column,
710              * and also another row and column so that the player
711              * can't trivially determine which element is the
712              * identity.
713              */
714
715             j = 1 + random_upto(rs, w-1);  /* pick a second row/col to blank */
716             for (i = 0; i < w; i++) {
717                 grid[(soln2[0])*w+i] = grid[i*w+(soln2[0])] = 0;
718                 grid[(soln2[j])*w+i] = grid[i*w+(soln2[j])] = 0;
719             }
720
721             memcpy(soln2, grid, a);
722             if (solver(params, soln2, diff) > diff)
723                 continue;              /* go round again if that didn't work */
724         }
725
726         k = 0;
727         for (i = (params->id ? 1 : 0); i < w; i++)
728             for (j = (params->id ? 1 : 0); j < w; j++)
729                 if (grid[i*w+j])
730                     indices[k++] = i*w+j;
731         shuffle(indices, k, sizeof(*indices), rs);
732
733         for (i = 0; i < k; i++) {
734             memcpy(soln2, grid, a);
735             soln2[indices[i]] = 0;
736             if (solver(params, soln2, diff) <= diff)
737                 grid[indices[i]] = 0;
738         }
739
740         /*
741          * Make sure the puzzle isn't too easy.
742          */
743         if (diff > 0) {
744             memcpy(soln2, grid, a);
745             if (solver(params, soln2, diff-1) < diff)
746                 continue;              /* go round and try again */
747         }
748
749         /*
750          * Done.
751          */
752         break;
753     }
754
755     /*
756      * Encode the puzzle description.
757      */
758     desc = snewn(a*20, char);
759     p = encode_grid(desc, grid, a);
760     *p++ = '\0';
761     desc = sresize(desc, p - desc, char);
762
763     /*
764      * Encode the solution.
765      */
766     *aux = snewn(a+2, char);
767     (*aux)[0] = 'S';
768     for (i = 0; i < a; i++)
769         (*aux)[i+1] = TOCHAR(soln[i], params->id);
770     (*aux)[a+1] = '\0';
771
772     sfree(grid);
773     sfree(soln);
774     sfree(soln2);
775     sfree(indices);
776
777     return desc;
778 }
779
780 /* ----------------------------------------------------------------------
781  * Gameplay.
782  */
783
784 static char *validate_grid_desc(const char **pdesc, int range, int area)
785 {
786     const char *desc = *pdesc;
787     int squares = 0;
788     while (*desc && *desc != ',') {
789         int n = *desc++;
790         if (n >= 'a' && n <= 'z') {
791             squares += n - 'a' + 1;
792         } else if (n == '_') {
793             /* do nothing */;
794         } else if (n > '0' && n <= '9') {
795             int val = atoi(desc-1);
796             if (val < 1 || val > range)
797                 return "Out-of-range number in game description";
798             squares++;
799             while (*desc >= '0' && *desc <= '9')
800                 desc++;
801         } else
802             return "Invalid character in game description";
803     }
804
805     if (squares < area)
806         return "Not enough data to fill grid";
807
808     if (squares > area)
809         return "Too much data to fit in grid";
810     *pdesc = desc;
811     return NULL;
812 }
813
814 static char *validate_desc(const game_params *params, const char *desc)
815 {
816     int w = params->w, a = w*w;
817     const char *p = desc;
818
819     return validate_grid_desc(&p, w, a);
820 }
821
822 static const char *spec_to_grid(const char *desc, digit *grid, int area)
823 {
824     int i = 0;
825     while (*desc && *desc != ',') {
826         int n = *desc++;
827         if (n >= 'a' && n <= 'z') {
828             int run = n - 'a' + 1;
829             assert(i + run <= area);
830             while (run-- > 0)
831                 grid[i++] = 0;
832         } else if (n == '_') {
833             /* do nothing */;
834         } else if (n > '0' && n <= '9') {
835             assert(i < area);
836             grid[i++] = atoi(desc-1);
837             while (*desc >= '0' && *desc <= '9')
838                 desc++;
839         } else {
840             assert(!"We can't get here");
841         }
842     }
843     assert(i == area);
844     return desc;
845 }
846
847 static game_state *new_game(midend *me, const game_params *params,
848                             const char *desc)
849 {
850     int w = params->w, a = w*w;
851     game_state *state = snew(game_state);
852     int i;
853
854     state->par = *params;              /* structure copy */
855     state->grid = snewn(a, digit);
856     state->immutable = snewn(a, unsigned char);
857     state->pencil = snewn(a, int);
858     for (i = 0; i < a; i++) {
859         state->grid[i] = 0;
860         state->immutable[i] = 0;
861         state->pencil[i] = 0;
862     }
863     state->sequence = snewn(w, digit);
864     state->dividers = snewn(w, int);
865     for (i = 0; i < w; i++) {
866         state->sequence[i] = i;
867         state->dividers[i] = -1;
868     }
869
870     desc = spec_to_grid(desc, state->grid, a);
871     for (i = 0; i < a; i++)
872         if (state->grid[i] != 0)
873             state->immutable[i] = TRUE;
874
875     state->completed = state->cheated = FALSE;
876
877     return state;
878 }
879
880 static game_state *dup_game(const game_state *state)
881 {
882     int w = state->par.w, a = w*w;
883     game_state *ret = snew(game_state);
884
885     ret->par = state->par;             /* structure copy */
886
887     ret->grid = snewn(a, digit);
888     ret->immutable = snewn(a, unsigned char);
889     ret->pencil = snewn(a, int);
890     ret->sequence = snewn(w, digit);
891     ret->dividers = snewn(w, int);
892     memcpy(ret->grid, state->grid, a*sizeof(digit));
893     memcpy(ret->immutable, state->immutable, a*sizeof(unsigned char));
894     memcpy(ret->pencil, state->pencil, a*sizeof(int));
895     memcpy(ret->sequence, state->sequence, w*sizeof(digit));
896     memcpy(ret->dividers, state->dividers, w*sizeof(int));
897
898     ret->completed = state->completed;
899     ret->cheated = state->cheated;
900
901     return ret;
902 }
903
904 static void free_game(game_state *state)
905 {
906     sfree(state->grid);
907     sfree(state->immutable);
908     sfree(state->pencil);
909     sfree(state->sequence);
910     sfree(state);
911 }
912
913 static char *solve_game(const game_state *state, const game_state *currstate,
914                         const char *aux, char **error)
915 {
916     int w = state->par.w, a = w*w;
917     int i, ret;
918     digit *soln;
919     char *out;
920
921     if (aux)
922         return dupstr(aux);
923
924     soln = snewn(a, digit);
925     memcpy(soln, state->grid, a*sizeof(digit));
926
927     ret = solver(&state->par, soln, DIFFCOUNT-1);
928
929     if (ret == diff_impossible) {
930         *error = "No solution exists for this puzzle";
931         out = NULL;
932     } else if (ret == diff_ambiguous) {
933         *error = "Multiple solutions exist for this puzzle";
934         out = NULL;
935     } else {
936         out = snewn(a+2, char);
937         out[0] = 'S';
938         for (i = 0; i < a; i++)
939             out[i+1] = TOCHAR(soln[i], state->par.id);
940         out[a+1] = '\0';
941     }
942
943     sfree(soln);
944     return out;
945 }
946
947 static int game_can_format_as_text_now(const game_params *params)
948 {
949     return TRUE;
950 }
951
952 static char *game_text_format(const game_state *state)
953 {
954     int w = state->par.w;
955     int x, y;
956     char *ret, *p, ch;
957
958     ret = snewn(2*w*w+1, char);        /* leave room for terminating NUL */
959
960     p = ret;
961     for (y = 0; y < w; y++) {
962         for (x = 0; x < w; x++) {
963             digit d = state->grid[y*w+x];
964
965             if (d == 0) {
966                 ch = '.';
967             } else {
968                 ch = TOCHAR(d, state->par.id);
969             }
970
971             *p++ = ch;
972             if (x == w-1) {
973                 *p++ = '\n';
974             } else {
975                 *p++ = ' ';
976             }
977         }
978     }
979
980     assert(p - ret == 2*w*w);
981     *p = '\0';
982     return ret;
983 }
984
985 struct game_ui {
986     /*
987      * These are the coordinates of the currently highlighted
988      * square on the grid, if hshow = 1.
989      */
990     int hx, hy;
991     /*
992      * This indicates whether the current highlight is a
993      * pencil-mark one or a real one.
994      */
995     int hpencil;
996     /*
997      * This indicates whether or not we're showing the highlight
998      * (used to be hx = hy = -1); important so that when we're
999      * using the cursor keys it doesn't keep coming back at a
1000      * fixed position. When hshow = 1, pressing a valid number
1001      * or letter key or Space will enter that number or letter in the grid.
1002      */
1003     int hshow;
1004     /*
1005      * This indicates whether we're using the highlight as a cursor;
1006      * it means that it doesn't vanish on a keypress, and that it is
1007      * allowed on immutable squares.
1008      */
1009     int hcursor;
1010     /*
1011      * This indicates whether we're dragging a table header to
1012      * reposition an entire row or column.
1013      */
1014     int drag;                          /* 0=none 1=row 2=col */
1015     int dragnum;                       /* element being dragged */
1016     int dragpos;                       /* its current position */
1017     int edgepos;
1018 };
1019
1020 static game_ui *new_ui(const game_state *state)
1021 {
1022     game_ui *ui = snew(game_ui);
1023
1024     ui->hx = ui->hy = 0;
1025     ui->hpencil = ui->hshow = ui->hcursor = 0;
1026     ui->drag = 0;
1027
1028     return ui;
1029 }
1030
1031 static void free_ui(game_ui *ui)
1032 {
1033     sfree(ui);
1034 }
1035
1036 static char *encode_ui(const game_ui *ui)
1037 {
1038     return NULL;
1039 }
1040
1041 static void decode_ui(game_ui *ui, const char *encoding)
1042 {
1043 }
1044
1045 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1046                                const game_state *newstate)
1047 {
1048     int w = newstate->par.w;
1049     /*
1050      * We prevent pencil-mode highlighting of a filled square, unless
1051      * we're using the cursor keys. So if the user has just filled in
1052      * a square which we had a pencil-mode highlight in (by Undo, or
1053      * by Redo, or by Solve), then we cancel the highlight.
1054      */
1055     if (ui->hshow && ui->hpencil && !ui->hcursor &&
1056         newstate->grid[ui->hy * w + ui->hx] != 0) {
1057         ui->hshow = 0;
1058     }
1059 }
1060
1061 #define PREFERRED_TILESIZE 48
1062 #define TILESIZE (ds->tilesize)
1063 #define BORDER (TILESIZE / 2)
1064 #define LEGEND (TILESIZE)
1065 #define GRIDEXTRA max((TILESIZE / 32),1)
1066 #define COORD(x) ((x)*TILESIZE + BORDER + LEGEND)
1067 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER-LEGEND)) / TILESIZE - 1)
1068
1069 #define FLASH_TIME 0.4F
1070
1071 #define DF_DIVIDER_TOP 0x1000
1072 #define DF_DIVIDER_BOT 0x2000
1073 #define DF_DIVIDER_LEFT 0x4000
1074 #define DF_DIVIDER_RIGHT 0x8000
1075 #define DF_HIGHLIGHT 0x0400
1076 #define DF_HIGHLIGHT_PENCIL 0x0200
1077 #define DF_IMMUTABLE 0x0100
1078 #define DF_LEGEND 0x0080
1079 #define DF_DIGIT_MASK 0x001F
1080
1081 #define EF_DIGIT_SHIFT 5
1082 #define EF_DIGIT_MASK ((1 << EF_DIGIT_SHIFT) - 1)
1083 #define EF_LEFT_SHIFT 0
1084 #define EF_RIGHT_SHIFT (3*EF_DIGIT_SHIFT)
1085 #define EF_LEFT_MASK ((1UL << (3*EF_DIGIT_SHIFT)) - 1UL)
1086 #define EF_RIGHT_MASK (EF_LEFT_MASK << EF_RIGHT_SHIFT)
1087 #define EF_LATIN (1UL << (6*EF_DIGIT_SHIFT))
1088
1089 struct game_drawstate {
1090     game_params par;
1091     int w, tilesize;
1092     int started;
1093     long *tiles, *legend, *pencil, *errors;
1094     long *errtmp;
1095     digit *sequence;
1096 };
1097
1098 static int check_errors(const game_state *state, long *errors)
1099 {
1100     int w = state->par.w, a = w*w;
1101     digit *grid = state->grid;
1102     int i, j, k, x, y, errs = FALSE;
1103
1104     /*
1105      * To verify that we have a valid group table, it suffices to
1106      * test latin-square-hood and associativity only. All the other
1107      * group axioms follow from those two.
1108      *
1109      * Proof:
1110      *
1111      * Associativity is given; closure is obvious from latin-
1112      * square-hood. We need to show that an identity exists and that
1113      * every element has an inverse.
1114      *
1115      * Identity: take any element a. There will be some element e
1116      * such that ea=a (in a latin square, every element occurs in
1117      * every row and column, so a must occur somewhere in the a
1118      * column, say on row e). For any other element b, there must
1119      * exist x such that ax=b (same argument from latin-square-hood
1120      * again), and then associativity gives us eb = e(ax) = (ea)x =
1121      * ax = b. Hence eb=b for all b, i.e. e is a left-identity. A
1122      * similar argument tells us that there must be some f which is
1123      * a right-identity, and then we show they are the same element
1124      * by observing that ef must simultaneously equal e and equal f.
1125      *
1126      * Inverses: given any a, by the latin-square argument again,
1127      * there must exist p and q such that pa=e and aq=e (i.e. left-
1128      * and right-inverses). We can show these are equal by
1129      * associativity: p = pe = p(aq) = (pa)q = eq = q. []
1130      */
1131
1132     if (errors)
1133         for (i = 0; i < a; i++)
1134             errors[i] = 0;
1135
1136     for (y = 0; y < w; y++) {
1137         unsigned long mask = 0, errmask = 0;
1138         for (x = 0; x < w; x++) {
1139             unsigned long bit = 1UL << grid[y*w+x];
1140             errmask |= (mask & bit);
1141             mask |= bit;
1142         }
1143
1144         if (mask != (1 << (w+1)) - (1 << 1)) {
1145             errs = TRUE;
1146             errmask &= ~1UL;
1147             if (errors) {
1148                 for (x = 0; x < w; x++)
1149                     if (errmask & (1UL << grid[y*w+x]))
1150                         errors[y*w+x] |= EF_LATIN;
1151             }
1152         }
1153     }
1154
1155     for (x = 0; x < w; x++) {
1156         unsigned long mask = 0, errmask = 0;
1157         for (y = 0; y < w; y++) {
1158             unsigned long bit = 1UL << grid[y*w+x];
1159             errmask |= (mask & bit);
1160             mask |= bit;
1161         }
1162
1163         if (mask != (1 << (w+1)) - (1 << 1)) {
1164             errs = TRUE;
1165             errmask &= ~1UL;
1166             if (errors) {
1167                 for (y = 0; y < w; y++)
1168                     if (errmask & (1UL << grid[y*w+x]))
1169                         errors[y*w+x] |= EF_LATIN;
1170             }
1171         }
1172     }
1173
1174     for (i = 1; i < w; i++)
1175         for (j = 1; j < w; j++)
1176             for (k = 1; k < w; k++)
1177                 if (grid[i*w+j] && grid[j*w+k] &&
1178                     grid[(grid[i*w+j]-1)*w+k] &&
1179                     grid[i*w+(grid[j*w+k]-1)] &&
1180                     grid[(grid[i*w+j]-1)*w+k] != grid[i*w+(grid[j*w+k]-1)]) {
1181                     if (errors) {
1182                         int a = i+1, b = j+1, c = k+1;
1183                         int ab = grid[i*w+j], bc = grid[j*w+k];
1184                         int left = (ab-1)*w+(c-1), right = (a-1)*w+(bc-1);
1185                         /*
1186                          * If the appropriate error slot is already
1187                          * used for one of the squares, we don't
1188                          * fill either of them.
1189                          */
1190                         if (!(errors[left] & EF_LEFT_MASK) &&
1191                             !(errors[right] & EF_RIGHT_MASK)) {
1192                             long err;
1193                             err = a;
1194                             err = (err << EF_DIGIT_SHIFT) | b;
1195                             err = (err << EF_DIGIT_SHIFT) | c;
1196                             errors[left] |= err << EF_LEFT_SHIFT;
1197                             errors[right] |= err << EF_RIGHT_SHIFT;
1198                         }
1199                     }
1200                     errs = TRUE;
1201                 }
1202
1203     return errs;
1204 }
1205
1206 static int find_in_sequence(digit *seq, int len, digit n)
1207 {
1208     int i;
1209
1210     for (i = 0; i < len; i++)
1211         if (seq[i] == n)
1212             return i;
1213
1214     assert(!"Should never get here");
1215     return -1;
1216 }
1217
1218 static char *interpret_move(const game_state *state, game_ui *ui,
1219                             const game_drawstate *ds,
1220                             int x, int y, int button)
1221 {
1222     int w = state->par.w;
1223     int tx, ty;
1224     char buf[80];
1225
1226     button &= ~MOD_MASK;
1227
1228     tx = FROMCOORD(x);
1229     ty = FROMCOORD(y);
1230
1231     if (ui->drag) {
1232         if (IS_MOUSE_DRAG(button)) {
1233             int tcoord = ((ui->drag &~ 4) == 1 ? ty : tx);
1234             ui->drag |= 4;             /* some movement has happened */
1235             if (tcoord >= 0 && tcoord < w) {
1236                 ui->dragpos = tcoord;
1237                 return "";
1238             }
1239         } else if (IS_MOUSE_RELEASE(button)) {
1240             if (ui->drag & 4) {
1241                 ui->drag = 0;          /* end drag */
1242                 if (state->sequence[ui->dragpos] == ui->dragnum)
1243                     return "";         /* drag was a no-op overall */
1244                 sprintf(buf, "D%d,%d", ui->dragnum, ui->dragpos);
1245                 return dupstr(buf);
1246             } else {
1247                 ui->drag = 0;          /* end 'drag' */
1248                 if (ui->edgepos > 0 && ui->edgepos < w) {
1249                     sprintf(buf, "V%d,%d",
1250                             state->sequence[ui->edgepos-1],
1251                             state->sequence[ui->edgepos]);
1252                     return dupstr(buf);
1253                 } else
1254                     return "";         /* no-op */
1255             }
1256         }
1257     } else if (IS_MOUSE_DOWN(button)) {
1258         if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1259             tx = state->sequence[tx];
1260             ty = state->sequence[ty];
1261             if (button == LEFT_BUTTON) {
1262                 if (tx == ui->hx && ty == ui->hy &&
1263                     ui->hshow && ui->hpencil == 0) {
1264                     ui->hshow = 0;
1265                 } else {
1266                     ui->hx = tx;
1267                     ui->hy = ty;
1268                     ui->hshow = !state->immutable[ty*w+tx];
1269                     ui->hpencil = 0;
1270                 }
1271                 ui->hcursor = 0;
1272                 return "";                     /* UI activity occurred */
1273             }
1274             if (button == RIGHT_BUTTON) {
1275                 /*
1276                  * Pencil-mode highlighting for non filled squares.
1277                  */
1278                 if (state->grid[ty*w+tx] == 0) {
1279                     if (tx == ui->hx && ty == ui->hy &&
1280                         ui->hshow && ui->hpencil) {
1281                         ui->hshow = 0;
1282                     } else {
1283                         ui->hpencil = 1;
1284                         ui->hx = tx;
1285                         ui->hy = ty;
1286                         ui->hshow = 1;
1287                     }
1288                 } else {
1289                     ui->hshow = 0;
1290                 }
1291                 ui->hcursor = 0;
1292                 return "";                     /* UI activity occurred */
1293             }
1294         } else if (tx >= 0 && tx < w && ty == -1) {
1295             ui->drag = 2;
1296             ui->dragnum = state->sequence[tx];
1297             ui->dragpos = tx;
1298             ui->edgepos = FROMCOORD(x + TILESIZE/2);
1299             return "";
1300         } else if (ty >= 0 && ty < w && tx == -1) {
1301             ui->drag = 1;
1302             ui->dragnum = state->sequence[ty];
1303             ui->dragpos = ty;
1304             ui->edgepos = FROMCOORD(y + TILESIZE/2);
1305             return "";
1306         }
1307     }
1308
1309     if (IS_CURSOR_MOVE(button)) {
1310         int cx = find_in_sequence(state->sequence, w, ui->hx);
1311         int cy = find_in_sequence(state->sequence, w, ui->hy);
1312         move_cursor(button, &cx, &cy, w, w, 0);
1313         ui->hx = state->sequence[cx];
1314         ui->hy = state->sequence[cy];
1315         ui->hshow = ui->hcursor = 1;
1316         return "";
1317     }
1318     if (ui->hshow &&
1319         (button == CURSOR_SELECT)) {
1320         ui->hpencil = 1 - ui->hpencil;
1321         ui->hcursor = 1;
1322         return "";
1323     }
1324
1325     if (ui->hshow &&
1326         ((ISCHAR(button) && FROMCHAR(button, state->par.id) <= w) ||
1327          button == CURSOR_SELECT2 || button == '\b')) {
1328         int n = FROMCHAR(button, state->par.id);
1329         if (button == CURSOR_SELECT2 || button == '\b')
1330             n = 0;
1331
1332         /*
1333          * Can't make pencil marks in a filled square. This can only
1334          * become highlighted if we're using cursor keys.
1335          */
1336         if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1337             return NULL;
1338
1339         /*
1340          * Can't do anything to an immutable square.
1341          */
1342         if (state->immutable[ui->hy*w+ui->hx])
1343             return NULL;
1344
1345         sprintf(buf, "%c%d,%d,%d",
1346                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1347
1348         if (!ui->hcursor) ui->hshow = 0;
1349
1350         return dupstr(buf);
1351     }
1352
1353     if (button == 'M' || button == 'm')
1354         return dupstr("M");
1355
1356     return NULL;
1357 }
1358
1359 static game_state *execute_move(const game_state *from, const char *move)
1360 {
1361     int w = from->par.w, a = w*w;
1362     game_state *ret;
1363     int x, y, i, j, n;
1364
1365     if (move[0] == 'S') {
1366         ret = dup_game(from);
1367         ret->completed = ret->cheated = TRUE;
1368
1369         for (i = 0; i < a; i++) {
1370             if (!ISCHAR(move[i+1]) || FROMCHAR(move[i+1], from->par.id) > w) {
1371                 free_game(ret);
1372                 return NULL;
1373             }
1374             ret->grid[i] = FROMCHAR(move[i+1], from->par.id);
1375             ret->pencil[i] = 0;
1376         }
1377
1378         if (move[a+1] != '\0') {
1379             free_game(ret);
1380             return NULL;
1381         }
1382
1383         return ret;
1384     } else if ((move[0] == 'P' || move[0] == 'R') &&
1385         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1386         x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1387         if (from->immutable[y*w+x])
1388             return NULL;
1389
1390         ret = dup_game(from);
1391         if (move[0] == 'P' && n > 0) {
1392             ret->pencil[y*w+x] ^= 1 << n;
1393         } else {
1394             ret->grid[y*w+x] = n;
1395             ret->pencil[y*w+x] = 0;
1396
1397             if (!ret->completed && !check_errors(ret, NULL))
1398                 ret->completed = TRUE;
1399         }
1400         return ret;
1401     } else if (move[0] == 'M') {
1402         /*
1403          * Fill in absolutely all pencil marks everywhere. (I
1404          * wouldn't use this for actual play, but it's a handy
1405          * starting point when following through a set of
1406          * diagnostics output by the standalone solver.)
1407          */
1408         ret = dup_game(from);
1409         for (i = 0; i < a; i++) {
1410             if (!ret->grid[i])
1411                 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1412         }
1413         return ret;
1414     } else if (move[0] == 'D' &&
1415                sscanf(move+1, "%d,%d", &x, &y) == 2) {
1416         /*
1417          * Reorder the rows and columns so that digit x is in position
1418          * y.
1419          */
1420         ret = dup_game(from);
1421         for (i = j = 0; i < w; i++) {
1422             if (i == y) {
1423                 ret->sequence[i] = x;
1424             } else {
1425                 if (from->sequence[j] == x)
1426                     j++;
1427                 ret->sequence[i] = from->sequence[j++];
1428             }
1429         }
1430         /*
1431          * Eliminate any obsoleted dividers.
1432          */
1433         for (x = 0; x+1 < w; x++) {
1434             int i = ret->sequence[x], j = ret->sequence[x+1];
1435             if (ret->dividers[i] != j)
1436                 ret->dividers[i] = -1;
1437         }
1438         return ret;
1439     } else if (move[0] == 'V' &&
1440                sscanf(move+1, "%d,%d", &i, &j) == 2) {
1441         ret = dup_game(from);
1442         if (ret->dividers[i] == j)
1443             ret->dividers[i] = -1;
1444         else
1445             ret->dividers[i] = j;
1446         return ret;
1447     } else
1448         return NULL;                   /* couldn't parse move string */
1449 }
1450
1451 /* ----------------------------------------------------------------------
1452  * Drawing routines.
1453  */
1454
1455 #define SIZE(w) ((w) * TILESIZE + 2*BORDER + LEGEND)
1456
1457 static void game_compute_size(const game_params *params, int tilesize,
1458                               int *x, int *y)
1459 {
1460     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1461     struct { int tilesize; } ads, *ds = &ads;
1462     ads.tilesize = tilesize;
1463
1464     *x = *y = SIZE(params->w);
1465 }
1466
1467 static void game_set_size(drawing *dr, game_drawstate *ds,
1468                           const game_params *params, int tilesize)
1469 {
1470     ds->tilesize = tilesize;
1471 }
1472
1473 static float *game_colours(frontend *fe, int *ncolours)
1474 {
1475     float *ret = snewn(3 * NCOLOURS, float);
1476
1477     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1478
1479     ret[COL_GRID * 3 + 0] = 0.0F;
1480     ret[COL_GRID * 3 + 1] = 0.0F;
1481     ret[COL_GRID * 3 + 2] = 0.0F;
1482
1483     ret[COL_USER * 3 + 0] = 0.0F;
1484     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1485     ret[COL_USER * 3 + 2] = 0.0F;
1486
1487     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1488     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1489     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1490
1491     ret[COL_ERROR * 3 + 0] = 1.0F;
1492     ret[COL_ERROR * 3 + 1] = 0.0F;
1493     ret[COL_ERROR * 3 + 2] = 0.0F;
1494
1495     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1496     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1497     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1498
1499     ret[COL_DIAGONAL * 3 + 0] = 0.95F * ret[COL_BACKGROUND * 3 + 0];
1500     ret[COL_DIAGONAL * 3 + 1] = 0.95F * ret[COL_BACKGROUND * 3 + 1];
1501     ret[COL_DIAGONAL * 3 + 2] = 0.95F * ret[COL_BACKGROUND * 3 + 2];
1502
1503     *ncolours = NCOLOURS;
1504     return ret;
1505 }
1506
1507 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1508 {
1509     int w = state->par.w, a = w*w;
1510     struct game_drawstate *ds = snew(struct game_drawstate);
1511     int i;
1512
1513     ds->w = w;
1514     ds->par = state->par;              /* structure copy */
1515     ds->tilesize = 0;
1516     ds->started = FALSE;
1517     ds->tiles = snewn(a, long);
1518     ds->legend = snewn(w, long);
1519     ds->pencil = snewn(a, long);
1520     ds->errors = snewn(a, long);
1521     ds->sequence = snewn(a, digit);
1522     for (i = 0; i < a; i++)
1523         ds->tiles[i] = ds->pencil[i] = -1;
1524     for (i = 0; i < w; i++)
1525         ds->legend[i] = -1;
1526     ds->errtmp = snewn(a, long);
1527
1528     return ds;
1529 }
1530
1531 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1532 {
1533     sfree(ds->tiles);
1534     sfree(ds->pencil);
1535     sfree(ds->errors);
1536     sfree(ds->errtmp);
1537     sfree(ds->sequence);
1538     sfree(ds);
1539 }
1540
1541 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, long tile,
1542                       long pencil, long error)
1543 {
1544     int w = ds->w /* , a = w*w */;
1545     int tx, ty, tw, th;
1546     int cx, cy, cw, ch;
1547     char str[64];
1548
1549     tx = BORDER + LEGEND + x * TILESIZE + 1;
1550     ty = BORDER + LEGEND + y * TILESIZE + 1;
1551
1552     cx = tx;
1553     cy = ty;
1554     cw = tw = TILESIZE-1;
1555     ch = th = TILESIZE-1;
1556
1557     if (tile & DF_LEGEND) {
1558         cx += TILESIZE/10;
1559         cy += TILESIZE/10;
1560         cw -= TILESIZE/5;
1561         ch -= TILESIZE/5;
1562         tile |= DF_IMMUTABLE;
1563     }
1564
1565     clip(dr, cx, cy, cw, ch);
1566
1567     /* background needs erasing */
1568     draw_rect(dr, cx, cy, cw, ch,
1569               (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT :
1570               (x == y) ? COL_DIAGONAL : COL_BACKGROUND);
1571
1572     /* dividers */
1573     if (tile & DF_DIVIDER_TOP)
1574         draw_rect(dr, cx, cy, cw, 1, COL_GRID);
1575     if (tile & DF_DIVIDER_BOT)
1576         draw_rect(dr, cx, cy+ch-1, cw, 1, COL_GRID);
1577     if (tile & DF_DIVIDER_LEFT)
1578         draw_rect(dr, cx, cy, 1, ch, COL_GRID);
1579     if (tile & DF_DIVIDER_RIGHT)
1580         draw_rect(dr, cx+cw-1, cy, 1, ch, COL_GRID);
1581
1582     /* pencil-mode highlight */
1583     if (tile & DF_HIGHLIGHT_PENCIL) {
1584         int coords[6];
1585         coords[0] = cx;
1586         coords[1] = cy;
1587         coords[2] = cx+cw/2;
1588         coords[3] = cy;
1589         coords[4] = cx;
1590         coords[5] = cy+ch/2;
1591         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1592     }
1593
1594     /* new number needs drawing? */
1595     if (tile & DF_DIGIT_MASK) {
1596         str[1] = '\0';
1597         str[0] = TOCHAR(tile & DF_DIGIT_MASK, ds->par.id);
1598         draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1599                   FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1600                   (error & EF_LATIN) ? COL_ERROR :
1601                   (tile & DF_IMMUTABLE) ? COL_GRID : COL_USER, str);
1602
1603         if (error & EF_LEFT_MASK) {
1604             int a = (error >> (EF_LEFT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1605             int b = (error >> (EF_LEFT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1606             int c = (error >> (EF_LEFT_SHIFT                 ))&EF_DIGIT_MASK;
1607             char buf[10];
1608             sprintf(buf, "(%c%c)%c", TOCHAR(a, ds->par.id),
1609                     TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1610             draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/6,
1611                       FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1612                       COL_ERROR, buf);
1613         }
1614         if (error & EF_RIGHT_MASK) {
1615             int a = (error >> (EF_RIGHT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1616             int b = (error >> (EF_RIGHT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1617             int c = (error >> (EF_RIGHT_SHIFT                 ))&EF_DIGIT_MASK;
1618             char buf[10];
1619             sprintf(buf, "%c(%c%c)", TOCHAR(a, ds->par.id),
1620                     TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1621             draw_text(dr, tx + TILESIZE/2, ty + TILESIZE - TILESIZE/6,
1622                       FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1623                       COL_ERROR, buf);
1624         }
1625     } else {
1626         int i, j, npencil;
1627         int pl, pr, pt, pb;
1628         float bestsize;
1629         int pw, ph, minph, pbest, fontsize;
1630
1631         /* Count the pencil marks required. */
1632         for (i = 1, npencil = 0; i <= w; i++)
1633             if (pencil & (1 << i))
1634                 npencil++;
1635         if (npencil) {
1636
1637             minph = 2;
1638
1639             /*
1640              * Determine the bounding rectangle within which we're going
1641              * to put the pencil marks.
1642              */
1643             /* Start with the whole square */
1644             pl = tx + GRIDEXTRA;
1645             pr = pl + TILESIZE - GRIDEXTRA;
1646             pt = ty + GRIDEXTRA;
1647             pb = pt + TILESIZE - GRIDEXTRA;
1648
1649             /*
1650              * We arrange our pencil marks in a grid layout, with
1651              * the number of rows and columns adjusted to allow the
1652              * maximum font size.
1653              *
1654              * So now we work out what the grid size ought to be.
1655              */
1656             bestsize = 0.0;
1657             pbest = 0;
1658             /* Minimum */
1659             for (pw = 3; pw < max(npencil,4); pw++) {
1660                 float fw, fh, fs;
1661
1662                 ph = (npencil + pw - 1) / pw;
1663                 ph = max(ph, minph);
1664                 fw = (pr - pl) / (float)pw;
1665                 fh = (pb - pt) / (float)ph;
1666                 fs = min(fw, fh);
1667                 if (fs > bestsize) {
1668                     bestsize = fs;
1669                     pbest = pw;
1670                 }
1671             }
1672             assert(pbest > 0);
1673             pw = pbest;
1674             ph = (npencil + pw - 1) / pw;
1675             ph = max(ph, minph);
1676
1677             /*
1678              * Now we've got our grid dimensions, work out the pixel
1679              * size of a grid element, and round it to the nearest
1680              * pixel. (We don't want rounding errors to make the
1681              * grid look uneven at low pixel sizes.)
1682              */
1683             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1684
1685             /*
1686              * Centre the resulting figure in the square.
1687              */
1688             pl = tx + (TILESIZE - fontsize * pw) / 2;
1689             pt = ty + (TILESIZE - fontsize * ph) / 2;
1690
1691             /*
1692              * Now actually draw the pencil marks.
1693              */
1694             for (i = 1, j = 0; i <= w; i++)
1695                 if (pencil & (1 << i)) {
1696                     int dx = j % pw, dy = j / pw;
1697
1698                     str[1] = '\0';
1699                     str[0] = TOCHAR(i, ds->par.id);
1700                     draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1701                               pt + fontsize * (2*dy+1) / 2,
1702                               FONT_VARIABLE, fontsize,
1703                               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1704                     j++;
1705                 }
1706         }
1707     }
1708
1709     unclip(dr);
1710
1711     draw_update(dr, cx, cy, cw, ch);
1712 }
1713
1714 static void game_redraw(drawing *dr, game_drawstate *ds,
1715                         const game_state *oldstate, const game_state *state,
1716                         int dir, const game_ui *ui,
1717                         float animtime, float flashtime)
1718 {
1719     int w = state->par.w /*, a = w*w */;
1720     int x, y, i, j;
1721
1722     if (!ds->started) {
1723         /*
1724          * The initial contents of the window are not guaranteed and
1725          * can vary with front ends. To be on the safe side, all
1726          * games should start by drawing a big background-colour
1727          * rectangle covering the whole window.
1728          */
1729         draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1730
1731         /*
1732          * Big containing rectangle.
1733          */
1734         draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1735                   w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1736                   COL_GRID);
1737
1738         draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1739
1740         ds->started = TRUE;
1741     }
1742
1743     check_errors(state, ds->errtmp);
1744
1745     /*
1746      * Construct a modified version of state->sequence which takes
1747      * into account an unfinished drag operation.
1748      */
1749     if (ui->drag) {
1750         x = ui->dragnum;
1751         y = ui->dragpos;
1752     } else {
1753         x = y = -1;
1754     }
1755     for (i = j = 0; i < w; i++) {
1756         if (i == y) {
1757             ds->sequence[i] = x;
1758         } else {
1759             if (state->sequence[j] == x)
1760                 j++;
1761             ds->sequence[i] = state->sequence[j++];
1762         }
1763     }
1764
1765     /*
1766      * Draw the table legend.
1767      */
1768     for (x = 0; x < w; x++) {
1769         int sx = ds->sequence[x];
1770         long tile = (sx+1) | DF_LEGEND;
1771         if (ds->legend[x] != tile) {
1772             ds->legend[x] = tile;
1773             draw_tile(dr, ds, -1, x, tile, 0, 0);
1774             draw_tile(dr, ds, x, -1, tile, 0, 0);
1775         }
1776     }
1777
1778     for (y = 0; y < w; y++) {
1779         int sy = ds->sequence[y];
1780         for (x = 0; x < w; x++) {
1781             long tile = 0L, pencil = 0L, error;
1782             int sx = ds->sequence[x];
1783
1784             if (state->grid[sy*w+sx])
1785                 tile = state->grid[sy*w+sx];
1786             else
1787                 pencil = (long)state->pencil[sy*w+sx];
1788
1789             if (state->immutable[sy*w+sx])
1790                 tile |= DF_IMMUTABLE;
1791
1792             if ((ui->drag == 5 && ui->dragnum == sy) ||
1793                 (ui->drag == 6 && ui->dragnum == sx))
1794                 tile |= DF_HIGHLIGHT;
1795             else if (ui->hshow && ui->hx == sx && ui->hy == sy)
1796                 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
1797
1798             if (flashtime > 0 &&
1799                 (flashtime <= FLASH_TIME/3 ||
1800                  flashtime >= FLASH_TIME*2/3))
1801                 tile |= DF_HIGHLIGHT;  /* completion flash */
1802
1803             if (y <= 0 || state->dividers[ds->sequence[y-1]] == sy)
1804                 tile |= DF_DIVIDER_TOP;
1805             if (y+1 >= w || state->dividers[sy] == ds->sequence[y+1])
1806                 tile |= DF_DIVIDER_BOT;
1807             if (x <= 0 || state->dividers[ds->sequence[x-1]] == sx)
1808                 tile |= DF_DIVIDER_LEFT;
1809             if (x+1 >= w || state->dividers[sx] == ds->sequence[x+1])
1810                 tile |= DF_DIVIDER_RIGHT;
1811
1812             error = ds->errtmp[sy*w+sx];
1813
1814             if (ds->tiles[y*w+x] != tile ||
1815                 ds->pencil[y*w+x] != pencil ||
1816                 ds->errors[y*w+x] != error) {
1817                 ds->tiles[y*w+x] = tile;
1818                 ds->pencil[y*w+x] = pencil;
1819                 ds->errors[y*w+x] = error;
1820                 draw_tile(dr, ds, x, y, tile, pencil, error);
1821             }
1822         }
1823     }
1824 }
1825
1826 static float game_anim_length(const game_state *oldstate,
1827                               const game_state *newstate, int dir, game_ui *ui)
1828 {
1829     return 0.0F;
1830 }
1831
1832 static float game_flash_length(const game_state *oldstate,
1833                                const game_state *newstate, int dir, game_ui *ui)
1834 {
1835     if (!oldstate->completed && newstate->completed &&
1836         !oldstate->cheated && !newstate->cheated)
1837         return FLASH_TIME;
1838     return 0.0F;
1839 }
1840
1841 static int game_status(const game_state *state)
1842 {
1843     return state->completed ? +1 : 0;
1844 }
1845
1846 static int game_timing_state(const game_state *state, game_ui *ui)
1847 {
1848     if (state->completed)
1849         return FALSE;
1850     return TRUE;
1851 }
1852
1853 static void game_print_size(const game_params *params, float *x, float *y)
1854 {
1855     int pw, ph;
1856
1857     /*
1858      * We use 9mm squares by default, like Solo.
1859      */
1860     game_compute_size(params, 900, &pw, &ph);
1861     *x = pw / 100.0F;
1862     *y = ph / 100.0F;
1863 }
1864
1865 static void game_print(drawing *dr, const game_state *state, int tilesize)
1866 {
1867     int w = state->par.w;
1868     int ink = print_mono_colour(dr, 0);
1869     int x, y;
1870
1871     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1872     game_drawstate ads, *ds = &ads;
1873     game_set_size(dr, ds, NULL, tilesize);
1874
1875     /*
1876      * Border.
1877      */
1878     print_line_width(dr, 3 * TILESIZE / 40);
1879     draw_rect_outline(dr, BORDER + LEGEND, BORDER + LEGEND,
1880                       w*TILESIZE, w*TILESIZE, ink);
1881
1882     /*
1883      * Legend on table.
1884      */
1885     for (x = 0; x < w; x++) {
1886         char str[2];
1887         str[1] = '\0';
1888         str[0] = TOCHAR(x+1, state->par.id);
1889         draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1890                   BORDER + TILESIZE/2,
1891                   FONT_VARIABLE, TILESIZE/2,
1892                   ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1893         draw_text(dr, BORDER + TILESIZE/2,
1894                   BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1895                   FONT_VARIABLE, TILESIZE/2,
1896                   ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1897     }
1898
1899     /*
1900      * Main grid.
1901      */
1902     for (x = 1; x < w; x++) {
1903         print_line_width(dr, TILESIZE / 40);
1904         draw_line(dr, BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND,
1905                   BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND+w*TILESIZE, ink);
1906     }
1907     for (y = 1; y < w; y++) {
1908         print_line_width(dr, TILESIZE / 40);
1909         draw_line(dr, BORDER+LEGEND, BORDER+LEGEND+y*TILESIZE,
1910                   BORDER+LEGEND+w*TILESIZE, BORDER+LEGEND+y*TILESIZE, ink);
1911     }
1912
1913     /*
1914      * Numbers.
1915      */
1916     for (y = 0; y < w; y++)
1917         for (x = 0; x < w; x++)
1918             if (state->grid[y*w+x]) {
1919                 char str[2];
1920                 str[1] = '\0';
1921                 str[0] = TOCHAR(state->grid[y*w+x], state->par.id);
1922                 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1923                           BORDER+LEGEND + y*TILESIZE + TILESIZE/2,
1924                           FONT_VARIABLE, TILESIZE/2,
1925                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1926             }
1927 }
1928
1929 #ifdef COMBINED
1930 #define thegame group
1931 #endif
1932
1933 const struct game thegame = {
1934     "Group", NULL, NULL,
1935     default_params,
1936     game_fetch_preset,
1937     decode_params,
1938     encode_params,
1939     free_params,
1940     dup_params,
1941     TRUE, game_configure, custom_params,
1942     validate_params,
1943     new_game_desc,
1944     validate_desc,
1945     new_game,
1946     dup_game,
1947     free_game,
1948     TRUE, solve_game,
1949     TRUE, game_can_format_as_text_now, game_text_format,
1950     new_ui,
1951     free_ui,
1952     encode_ui,
1953     decode_ui,
1954     game_changed_state,
1955     interpret_move,
1956     execute_move,
1957     PREFERRED_TILESIZE, game_compute_size, game_set_size,
1958     game_colours,
1959     game_new_drawstate,
1960     game_free_drawstate,
1961     game_redraw,
1962     game_anim_length,
1963     game_flash_length,
1964     game_status,
1965     TRUE, FALSE, game_print_size, game_print,
1966     FALSE,                             /* wants_statusbar */
1967     FALSE, game_timing_state,
1968     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
1969 };
1970
1971 #ifdef STANDALONE_SOLVER
1972
1973 #include <stdarg.h>
1974
1975 int main(int argc, char **argv)
1976 {
1977     game_params *p;
1978     game_state *s;
1979     char *id = NULL, *desc, *err;
1980     digit *grid;
1981     int grade = FALSE;
1982     int ret, diff, really_show_working = FALSE;
1983
1984     while (--argc > 0) {
1985         char *p = *++argv;
1986         if (!strcmp(p, "-v")) {
1987             really_show_working = TRUE;
1988         } else if (!strcmp(p, "-g")) {
1989             grade = TRUE;
1990         } else if (*p == '-') {
1991             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1992             return 1;
1993         } else {
1994             id = p;
1995         }
1996     }
1997
1998     if (!id) {
1999         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2000         return 1;
2001     }
2002
2003     desc = strchr(id, ':');
2004     if (!desc) {
2005         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2006         return 1;
2007     }
2008     *desc++ = '\0';
2009
2010     p = default_params();
2011     decode_params(p, id);
2012     err = validate_desc(p, desc);
2013     if (err) {
2014         fprintf(stderr, "%s: %s\n", argv[0], err);
2015         return 1;
2016     }
2017     s = new_game(NULL, p, desc);
2018
2019     grid = snewn(p->w * p->w, digit);
2020
2021     /*
2022      * When solving a Normal puzzle, we don't want to bother the
2023      * user with Hard-level deductions. For this reason, we grade
2024      * the puzzle internally before doing anything else.
2025      */
2026     ret = -1;                          /* placate optimiser */
2027     solver_show_working = FALSE;
2028     for (diff = 0; diff < DIFFCOUNT; diff++) {
2029         memcpy(grid, s->grid, p->w * p->w);
2030         ret = solver(&s->par, grid, diff);
2031         if (ret <= diff)
2032             break;
2033     }
2034
2035     if (diff == DIFFCOUNT) {
2036         if (grade)
2037             printf("Difficulty rating: ambiguous\n");
2038         else
2039             printf("Unable to find a unique solution\n");
2040     } else {
2041         if (grade) {
2042             if (ret == diff_impossible)
2043                 printf("Difficulty rating: impossible (no solution exists)\n");
2044             else
2045                 printf("Difficulty rating: %s\n", group_diffnames[ret]);
2046         } else {
2047             solver_show_working = really_show_working;
2048             memcpy(grid, s->grid, p->w * p->w);
2049             ret = solver(&s->par, grid, diff);
2050             if (ret != diff)
2051                 printf("Puzzle is inconsistent\n");
2052             else {
2053                 memcpy(s->grid, grid, p->w * p->w);
2054                 fputs(game_text_format(s), stdout);
2055             }
2056         }
2057     }
2058
2059     return 0;
2060 }
2061
2062 #endif
2063
2064 /* vim: set shiftwidth=4 tabstop=8: */