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