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