Proof that check_errors() is sufficient.
[sgt/puzzles] / unfinished / group.c
CommitLineData
d8fa223c 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.
d8fa223c 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
53enum { DIFFLIST(ENUM) DIFFCOUNT };
54static char const *const group_diffnames[] = { DIFFLIST(TITLE) };
55static char const group_diffchars[] = DIFFLIST(ENCODE);
56#define DIFFCONFIG DIFFLIST(CONFIG)
57
58enum {
59 COL_BACKGROUND,
d8fa223c 60 COL_GRID,
61 COL_USER,
62 COL_HIGHLIGHT,
63 COL_ERROR,
64 COL_PENCIL,
65 NCOLOURS
66};
67
5523645e 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))
d8fa223c 78
79struct game_params {
b84b31a8 80 int w, diff, id;
d8fa223c 81};
82
83struct 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
91static game_params *default_params(void)
92{
93 game_params *ret = snew(game_params);
94
95 ret->w = 6;
96 ret->diff = DIFF_NORMAL;
b84b31a8 97 ret->id = TRUE;
d8fa223c 98
99 return ret;
100}
101
102const static struct game_params group_presets[] = {
b84b31a8 103 { 6, DIFF_NORMAL, TRUE },
104 { 6, DIFF_NORMAL, FALSE },
b84b31a8 105 { 8, DIFF_NORMAL, TRUE },
106 { 8, DIFF_NORMAL, FALSE },
5523645e 107 { 8, DIFF_HARD, TRUE },
108 { 8, DIFF_HARD, FALSE },
b84b31a8 109 { 12, DIFF_NORMAL, TRUE },
d8fa223c 110};
111
112static 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
b84b31a8 123 sprintf(buf, "%dx%d %s%s", ret->w, ret->w, group_diffnames[ret->diff],
124 ret->id ? "" : ", identity hidden");
d8fa223c 125
126 *name = dupstr(buf);
127 *params = ret;
128 return TRUE;
129}
130
131static void free_params(game_params *params)
132{
133 sfree(params);
134}
135
136static 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
143static 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++;
b84b31a8 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;
5523645e 166 p++;
167 } else {
168 /* unrecognised character */
169 p++;
b84b31a8 170 }
d8fa223c 171 }
172}
173
174static 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]);
b84b31a8 181 if (!params->id)
182 sprintf(ret + strlen(ret), "i");
d8fa223c 183
184 return dupstr(ret);
185}
186
187static config_item *game_configure(game_params *params)
188{
189 config_item *ret;
190 char buf[80];
191
b84b31a8 192 ret = snewn(4, config_item);
d8fa223c 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
b84b31a8 205 ret[2].name = "Show identity";
206 ret[2].type = C_BOOLEAN;
d8fa223c 207 ret[2].sval = NULL;
b84b31a8 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;
d8fa223c 214
215 return ret;
216}
217
218static 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;
b84b31a8 224 ret->id = cfg[2].ival;
d8fa223c 225
226 return ret;
227}
228
229static char *validate_params(game_params *params, int full)
230{
5523645e 231 if (params->w < 3 || params->w > 26)
232 return "Grid size must be between 3 and 26";
d8fa223c 233 if (params->diff >= DIFFCOUNT)
234 return "Unknown difficulty rating";
5523645e 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 }
d8fa223c 245 return NULL;
246}
247
248/* ----------------------------------------------------------------------
249 * Solver.
250 */
251
252static int solver_normal(struct latin_solver *solver, void *vctx)
253{
254 int w = solver->o;
5523645e 255#ifdef STANDALONE_SOLVER
256 char **names = solver->names;
257#endif
d8fa223c 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) {
5523645e 278 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
d8fa223c 279 solver_recurse_depth*4, "",
5523645e 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",
d8fa223c 284 solver_recurse_depth*4, "",
5523645e 285 names[n-1], x+1, y+1);
d8fa223c 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) {
5523645e 306 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
d8fa223c 307 solver_recurse_depth*4, "",
5523645e 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",
d8fa223c 312 solver_recurse_depth*4, "",
5523645e 313 names[n-1], x+1, y+1);
d8fa223c 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,
334static usersolver_t const group_solvers[] = { DIFFLIST(SOLVER) };
335
5523645e 336static int solver(game_params *params, digit *grid, int maxdiff)
d8fa223c 337{
5523645e 338 int w = params->w;
d8fa223c 339 int ret;
5523645e 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);
d8fa223c 362
363 return ret;
364}
365
366/* ----------------------------------------------------------------------
367 * Grid generation.
368 */
369
370static 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
409struct group {
410 unsigned long autosize;
411 int order, ngens;
412 const char *gens;
413};
414struct groups {
415 int ngroups;
416 const struct group *groups;
417};
418
419static const struct group groupdata[] = {
420 /* order 2 */
5523645e 421 {1L, 2, 1, "BA"},
d8fa223c 422 /* order 3 */
5523645e 423 {2L, 3, 1, "BCA"},
d8fa223c 424 /* order 4 */
5523645e 425 {2L, 4, 1, "BCDA"},
426 {6L, 4, 2, "BADC" "CDAB"},
d8fa223c 427 /* order 5 */
5523645e 428 {4L, 5, 1, "BCDEA"},
d8fa223c 429 /* order 6 */
5523645e 430 {6L, 6, 2, "CFEBAD" "BADCFE"},
431 {2L, 6, 1, "DCFEBA"},
d8fa223c 432 /* order 7 */
5523645e 433 {6L, 7, 1, "BCDEFGA"},
d8fa223c 434 /* order 8 */
5523645e 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"},
d8fa223c 440 /* order 9 */
5523645e 441 {6L, 9, 1, "BDECGHFIA"},
442 {48L, 9, 2, "BDEAGHCIF" "CEFGHAIBD"},
d8fa223c 443 /* order 10 */
5523645e 444 {20L, 10, 2, "CJEBGDIFAH" "BADCFEHGJI"},
445 {4L, 10, 1, "DCFEHGJIBA"},
d8fa223c 446 /* order 11 */
5523645e 447 {10L, 11, 1, "BCDEFGHIJKA"},
d8fa223c 448 /* order 12 */
5523645e 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"},
d8fa223c 454 /* order 13 */
5523645e 455 {12L, 13, 1, "BCDEFGHIJKLMA"},
d8fa223c 456 /* order 14 */
5523645e 457 {42L, 14, 2, "ELGNIBKDMFAHCJ" "BADCFEHGJILKNM"},
458 {6L, 14, 1, "FEHGJILKNMBADC"},
d8fa223c 459 /* order 15 */
5523645e 460 {8L, 15, 1, "EGHCJKFMNIOBLDA"},
d8fa223c 461 /* order 16 */
5523645e 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"},
d8fa223c 471 {192L, 16, 3,
5523645e 472 "MCHPFAIJNBLDEOGK" "BEFGHJKALMNOCDPI" "GKLBNOEDFPHJIAMC"},
473 {64L, 16, 3, "MCHPFAIJNBLDEOGK" "LOGFPKJIBNMEDCHA" "CMAIJHPFDEONBLKG"},
d8fa223c 474 {192L, 16, 3,
5523645e 475 "IPKCOGMLEDJBNFAH" "BEFGHJKALMNOCDPI" "CMEIJBPFKAOGHLDN"},
476 {48L, 16, 3, "IPDJONFLEKCBGMAH" "FJBLMEOCGHPKAIND" "DGIEKLHNJOAMPBCF"},
d8fa223c 477 {20160L, 16, 4,
5523645e 478 "EHJKAMNBOCDPFGIL" "BAFGHCDELMNIJKPO" "CFAIJBLMDEOGHPKN"
479 "DGIAKLBNCOEFPHJM"},
d8fa223c 480 /* order 17 */
5523645e 481 {16L, 17, 1, "EFGHIJKLMNOPQABCD"},
d8fa223c 482 /* order 18 */
5523645e 483 {54L, 18, 2, "MKIQOPNAGLRECDBJHF" "BAEFCDJKLGHIOPMNRQ"},
484 {6L, 18, 1, "ECJKGHFOPDMNLRIQBA"},
485 {12L, 18, 2, "ECJKGHBOPAMNFRDQLI" "KNOPQCFREIGHLJAMBD"},
d8fa223c 486 {432L, 18, 3,
5523645e 487 "IFNAKLQCDOPBGHREMJ" "NOQCFRIGHKLJAMPBDE" "BAEFCDJKLGHIOPMNRQ"},
488 {48L, 18, 2, "ECJKGHBOPAMNFRDQLI" "FDKLHIOPBMNAREQCJG"},
d8fa223c 489 /* order 19 */
5523645e 490 {18L, 19, 1, "EFGHIJKLMNOPQRSABCD"},
d8fa223c 491 /* order 20 */
5523645e 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"},
d8fa223c 497 /* order 21 */
5523645e 498 {42L, 21, 2, "ITLSBOUERDHAGKCJNFMQP" "EJHLMKOPNRSQAUTCDBFGI"},
499 {12L, 21, 1, "EGHCJKFMNIPQLSTOUBRDA"},
d8fa223c 500 /* order 22 */
5523645e 501 {110L, 22, 2, "ETGVIBKDMFOHQJSLUNAPCR" "BADCFEHGJILKNMPORQTSVU"},
502 {10L, 22, 1, "FEHGJILKNMPORQTSVUBADC"},
d8fa223c 503 /* order 23 */
5523645e 504 {22L, 23, 1, "EFGHIJKLMNOPQRSTUVWABCD"},
d8fa223c 505 /* order 24 */
5523645e 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"},
d8fa223c 512 {48L, 24, 3,
5523645e 513 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
514 "HSNOPWLDTUVBRIAKXFGCQEMJ"},
d8fa223c 515 {24L, 24, 3,
5523645e 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"},
d8fa223c 523 {144L, 24, 3,
5523645e 524 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
525 "BAFGHCDEMNOPIJKLTUVQRSXW"},
d8fa223c 526 {336L, 24, 3,
5523645e 527 "QTKJWONXESRIHVUMLDCPGFAB" "JNEQRHTUKLWCOPXFSAIVBMDG"
528 "HENOPJKLTUVBQRSAXFGWCDMI"},
d8fa223c 529 /* order 25 */
5523645e 530 {20L, 25, 1, "EHILMNPQRSFTUVBJWXDOYGAKC"},
531 {480L, 25, 2, "EHILMNPQRSCTUVBFWXDJYGOKA" "BDEGHIKLMNAPQRSCTUVFWXJYO"},
d8fa223c 532 /* order 26 */
533 {156L, 26, 2,
5523645e 534 "EXGZIBKDMFOHQJSLUNWPYRATCV" "BADCFEHGJILKNMPORQTSVUXWZY"},
535 {12L, 26, 1, "FEHGJILKNMPORQTSVUXWZYBADC"},
d8fa223c 536};
537
538static const struct groups groups[] = {
5523645e 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 */
d8fa223c 566};
567
568/* ----- data generated by group.gap ends ----- */
569
570static 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
591for d in t n h x u; do
5523645e 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
d8fa223c 598 done
599done
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 */
5523645e 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)
d8fa223c 609 diff--;
5523645e 610 if ((w < 6 || (w == 6 && params->id)) && diff == DIFF_HARD)
d8fa223c 611 diff--;
5523645e 612 if ((w < 4 || (w == 4 && params->id)) && diff == DIFF_NORMAL)
613 diff--;
614#endif
d8fa223c 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 */
5523645e 655 nri = gen[row[0]-1] - 'A' + 1; /* which row is it? */
d8fa223c 656 newrow = soln + (nri-1)*w;
657 if (!newrow[0]) { /* not done yet */
658 for (k = 0; k < w; k++)
5523645e 659 newrow[k] = gen[row[k]-1] - 'A' + 1;
d8fa223c 660 grid[qt++] = nri;
661 }
662 }
663 }
664 /* That's got the canonical table. Now shuffle it. */
665 for (i = 0; i < w; i++)
b84b31a8 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);
d8fa223c 671 for (i = 0; i < w; i++)
b84b31a8 672 for (j = 0; j < w; j++)
673 grid[(soln2[i])*w+(soln2[j])] = soln2[soln[i*w+j]-1]+1;
d8fa223c 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);
b84b31a8 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);
5523645e 695 if (solver(params, soln2, diff) > diff)
b84b31a8 696 continue; /* go round again if that didn't work */
697 }
d8fa223c 698
699 k = 0;
b84b31a8 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;
7a8dfea2 704 shuffle(indices, k, sizeof(*indices), rs);
d8fa223c 705
706 for (i = 0; i < k; i++) {
707 memcpy(soln2, grid, a);
708 soln2[indices[i]] = 0;
5523645e 709 if (solver(params, soln2, diff) <= diff)
d8fa223c 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);
5523645e 718 if (solver(params, soln2, diff-1) < diff)
d8fa223c 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++)
5523645e 742 (*aux)[i+1] = TOCHAR(soln[i], params->id);
d8fa223c 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
757static 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
787static 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
795static 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
820static 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
846static 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
866static void free_game(game_state *state)
867{
868 sfree(state->grid);
869 sfree(state->immutable);
870 sfree(state->pencil);
871 sfree(state);
872}
873
874static 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
5523645e 888 ret = solver(&state->par, soln, DIFFCOUNT-1);
d8fa223c 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++)
5523645e 900 out[i+1] = TOCHAR(soln[i], state->par.id);
d8fa223c 901 out[a+1] = '\0';
902 }
903
904 sfree(soln);
905 return out;
906}
907
908static int game_can_format_as_text_now(game_params *params)
909{
910 return TRUE;
911}
912
913static 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 {
5523645e 929 ch = TOCHAR(d, state->par.id);
d8fa223c 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
946struct 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
973static game_ui *new_ui(game_state *state)
974{
975 game_ui *ui = snew(game_ui);
976
b84b31a8 977 ui->hx = ui->hy = 0;
d8fa223c 978 ui->hpencil = ui->hshow = ui->hcursor = 0;
979
980 return ui;
981}
982
983static void free_ui(game_ui *ui)
984{
985 sfree(ui);
986}
987
988static char *encode_ui(game_ui *ui)
989{
990 return NULL;
991}
992
993static void decode_ui(game_ui *ui, char *encoding)
994{
995}
996
997static 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)
b84b31a8 1016#define LEGEND (TILESIZE)
d8fa223c 1017#define GRIDEXTRA max((TILESIZE / 32),1)
b84b31a8 1018#define COORD(x) ((x)*TILESIZE + BORDER + LEGEND)
1019#define FROMCOORD(x) (((x)+(TILESIZE-BORDER-LEGEND)) / TILESIZE - 1)
d8fa223c 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
1036struct game_drawstate {
5523645e 1037 game_params par;
d8fa223c 1038 int w, tilesize;
1039 int started;
1040 long *tiles, *pencil, *errors;
1041 long *errtmp;
1042};
1043
1044static 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
05d6901a 1050 /*
1051 * To verify that we have a valid group table, it suffices to
1052 * test latin-square-hood and associativity only. All the other
1053 * group axioms follow from those two.
1054 *
1055 * Proof:
1056 *
1057 * Associativity is given; closure is obvious from latin-
1058 * square-hood. We need to show that an identity exists and that
1059 * every element has an inverse.
1060 *
1061 * Identity: take any element a. There will be some element e
1062 * such that ea=a (in a latin square, every element occurs in
1063 * every row and column, so a must occur somewhere in the a
1064 * column, say on row e). For any other element b, there must
1065 * exist x such that ax=b (same argument from latin-square-hood
1066 * again), and then associativity gives us eb = e(ax) = (ea)x =
1067 * ax = b. Hence eb=b for all b, i.e. e is a left-identity. A
1068 * similar argument tells us that there must be some f which is
1069 * a right-identity, and then we show they are the same element
1070 * by observing that ef must simultaneously equal e and equal f.
1071 *
1072 * Inverses: given any a, by the latin-square argument again,
1073 * there must exist p and q such that pa=e and aq=e (i.e. left-
1074 * and right-inverses). We can show these are equal by
1075 * associativity: p = pe = p(aq) = (pa)q = eq = q. []
1076 */
1077
d8fa223c 1078 if (errors)
1079 for (i = 0; i < a; i++)
1080 errors[i] = 0;
1081
1082 for (y = 0; y < w; y++) {
1083 unsigned long mask = 0, errmask = 0;
1084 for (x = 0; x < w; x++) {
1085 unsigned long bit = 1UL << grid[y*w+x];
1086 errmask |= (mask & bit);
1087 mask |= bit;
1088 }
1089
1090 if (mask != (1 << (w+1)) - (1 << 1)) {
1091 errs = TRUE;
1092 errmask &= ~1UL;
1093 if (errors) {
1094 for (x = 0; x < w; x++)
1095 if (errmask & (1UL << grid[y*w+x]))
1096 errors[y*w+x] |= EF_LATIN;
1097 }
1098 }
1099 }
1100
1101 for (x = 0; x < w; x++) {
1102 unsigned long mask = 0, errmask = 0;
1103 for (y = 0; y < w; y++) {
1104 unsigned long bit = 1UL << grid[y*w+x];
1105 errmask |= (mask & bit);
1106 mask |= bit;
1107 }
1108
1109 if (mask != (1 << (w+1)) - (1 << 1)) {
1110 errs = TRUE;
1111 errmask &= ~1UL;
1112 if (errors) {
1113 for (y = 0; y < w; y++)
1114 if (errmask & (1UL << grid[y*w+x]))
1115 errors[y*w+x] |= EF_LATIN;
1116 }
1117 }
1118 }
1119
1120 for (i = 1; i < w; i++)
1121 for (j = 1; j < w; j++)
1122 for (k = 1; k < w; k++)
1123 if (grid[i*w+j] && grid[j*w+k] &&
1124 grid[(grid[i*w+j]-1)*w+k] &&
1125 grid[i*w+(grid[j*w+k]-1)] &&
1126 grid[(grid[i*w+j]-1)*w+k] != grid[i*w+(grid[j*w+k]-1)]) {
1127 if (errors) {
1128 int a = i+1, b = j+1, c = k+1;
1129 int ab = grid[i*w+j], bc = grid[j*w+k];
1130 int left = (ab-1)*w+(c-1), right = (a-1)*w+(bc-1);
1131 /*
1132 * If the appropriate error slot is already
1133 * used for one of the squares, we don't
1134 * fill either of them.
1135 */
1136 if (!(errors[left] & EF_LEFT_MASK) &&
1137 !(errors[right] & EF_RIGHT_MASK)) {
1138 long err;
1139 err = a;
1140 err = (err << EF_DIGIT_SHIFT) | b;
1141 err = (err << EF_DIGIT_SHIFT) | c;
1142 errors[left] |= err << EF_LEFT_SHIFT;
1143 errors[right] |= err << EF_RIGHT_SHIFT;
1144 }
1145 }
1146 errs = TRUE;
1147 }
1148
1149 return errs;
1150}
1151
1152static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1153 int x, int y, int button)
1154{
1155 int w = state->par.w;
1156 int tx, ty;
1157 char buf[80];
1158
1159 button &= ~MOD_MASK;
1160
1161 tx = FROMCOORD(x);
1162 ty = FROMCOORD(y);
1163
b84b31a8 1164 if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
d8fa223c 1165 if (button == LEFT_BUTTON) {
1166 if (tx == ui->hx && ty == ui->hy &&
1167 ui->hshow && ui->hpencil == 0) {
1168 ui->hshow = 0;
1169 } else {
1170 ui->hx = tx;
1171 ui->hy = ty;
1172 ui->hshow = !state->immutable[ty*w+tx];
1173 ui->hpencil = 0;
1174 }
1175 ui->hcursor = 0;
1176 return ""; /* UI activity occurred */
1177 }
1178 if (button == RIGHT_BUTTON) {
1179 /*
1180 * Pencil-mode highlighting for non filled squares.
1181 */
1182 if (state->grid[ty*w+tx] == 0) {
1183 if (tx == ui->hx && ty == ui->hy &&
1184 ui->hshow && ui->hpencil) {
1185 ui->hshow = 0;
1186 } else {
1187 ui->hpencil = 1;
1188 ui->hx = tx;
1189 ui->hy = ty;
1190 ui->hshow = 1;
1191 }
1192 } else {
1193 ui->hshow = 0;
1194 }
1195 ui->hcursor = 0;
1196 return ""; /* UI activity occurred */
1197 }
1198 }
1199 if (IS_CURSOR_MOVE(button)) {
b84b31a8 1200 move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
d8fa223c 1201 ui->hshow = ui->hcursor = 1;
1202 return "";
1203 }
1204 if (ui->hshow &&
1205 (button == CURSOR_SELECT)) {
1206 ui->hpencil = 1 - ui->hpencil;
1207 ui->hcursor = 1;
1208 return "";
1209 }
1210
1211 if (ui->hshow &&
5523645e 1212 ((ISCHAR(button) && FROMCHAR(button, state->par.id) <= w) ||
d8fa223c 1213 button == CURSOR_SELECT2 || button == '\b')) {
5523645e 1214 int n = FROMCHAR(button, state->par.id);
d8fa223c 1215 if (button == CURSOR_SELECT2 || button == '\b')
1216 n = 0;
1217
1218 /*
1219 * Can't make pencil marks in a filled square. This can only
1220 * become highlighted if we're using cursor keys.
1221 */
1222 if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1223 return NULL;
1224
1225 /*
1226 * Can't do anything to an immutable square.
1227 */
1228 if (state->immutable[ui->hy*w+ui->hx])
1229 return NULL;
1230
1231 sprintf(buf, "%c%d,%d,%d",
1232 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1233
1234 if (!ui->hcursor) ui->hshow = 0;
1235
1236 return dupstr(buf);
1237 }
1238
1239 if (button == 'M' || button == 'm')
1240 return dupstr("M");
1241
1242 return NULL;
1243}
1244
1245static game_state *execute_move(game_state *from, char *move)
1246{
1247 int w = from->par.w, a = w*w;
1248 game_state *ret;
1249 int x, y, i, n;
1250
1251 if (move[0] == 'S') {
1252 ret = dup_game(from);
1253 ret->completed = ret->cheated = TRUE;
1254
1255 for (i = 0; i < a; i++) {
5523645e 1256 if (!ISCHAR(move[i+1]) || FROMCHAR(move[i+1], from->par.id) > w) {
d8fa223c 1257 free_game(ret);
1258 return NULL;
1259 }
5523645e 1260 ret->grid[i] = FROMCHAR(move[i+1], from->par.id);
d8fa223c 1261 ret->pencil[i] = 0;
1262 }
1263
1264 if (move[a+1] != '\0') {
1265 free_game(ret);
1266 return NULL;
1267 }
1268
1269 return ret;
1270 } else if ((move[0] == 'P' || move[0] == 'R') &&
1271 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1272 x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1273 if (from->immutable[y*w+x])
1274 return NULL;
1275
1276 ret = dup_game(from);
1277 if (move[0] == 'P' && n > 0) {
1278 ret->pencil[y*w+x] ^= 1 << n;
1279 } else {
1280 ret->grid[y*w+x] = n;
1281 ret->pencil[y*w+x] = 0;
1282
1283 if (!ret->completed && !check_errors(ret, NULL))
1284 ret->completed = TRUE;
1285 }
1286 return ret;
1287 } else if (move[0] == 'M') {
1288 /*
1289 * Fill in absolutely all pencil marks everywhere. (I
1290 * wouldn't use this for actual play, but it's a handy
1291 * starting point when following through a set of
1292 * diagnostics output by the standalone solver.)
1293 */
1294 ret = dup_game(from);
1295 for (i = 0; i < a; i++) {
1296 if (!ret->grid[i])
1297 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1298 }
1299 return ret;
1300 } else
1301 return NULL; /* couldn't parse move string */
1302}
1303
1304/* ----------------------------------------------------------------------
1305 * Drawing routines.
1306 */
1307
b84b31a8 1308#define SIZE(w) ((w) * TILESIZE + 2*BORDER + LEGEND)
d8fa223c 1309
1310static void game_compute_size(game_params *params, int tilesize,
1311 int *x, int *y)
1312{
1313 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1314 struct { int tilesize; } ads, *ds = &ads;
1315 ads.tilesize = tilesize;
1316
1317 *x = *y = SIZE(params->w);
1318}
1319
1320static void game_set_size(drawing *dr, game_drawstate *ds,
1321 game_params *params, int tilesize)
1322{
1323 ds->tilesize = tilesize;
1324}
1325
1326static float *game_colours(frontend *fe, int *ncolours)
1327{
1328 float *ret = snewn(3 * NCOLOURS, float);
1329
1330 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1331
1332 ret[COL_GRID * 3 + 0] = 0.0F;
1333 ret[COL_GRID * 3 + 1] = 0.0F;
1334 ret[COL_GRID * 3 + 2] = 0.0F;
1335
d8fa223c 1336 ret[COL_USER * 3 + 0] = 0.0F;
1337 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1338 ret[COL_USER * 3 + 2] = 0.0F;
1339
1340 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1341 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1342 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1343
1344 ret[COL_ERROR * 3 + 0] = 1.0F;
1345 ret[COL_ERROR * 3 + 1] = 0.0F;
1346 ret[COL_ERROR * 3 + 2] = 0.0F;
1347
1348 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1349 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1350 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1351
1352 *ncolours = NCOLOURS;
1353 return ret;
1354}
1355
1356static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1357{
1358 int w = state->par.w, a = w*w;
1359 struct game_drawstate *ds = snew(struct game_drawstate);
1360 int i;
1361
1362 ds->w = w;
5523645e 1363 ds->par = state->par; /* structure copy */
d8fa223c 1364 ds->tilesize = 0;
1365 ds->started = FALSE;
1366 ds->tiles = snewn(a, long);
1367 ds->pencil = snewn(a, long);
1368 ds->errors = snewn(a, long);
1369 for (i = 0; i < a; i++)
1370 ds->tiles[i] = ds->pencil[i] = -1;
1371 ds->errtmp = snewn(a, long);
1372
1373 return ds;
1374}
1375
1376static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1377{
1378 sfree(ds->tiles);
1379 sfree(ds->pencil);
1380 sfree(ds->errors);
1381 sfree(ds->errtmp);
1382 sfree(ds);
1383}
1384
d2cfd12c 1385static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, long tile,
1386 long pencil, long error)
d8fa223c 1387{
1388 int w = ds->w /* , a = w*w */;
1389 int tx, ty, tw, th;
1390 int cx, cy, cw, ch;
1391 char str[64];
1392
b84b31a8 1393 tx = BORDER + LEGEND + x * TILESIZE + 1;
1394 ty = BORDER + LEGEND + y * TILESIZE + 1;
d8fa223c 1395
1396 cx = tx;
1397 cy = ty;
1398 cw = tw = TILESIZE-1;
1399 ch = th = TILESIZE-1;
1400
1401 clip(dr, cx, cy, cw, ch);
1402
1403 /* background needs erasing */
1404 draw_rect(dr, cx, cy, cw, ch,
b84b31a8 1405 (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
d8fa223c 1406
1407 /* pencil-mode highlight */
1408 if (tile & DF_HIGHLIGHT_PENCIL) {
1409 int coords[6];
1410 coords[0] = cx;
1411 coords[1] = cy;
1412 coords[2] = cx+cw/2;
1413 coords[3] = cy;
1414 coords[4] = cx;
1415 coords[5] = cy+ch/2;
1416 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1417 }
1418
1419 /* new number needs drawing? */
1420 if (tile & DF_DIGIT_MASK) {
1421 str[1] = '\0';
5523645e 1422 str[0] = TOCHAR(tile & DF_DIGIT_MASK, ds->par.id);
d8fa223c 1423 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1424 FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1425 (error & EF_LATIN) ? COL_ERROR :
1426 (tile & DF_IMMUTABLE) ? COL_GRID : COL_USER, str);
1427
1428 if (error & EF_LEFT_MASK) {
1429 int a = (error >> (EF_LEFT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1430 int b = (error >> (EF_LEFT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1431 int c = (error >> (EF_LEFT_SHIFT ))&EF_DIGIT_MASK;
1432 char buf[10];
5523645e 1433 sprintf(buf, "(%c%c)%c", TOCHAR(a, ds->par.id),
1434 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
d8fa223c 1435 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/6,
1436 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1437 COL_ERROR, buf);
1438 }
1439 if (error & EF_RIGHT_MASK) {
1440 int a = (error >> (EF_RIGHT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1441 int b = (error >> (EF_RIGHT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1442 int c = (error >> (EF_RIGHT_SHIFT ))&EF_DIGIT_MASK;
1443 char buf[10];
5523645e 1444 sprintf(buf, "%c(%c%c)", TOCHAR(a, ds->par.id),
1445 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
d8fa223c 1446 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE - TILESIZE/6,
1447 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1448 COL_ERROR, buf);
1449 }
1450 } else {
1451 int i, j, npencil;
1452 int pl, pr, pt, pb;
1453 float bestsize;
1454 int pw, ph, minph, pbest, fontsize;
1455
1456 /* Count the pencil marks required. */
1457 for (i = 1, npencil = 0; i <= w; i++)
1458 if (pencil & (1 << i))
1459 npencil++;
1460 if (npencil) {
1461
1462 minph = 2;
1463
1464 /*
1465 * Determine the bounding rectangle within which we're going
1466 * to put the pencil marks.
1467 */
1468 /* Start with the whole square */
1469 pl = tx + GRIDEXTRA;
1470 pr = pl + TILESIZE - GRIDEXTRA;
1471 pt = ty + GRIDEXTRA;
1472 pb = pt + TILESIZE - GRIDEXTRA;
1473
1474 /*
1475 * We arrange our pencil marks in a grid layout, with
1476 * the number of rows and columns adjusted to allow the
1477 * maximum font size.
1478 *
1479 * So now we work out what the grid size ought to be.
1480 */
1481 bestsize = 0.0;
1482 pbest = 0;
1483 /* Minimum */
1484 for (pw = 3; pw < max(npencil,4); pw++) {
1485 float fw, fh, fs;
1486
1487 ph = (npencil + pw - 1) / pw;
1488 ph = max(ph, minph);
1489 fw = (pr - pl) / (float)pw;
1490 fh = (pb - pt) / (float)ph;
1491 fs = min(fw, fh);
1492 if (fs > bestsize) {
1493 bestsize = fs;
1494 pbest = pw;
1495 }
1496 }
1497 assert(pbest > 0);
1498 pw = pbest;
1499 ph = (npencil + pw - 1) / pw;
1500 ph = max(ph, minph);
1501
1502 /*
1503 * Now we've got our grid dimensions, work out the pixel
1504 * size of a grid element, and round it to the nearest
1505 * pixel. (We don't want rounding errors to make the
1506 * grid look uneven at low pixel sizes.)
1507 */
1508 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1509
1510 /*
1511 * Centre the resulting figure in the square.
1512 */
1513 pl = tx + (TILESIZE - fontsize * pw) / 2;
1514 pt = ty + (TILESIZE - fontsize * ph) / 2;
1515
1516 /*
1517 * Now actually draw the pencil marks.
1518 */
1519 for (i = 1, j = 0; i <= w; i++)
1520 if (pencil & (1 << i)) {
1521 int dx = j % pw, dy = j / pw;
1522
1523 str[1] = '\0';
5523645e 1524 str[0] = TOCHAR(i, ds->par.id);
d8fa223c 1525 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1526 pt + fontsize * (2*dy+1) / 2,
1527 FONT_VARIABLE, fontsize,
1528 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1529 j++;
1530 }
1531 }
1532 }
1533
1534 unclip(dr);
1535
1536 draw_update(dr, cx, cy, cw, ch);
1537}
1538
1539static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1540 game_state *state, int dir, game_ui *ui,
1541 float animtime, float flashtime)
1542{
1543 int w = state->par.w /*, a = w*w */;
1544 int x, y;
1545
1546 if (!ds->started) {
1547 /*
1548 * The initial contents of the window are not guaranteed and
1549 * can vary with front ends. To be on the safe side, all
1550 * games should start by drawing a big background-colour
1551 * rectangle covering the whole window.
1552 */
1553 draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1554
1555 /*
1556 * Big containing rectangle.
1557 */
1558 draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1559 w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1560 COL_GRID);
1561
b84b31a8 1562 /*
1563 * Table legend.
1564 */
1565 for (x = 0; x < w; x++) {
1566 char str[2];
1567 str[1] = '\0';
5523645e 1568 str[0] = TOCHAR(x+1, ds->par.id);
b84b31a8 1569 draw_text(dr, COORD(x) + TILESIZE/2, BORDER + TILESIZE/2,
1570 FONT_VARIABLE, TILESIZE/2,
1571 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_GRID, str);
1572 draw_text(dr, BORDER + TILESIZE/2, COORD(x) + TILESIZE/2,
1573 FONT_VARIABLE, TILESIZE/2,
1574 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_GRID, str);
1575 }
1576
d8fa223c 1577 draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1578
1579 ds->started = TRUE;
1580 }
1581
1582 check_errors(state, ds->errtmp);
1583
1584 for (y = 0; y < w; y++) {
1585 for (x = 0; x < w; x++) {
1586 long tile = 0L, pencil = 0L, error;
1587
1588 if (state->grid[y*w+x])
1589 tile = state->grid[y*w+x];
1590 else
1591 pencil = (long)state->pencil[y*w+x];
1592
1593 if (state->immutable[y*w+x])
1594 tile |= DF_IMMUTABLE;
1595
1596 if (ui->hshow && ui->hx == x && ui->hy == y)
1597 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
1598
1599 if (flashtime > 0 &&
1600 (flashtime <= FLASH_TIME/3 ||
1601 flashtime >= FLASH_TIME*2/3))
1602 tile |= DF_HIGHLIGHT; /* completion flash */
1603
1604 error = ds->errtmp[y*w+x];
1605
1606 if (ds->tiles[y*w+x] != tile ||
1607 ds->pencil[y*w+x] != pencil ||
1608 ds->errors[y*w+x] != error) {
1609 ds->tiles[y*w+x] = tile;
1610 ds->pencil[y*w+x] = pencil;
1611 ds->errors[y*w+x] = error;
1612 draw_tile(dr, ds, x, y, tile, pencil, error);
1613 }
1614 }
1615 }
1616}
1617
1618static float game_anim_length(game_state *oldstate, game_state *newstate,
1619 int dir, game_ui *ui)
1620{
1621 return 0.0F;
1622}
1623
1624static float game_flash_length(game_state *oldstate, game_state *newstate,
1625 int dir, game_ui *ui)
1626{
1627 if (!oldstate->completed && newstate->completed &&
1628 !oldstate->cheated && !newstate->cheated)
1629 return FLASH_TIME;
1630 return 0.0F;
1631}
1632
1633static int game_timing_state(game_state *state, game_ui *ui)
1634{
1635 if (state->completed)
1636 return FALSE;
1637 return TRUE;
1638}
1639
1640static void game_print_size(game_params *params, float *x, float *y)
1641{
1642 int pw, ph;
1643
1644 /*
1645 * We use 9mm squares by default, like Solo.
1646 */
1647 game_compute_size(params, 900, &pw, &ph);
1648 *x = pw / 100.0F;
1649 *y = ph / 100.0F;
1650}
1651
1652static void game_print(drawing *dr, game_state *state, int tilesize)
1653{
1654 int w = state->par.w;
1655 int ink = print_mono_colour(dr, 0);
d8fa223c 1656 int x, y;
1657
1658 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1659 game_drawstate ads, *ds = &ads;
1660 game_set_size(dr, ds, NULL, tilesize);
1661
1662 /*
b84b31a8 1663 * Border.
d8fa223c 1664 */
b84b31a8 1665 print_line_width(dr, 3 * TILESIZE / 40);
1666 draw_rect_outline(dr, BORDER + LEGEND, BORDER + LEGEND,
1667 w*TILESIZE, w*TILESIZE, ink);
d8fa223c 1668
1669 /*
b84b31a8 1670 * Legend on table.
d8fa223c 1671 */
b84b31a8 1672 for (x = 0; x < w; x++) {
1673 char str[2];
1674 str[1] = '\0';
5523645e 1675 str[0] = TOCHAR(x+1, state->par.id);
b84b31a8 1676 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1677 BORDER + TILESIZE/2,
1678 FONT_VARIABLE, TILESIZE/2,
1679 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1680 draw_text(dr, BORDER + TILESIZE/2,
1681 BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1682 FONT_VARIABLE, TILESIZE/2,
1683 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1684 }
d8fa223c 1685
1686 /*
1687 * Main grid.
1688 */
1689 for (x = 1; x < w; x++) {
1690 print_line_width(dr, TILESIZE / 40);
b84b31a8 1691 draw_line(dr, BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND,
1692 BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND+w*TILESIZE, ink);
d8fa223c 1693 }
1694 for (y = 1; y < w; y++) {
1695 print_line_width(dr, TILESIZE / 40);
b84b31a8 1696 draw_line(dr, BORDER+LEGEND, BORDER+LEGEND+y*TILESIZE,
1697 BORDER+LEGEND+w*TILESIZE, BORDER+LEGEND+y*TILESIZE, ink);
d8fa223c 1698 }
1699
1700 /*
1701 * Numbers.
1702 */
1703 for (y = 0; y < w; y++)
1704 for (x = 0; x < w; x++)
1705 if (state->grid[y*w+x]) {
1706 char str[2];
1707 str[1] = '\0';
5523645e 1708 str[0] = TOCHAR(state->grid[y*w+x], state->par.id);
b84b31a8 1709 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1710 BORDER+LEGEND + y*TILESIZE + TILESIZE/2,
d8fa223c 1711 FONT_VARIABLE, TILESIZE/2,
1712 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1713 }
1714}
1715
1716#ifdef COMBINED
1717#define thegame group
1718#endif
1719
1720const struct game thegame = {
1721 "Group", NULL, NULL,
1722 default_params,
1723 game_fetch_preset,
1724 decode_params,
1725 encode_params,
1726 free_params,
1727 dup_params,
1728 TRUE, game_configure, custom_params,
1729 validate_params,
1730 new_game_desc,
1731 validate_desc,
1732 new_game,
1733 dup_game,
1734 free_game,
1735 TRUE, solve_game,
1736 TRUE, game_can_format_as_text_now, game_text_format,
1737 new_ui,
1738 free_ui,
1739 encode_ui,
1740 decode_ui,
1741 game_changed_state,
1742 interpret_move,
1743 execute_move,
1744 PREFERRED_TILESIZE, game_compute_size, game_set_size,
1745 game_colours,
1746 game_new_drawstate,
1747 game_free_drawstate,
1748 game_redraw,
1749 game_anim_length,
1750 game_flash_length,
1751 TRUE, FALSE, game_print_size, game_print,
1752 FALSE, /* wants_statusbar */
1753 FALSE, game_timing_state,
1754 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
1755};
1756
1757#ifdef STANDALONE_SOLVER
1758
1759#include <stdarg.h>
1760
1761int main(int argc, char **argv)
1762{
1763 game_params *p;
1764 game_state *s;
1765 char *id = NULL, *desc, *err;
1766 digit *grid;
1767 int grade = FALSE;
1768 int ret, diff, really_show_working = FALSE;
1769
1770 while (--argc > 0) {
1771 char *p = *++argv;
1772 if (!strcmp(p, "-v")) {
1773 really_show_working = TRUE;
1774 } else if (!strcmp(p, "-g")) {
1775 grade = TRUE;
1776 } else if (*p == '-') {
1777 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1778 return 1;
1779 } else {
1780 id = p;
1781 }
1782 }
1783
1784 if (!id) {
1785 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
1786 return 1;
1787 }
1788
1789 desc = strchr(id, ':');
1790 if (!desc) {
1791 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
1792 return 1;
1793 }
1794 *desc++ = '\0';
1795
1796 p = default_params();
1797 decode_params(p, id);
1798 err = validate_desc(p, desc);
1799 if (err) {
1800 fprintf(stderr, "%s: %s\n", argv[0], err);
1801 return 1;
1802 }
1803 s = new_game(NULL, p, desc);
1804
1805 grid = snewn(p->w * p->w, digit);
1806
1807 /*
1808 * When solving a Normal puzzle, we don't want to bother the
1809 * user with Hard-level deductions. For this reason, we grade
1810 * the puzzle internally before doing anything else.
1811 */
1812 ret = -1; /* placate optimiser */
1813 solver_show_working = FALSE;
1814 for (diff = 0; diff < DIFFCOUNT; diff++) {
1815 memcpy(grid, s->grid, p->w * p->w);
5523645e 1816 ret = solver(&s->par, grid, diff);
d8fa223c 1817 if (ret <= diff)
1818 break;
1819 }
1820
1821 if (diff == DIFFCOUNT) {
1822 if (grade)
1823 printf("Difficulty rating: ambiguous\n");
1824 else
1825 printf("Unable to find a unique solution\n");
1826 } else {
1827 if (grade) {
1828 if (ret == diff_impossible)
1829 printf("Difficulty rating: impossible (no solution exists)\n");
1830 else
1831 printf("Difficulty rating: %s\n", group_diffnames[ret]);
1832 } else {
1833 solver_show_working = really_show_working;
1834 memcpy(grid, s->grid, p->w * p->w);
5523645e 1835 ret = solver(&s->par, grid, diff);
d8fa223c 1836 if (ret != diff)
1837 printf("Puzzle is inconsistent\n");
1838 else {
1839 memcpy(s->grid, grid, p->w * p->w);
1840 fputs(game_text_format(s), stdout);
1841 }
1842 }
1843 }
1844
1845 return 0;
1846}
1847
1848#endif
1849
1850/* vim: set shiftwidth=4 tabstop=8: */