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.
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.
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
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.
44 A(TRIVIAL,Trivial,NULL,t) \
45 A(NORMAL,Normal,solver_normal,n) \
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)
70 * In identity mode, we number the elements e,a,b,c,d,f,g,h,...
71 * Otherwise, they're a,b,c,d,e,f,g,h,... in the obvious way.
73 #define E_TO_FRONT(c,id) ( (id) && (c)<=5 ? (c) % 5 + 1 : (c) )
74 #define E_FROM_FRONT(c,id) ( (id) && (c)<=5 ? ((c) + 3) % 5 + 1 : (c) )
76 #define FROMCHAR(c,id) E_TO_FRONT((((c)-('A'-1)) & ~0x20), id)
77 #define ISCHAR(c) (((c)>='A'&&(c)<='Z') || ((c)>='a'&&(c)<='z'))
78 #define TOCHAR(c,id) (E_FROM_FRONT(c,id) + ('a'-1))
87 unsigned char *immutable;
88 int *pencil; /* bitmaps using bits 1<<1..1<<n */
89 int completed, cheated;
90 digit *sequence; /* sequence of group elements shown */
93 * This array indicates thick lines separating rows and columns
94 * placed and unplaced manually by the user as a visual aid, e.g.
95 * to delineate a subgroup and its cosets.
97 * When a line is placed, it's deemed to be between the two
98 * particular group elements that are on either side of it at the
99 * time; dragging those two away from each other automatically
100 * gets rid of the line. Hence, for a given element i, dividers[i]
101 * is either -1 (indicating no divider to the right of i), or some
102 * other element (indicating a divider to the right of i iff that
103 * element is the one right of it). These are eagerly cleared
106 int *dividers; /* thick lines between rows/cols */
109 static game_params *default_params(void)
111 game_params *ret = snew(game_params);
114 ret->diff = DIFF_NORMAL;
120 const static struct game_params group_presets[] = {
121 { 6, DIFF_NORMAL, TRUE },
122 { 6, DIFF_NORMAL, FALSE },
123 { 8, DIFF_NORMAL, TRUE },
124 { 8, DIFF_NORMAL, FALSE },
125 { 8, DIFF_HARD, TRUE },
126 { 8, DIFF_HARD, FALSE },
127 { 12, DIFF_NORMAL, TRUE },
130 static int game_fetch_preset(int i, char **name, game_params **params)
135 if (i < 0 || i >= lenof(group_presets))
138 ret = snew(game_params);
139 *ret = group_presets[i]; /* structure copy */
141 sprintf(buf, "%dx%d %s%s", ret->w, ret->w, group_diffnames[ret->diff],
142 ret->id ? "" : ", identity hidden");
149 static void free_params(game_params *params)
154 static game_params *dup_params(const game_params *params)
156 game_params *ret = snew(game_params);
157 *ret = *params; /* structure copy */
161 static void decode_params(game_params *params, char const *string)
163 char const *p = string;
166 while (*p && isdigit((unsigned char)*p)) p++;
167 params->diff = DIFF_NORMAL;
174 params->diff = DIFFCOUNT+1; /* ...which is invalid */
176 for (i = 0; i < DIFFCOUNT; i++) {
177 if (*p == group_diffchars[i])
182 } else if (*p == 'i') {
186 /* unrecognised character */
192 static char *encode_params(const game_params *params, int full)
196 sprintf(ret, "%d", params->w);
198 sprintf(ret + strlen(ret), "d%c", group_diffchars[params->diff]);
200 sprintf(ret + strlen(ret), "i");
205 static config_item *game_configure(const game_params *params)
210 ret = snewn(4, config_item);
212 ret[0].name = "Grid size";
213 ret[0].type = C_STRING;
214 sprintf(buf, "%d", params->w);
215 ret[0].u.string.sval = dupstr(buf);
217 ret[1].name = "Difficulty";
218 ret[1].type = C_CHOICES;
219 ret[1].u.choices.choicenames = DIFFCONFIG;
220 ret[1].u.choices.selected = params->diff;
222 ret[2].name = "Show identity";
223 ret[2].type = C_BOOLEAN;
224 ret[2].u.boolean.bval = params->id;
232 static game_params *custom_params(const config_item *cfg)
234 game_params *ret = snew(game_params);
236 ret->w = atoi(cfg[0].u.string.sval);
237 ret->diff = cfg[1].u.choices.selected;
238 ret->id = cfg[2].u.boolean.bval;
243 static const char *validate_params(const game_params *params, int full)
245 if (params->w < 3 || params->w > 26)
246 return "Grid size must be between 3 and 26";
247 if (params->diff >= DIFFCOUNT)
248 return "Unknown difficulty rating";
249 if (!params->id && params->diff == DIFF_TRIVIAL) {
251 * We can't have a Trivial-difficulty puzzle (i.e. latin
252 * square deductions only) without a clear identity, because
253 * identityless puzzles always have two rows and two columns
254 * entirely blank, and no latin-square deduction permits the
255 * distinguishing of two such rows.
257 return "Trivial puzzles must have an identity";
259 if (!params->id && params->w == 3) {
261 * We can't have a 3x3 puzzle without an identity either,
262 * because 3x3 puzzles can't ever be harder than Trivial
263 * (there are no 3x3 latin squares which aren't also valid
264 * group tables, so enabling group-based deductions doesn't
265 * rule out any possible solutions) and - as above - Trivial
266 * puzzles can't not have an identity.
268 return "3x3 puzzles must have an identity";
273 /* ----------------------------------------------------------------------
277 static int solver_normal(struct latin_solver *solver, void *vctx)
280 #ifdef STANDALONE_SOLVER
281 char **names = solver->names;
283 digit *grid = solver->grid;
287 * Deduce using associativity: (ab)c = a(bc).
289 * So we pick any a,b,c we like; then if we know ab, bc, and
290 * (ab)c we can fill in a(bc).
292 for (i = 1; i < w; i++)
293 for (j = 1; j < w; j++)
294 for (k = 1; k < w; k++) {
295 if (!grid[i*w+j] || !grid[j*w+k])
297 if (grid[(grid[i*w+j]-1)*w+k] &&
298 !grid[i*w+(grid[j*w+k]-1)]) {
299 int x = grid[j*w+k]-1, y = i;
300 int n = grid[(grid[i*w+j]-1)*w+k];
301 #ifdef STANDALONE_SOLVER
302 if (solver_show_working) {
303 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
304 solver_recurse_depth*4, "",
305 names[i], names[j], names[k],
306 names[grid[i*w+j]-1], names[k],
307 names[i], names[grid[j*w+k]-1]);
308 printf("%*s placing %s at (%d,%d)\n",
309 solver_recurse_depth*4, "",
310 names[n-1], x+1, y+1);
313 if (solver->cube[(x*w+y)*w+n-1]) {
314 latin_solver_place(solver, x, y, n);
317 #ifdef STANDALONE_SOLVER
318 if (solver_show_working)
319 printf("%*s contradiction!\n",
320 solver_recurse_depth*4, "");
325 if (!grid[(grid[i*w+j]-1)*w+k] &&
326 grid[i*w+(grid[j*w+k]-1)]) {
327 int x = k, y = grid[i*w+j]-1;
328 int n = grid[i*w+(grid[j*w+k]-1)];
329 #ifdef STANDALONE_SOLVER
330 if (solver_show_working) {
331 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
332 solver_recurse_depth*4, "",
333 names[i], names[j], names[k],
334 names[grid[i*w+j]-1], names[k],
335 names[i], names[grid[j*w+k]-1]);
336 printf("%*s placing %s at (%d,%d)\n",
337 solver_recurse_depth*4, "",
338 names[n-1], x+1, y+1);
341 if (solver->cube[(x*w+y)*w+n-1]) {
342 latin_solver_place(solver, x, y, n);
345 #ifdef STANDALONE_SOLVER
346 if (solver_show_working)
347 printf("%*s contradiction!\n",
348 solver_recurse_depth*4, "");
358 #define SOLVER(upper,title,func,lower) func,
359 static usersolver_t const group_solvers[] = { DIFFLIST(SOLVER) };
361 static int solver(const game_params *params, digit *grid, int maxdiff)
365 struct latin_solver solver;
366 #ifdef STANDALONE_SOLVER
367 char *p, text[100], *names[50];
371 latin_solver_alloc(&solver, grid, w);
372 #ifdef STANDALONE_SOLVER
373 for (i = 0, p = text; i < w; i++) {
375 *p++ = TOCHAR(i+1, params->id);
378 solver.names = names;
381 ret = latin_solver_main(&solver, maxdiff,
382 DIFF_TRIVIAL, DIFF_HARD, DIFF_EXTREME,
383 DIFF_EXTREME, DIFF_UNREASONABLE,
384 group_solvers, NULL, NULL, NULL);
386 latin_solver_free(&solver);
391 /* ----------------------------------------------------------------------
395 static char *encode_grid(char *desc, digit *grid, int area)
401 for (i = 0; i <= area; i++) {
402 int n = (i < area ? grid[i] : -1);
409 int c = 'a' - 1 + run;
413 run -= c - ('a' - 1);
417 * If there's a number in the very top left or
418 * bottom right, there's no point putting an
419 * unnecessary _ before or after it.
421 if (p > desc && n > 0)
425 p += sprintf(p, "%d", n);
432 /* ----- data generated by group.gap begins ----- */
435 unsigned long autosize;
441 const struct group *groups;
444 static const struct group groupdata[] = {
451 {6L, 4, 2, "BADC" "CDAB"},
455 {6L, 6, 2, "CFEBAD" "BADCFE"},
456 {2L, 6, 1, "DCFEBA"},
458 {6L, 7, 1, "BCDEFGA"},
460 {4L, 8, 1, "BCEFDGHA"},
461 {8L, 8, 2, "BDEFGAHC" "EGBHDCFA"},
462 {8L, 8, 2, "EGBHDCFA" "BAEFCDHG"},
463 {24L, 8, 2, "BDEFGAHC" "CHDGBEAF"},
464 {168L, 8, 3, "BAEFCDHG" "CEAGBHDF" "DFGAHBCE"},
466 {6L, 9, 1, "BDECGHFIA"},
467 {48L, 9, 2, "BDEAGHCIF" "CEFGHAIBD"},
469 {20L, 10, 2, "CJEBGDIFAH" "BADCFEHGJI"},
470 {4L, 10, 1, "DCFEHGJIBA"},
472 {10L, 11, 1, "BCDEFGHIJKA"},
474 {12L, 12, 2, "GLDKJEHCBIAF" "BCEFAGIJDKLH"},
475 {4L, 12, 1, "EHIJKCBLDGFA"},
476 {24L, 12, 2, "BEFGAIJKCDLH" "FJBKHLEGDCIA"},
477 {12L, 12, 2, "GLDKJEHCBIAF" "BAEFCDIJGHLK"},
478 {12L, 12, 2, "FDIJGHLBKAEC" "GIDKFLHCJEAB"},
480 {12L, 13, 1, "BCDEFGHIJKLMA"},
482 {42L, 14, 2, "ELGNIBKDMFAHCJ" "BADCFEHGJILKNM"},
483 {6L, 14, 1, "FEHGJILKNMBADC"},
485 {8L, 15, 1, "EGHCJKFMNIOBLDA"},
487 {8L, 16, 1, "MKNPFOADBGLCIEHJ"},
488 {96L, 16, 2, "ILKCONFPEDJHGMAB" "BDFGHIAKLMNCOEPJ"},
489 {32L, 16, 2, "MIHPFDCONBLAKJGE" "BEFGHJKALMNOCDPI"},
490 {32L, 16, 2, "IFACOGLMDEJBNPKH" "BEFGHJKALMNOCDPI"},
491 {16L, 16, 2, "MOHPFKCINBLADJGE" "BDFGHIEKLMNJOAPC"},
492 {16L, 16, 2, "MIHPFDJONBLEKCGA" "BDFGHIEKLMNJOAPC"},
493 {32L, 16, 2, "MOHPFDCINBLEKJGA" "BAFGHCDELMNIJKPO"},
494 {16L, 16, 2, "MIHPFKJONBLADCGE" "GDPHNOEKFLBCIAMJ"},
495 {32L, 16, 2, "MIBPFDJOGHLEKCNA" "CLEIJGMPKAOHNFDB"},
497 "MCHPFAIJNBLDEOGK" "BEFGHJKALMNOCDPI" "GKLBNOEDFPHJIAMC"},
498 {64L, 16, 3, "MCHPFAIJNBLDEOGK" "LOGFPKJIBNMEDCHA" "CMAIJHPFDEONBLKG"},
500 "IPKCOGMLEDJBNFAH" "BEFGHJKALMNOCDPI" "CMEIJBPFKAOGHLDN"},
501 {48L, 16, 3, "IPDJONFLEKCBGMAH" "FJBLMEOCGHPKAIND" "DGIEKLHNJOAMPBCF"},
503 "EHJKAMNBOCDPFGIL" "BAFGHCDELMNIJKPO" "CFAIJBLMDEOGHPKN"
506 {16L, 17, 1, "EFGHIJKLMNOPQABCD"},
508 {54L, 18, 2, "MKIQOPNAGLRECDBJHF" "BAEFCDJKLGHIOPMNRQ"},
509 {6L, 18, 1, "ECJKGHFOPDMNLRIQBA"},
510 {12L, 18, 2, "ECJKGHBOPAMNFRDQLI" "KNOPQCFREIGHLJAMBD"},
512 "IFNAKLQCDOPBGHREMJ" "NOQCFRIGHKLJAMPBDE" "BAEFCDJKLGHIOPMNRQ"},
513 {48L, 18, 2, "ECJKGHBOPAMNFRDQLI" "FDKLHIOPBMNAREQCJG"},
515 {18L, 19, 1, "EFGHIJKLMNOPQRSABCD"},
517 {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "EABICDFMGHJQKLNTOPRS"},
518 {8L, 20, 1, "EHIJLCMNPGQRSKBTDOFA"},
519 {20L, 20, 2, "DJSHQNCLTRGPEBKAIFOM" "EABICDFMGHJQKLNTOPRS"},
520 {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "ECBIAGFMDKJQHONTLSRP"},
521 {24L, 20, 2, "IGFMDKJQHONTLSREPCBA" "FDIJGHMNKLQROPTBSAEC"},
523 {42L, 21, 2, "ITLSBOUERDHAGKCJNFMQP" "EJHLMKOPNRSQAUTCDBFGI"},
524 {12L, 21, 1, "EGHCJKFMNIPQLSTOUBRDA"},
526 {110L, 22, 2, "ETGVIBKDMFOHQJSLUNAPCR" "BADCFEHGJILKNMPORQTSVU"},
527 {10L, 22, 1, "FEHGJILKNMPORQTSVUBADC"},
529 {22L, 23, 1, "EFGHIJKLMNOPQRSTUVWABCD"},
531 {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "HRNOPSWCTUVBLDIJXFGAKQME"},
532 {8L, 24, 1, "MQBTUDRWFGHXJELINOPKSAVC"},
533 {24L, 24, 2, "IOQRBEUVFWGHKLAXMNPSCDTJ" "NJXOVGDKSMTFIPQELCURBWAH"},
534 {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "HSNOPWLDTUVBRIAKXFGCQEMJ"},
535 {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "TWHNXLRIOPUMSACQVBFDEJGK"},
536 {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "BAFGHCDEMNOPIJKLTUVQRSXW"},
538 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
539 "HSNOPWLDTUVBRIAKXFGCQEMJ"},
541 "QUKJWPXFESRIVBMNLDCGHTAO" "JXEQRVUMKLWCPGFTSAIBONDH"
542 "TRONXLWCHVUMSAIJPGFDEQBK"},
543 {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "VKXHOQASNTPBCWDEUFGIJLMR"},
544 {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "RMLWIGTUSDJQOPFXEKCBVNAH"},
545 {48L, 24, 2, "IULQRGXMSDCWOPNTEKJBVFAH" "GLMOPRSDTUBVWIEKFXHJQANC"},
546 {24L, 24, 2, "UJPXMRCSNHGTLWIKFVBEDQOA" "NRUFVLWIPXMOJEDQHGTCSABK"},
547 {24L, 24, 2, "MIBTUAQRFGHXCDEWNOPJKLVS" "OKXVFWSCGUTNDRQJBPMALIHE"},
549 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
550 "BAFGHCDEMNOPIJKLTUVQRSXW"},
552 "QTKJWONXESRIHVUMLDCPGFAB" "JNEQRHTUKLWCOPXFSAIVBMDG"
553 "HENOPJKLTUVBQRSAXFGWCDMI"},
555 {20L, 25, 1, "EHILMNPQRSFTUVBJWXDOYGAKC"},
556 {480L, 25, 2, "EHILMNPQRSCTUVBFWXDJYGOKA" "BDEGHIKLMNAPQRSCTUVFWXJYO"},
559 "EXGZIBKDMFOHQJSLUNWPYRATCV" "BADCFEHGJILKNMPORQTSVUXWZY"},
560 {12L, 26, 1, "FEHGJILKNMPORQTSVUXWZYBADC"},
563 static const struct groups groups[] = {
564 {0, NULL}, /* trivial case: 0 */
565 {0, NULL}, /* trivial case: 1 */
566 {1, groupdata + 0}, /* 2 */
567 {1, groupdata + 1}, /* 3 */
568 {2, groupdata + 2}, /* 4 */
569 {1, groupdata + 4}, /* 5 */
570 {2, groupdata + 5}, /* 6 */
571 {1, groupdata + 7}, /* 7 */
572 {5, groupdata + 8}, /* 8 */
573 {2, groupdata + 13}, /* 9 */
574 {2, groupdata + 15}, /* 10 */
575 {1, groupdata + 17}, /* 11 */
576 {5, groupdata + 18}, /* 12 */
577 {1, groupdata + 23}, /* 13 */
578 {2, groupdata + 24}, /* 14 */
579 {1, groupdata + 26}, /* 15 */
580 {14, groupdata + 27}, /* 16 */
581 {1, groupdata + 41}, /* 17 */
582 {5, groupdata + 42}, /* 18 */
583 {1, groupdata + 47}, /* 19 */
584 {5, groupdata + 48}, /* 20 */
585 {2, groupdata + 53}, /* 21 */
586 {2, groupdata + 55}, /* 22 */
587 {1, groupdata + 57}, /* 23 */
588 {15, groupdata + 58}, /* 24 */
589 {2, groupdata + 73}, /* 25 */
590 {2, groupdata + 75}, /* 26 */
593 /* ----- data generated by group.gap ends ----- */
595 static char *new_game_desc(const game_params *params, random_state *rs,
596 char **aux, int interactive)
598 int w = params->w, a = w*w;
599 digit *grid, *soln, *soln2;
602 int diff = params->diff;
603 const struct group *group;
607 * Difficulty exceptions: some combinations of size and
608 * difficulty cannot be satisfied, because all puzzles of at
609 * most that difficulty are actually even easier.
611 * Remember to re-test this whenever a change is made to the
614 * I tested it using the following shell command:
616 for d in t n h x u; do
619 echo -n "./group --generate 1 ${i}d${d}${id}: "
620 perl -e 'alarm 30; exec @ARGV' \
621 ./group --generate 1 ${i}d${d}${id} >/dev/null && echo ok
626 * Of course, it's better to do that after taking the exceptions
627 * _out_, so as to detect exceptions that should be removed as
628 * well as those which should be added.
630 if (w < 5 && diff == DIFF_UNREASONABLE)
632 if ((w < 5 || ((w == 6 || w == 8) && params->id)) && diff == DIFF_EXTREME)
634 if ((w < 6 || (w == 6 && params->id)) && diff == DIFF_HARD)
636 if ((w < 4 || (w == 4 && params->id)) && diff == DIFF_NORMAL)
639 grid = snewn(a, digit);
640 soln = snewn(a, digit);
641 soln2 = snewn(a, digit);
642 indices = snewn(a, int);
646 * Construct a valid group table, by picking a group from
647 * the above data table, decompressing it into a full
648 * representation by BFS, and then randomly permuting its
649 * non-identity elements.
651 * We build the canonical table in 'soln' (and use 'grid' as
652 * our BFS queue), then transfer the table into 'grid'
653 * having shuffled the rows.
656 assert(w < lenof(groups));
657 group = groups[w].groups + random_upto(rs, groups[w].ngroups);
658 assert(group->order == w);
660 for (i = 0; i < w; i++)
668 row = soln + (i-1)*w;
670 for (j = 0; j < group->ngens; j++) {
672 const char *gen = group->gens + j*w;
675 * Apply each group generator to row, constructing a
678 nri = gen[row[0]-1] - 'A' + 1; /* which row is it? */
679 newrow = soln + (nri-1)*w;
680 if (!newrow[0]) { /* not done yet */
681 for (k = 0; k < w; k++)
682 newrow[k] = gen[row[k]-1] - 'A' + 1;
687 /* That's got the canonical table. Now shuffle it. */
688 for (i = 0; i < w; i++)
690 if (params->id) /* do we shuffle in the identity? */
691 shuffle(soln2+1, w-1, sizeof(*soln2), rs);
693 shuffle(soln2, w, sizeof(*soln2), rs);
694 for (i = 0; i < w; i++)
695 for (j = 0; j < w; j++)
696 grid[(soln2[i])*w+(soln2[j])] = soln2[soln[i*w+j]-1]+1;
699 * Remove entries one by one while the puzzle is still
700 * soluble at the appropriate difficulty level.
702 memcpy(soln, grid, a);
705 * Start by blanking the entire identity row and column,
706 * and also another row and column so that the player
707 * can't trivially determine which element is the
711 j = 1 + random_upto(rs, w-1); /* pick a second row/col to blank */
712 for (i = 0; i < w; i++) {
713 grid[(soln2[0])*w+i] = grid[i*w+(soln2[0])] = 0;
714 grid[(soln2[j])*w+i] = grid[i*w+(soln2[j])] = 0;
717 memcpy(soln2, grid, a);
718 if (solver(params, soln2, diff) > diff)
719 continue; /* go round again if that didn't work */
723 for (i = (params->id ? 1 : 0); i < w; i++)
724 for (j = (params->id ? 1 : 0); j < w; j++)
726 indices[k++] = i*w+j;
727 shuffle(indices, k, sizeof(*indices), rs);
729 for (i = 0; i < k; i++) {
730 memcpy(soln2, grid, a);
731 soln2[indices[i]] = 0;
732 if (solver(params, soln2, diff) <= diff)
733 grid[indices[i]] = 0;
737 * Make sure the puzzle isn't too easy.
740 memcpy(soln2, grid, a);
741 if (solver(params, soln2, diff-1) < diff)
742 continue; /* go round and try again */
752 * Encode the puzzle description.
754 desc = snewn(a*20, char);
755 p = encode_grid(desc, grid, a);
757 desc = sresize(desc, p - desc, char);
760 * Encode the solution.
762 *aux = snewn(a+2, char);
764 for (i = 0; i < a; i++)
765 (*aux)[i+1] = TOCHAR(soln[i], params->id);
776 /* ----------------------------------------------------------------------
780 static const char *validate_grid_desc(const char **pdesc, int range, int area)
782 const char *desc = *pdesc;
784 while (*desc && *desc != ',') {
786 if (n >= 'a' && n <= 'z') {
787 squares += n - 'a' + 1;
788 } else if (n == '_') {
790 } else if (n > '0' && n <= '9') {
791 int val = atoi(desc-1);
792 if (val < 1 || val > range)
793 return "Out-of-range number in game description";
795 while (*desc >= '0' && *desc <= '9')
798 return "Invalid character in game description";
802 return "Not enough data to fill grid";
805 return "Too much data to fit in grid";
810 static const char *validate_desc(const game_params *params, const char *desc)
812 int w = params->w, a = w*w;
813 const char *p = desc;
815 return validate_grid_desc(&p, w, a);
818 static const char *spec_to_grid(const char *desc, digit *grid, int area)
821 while (*desc && *desc != ',') {
823 if (n >= 'a' && n <= 'z') {
824 int run = n - 'a' + 1;
825 assert(i + run <= area);
828 } else if (n == '_') {
830 } else if (n > '0' && n <= '9') {
832 grid[i++] = atoi(desc-1);
833 while (*desc >= '0' && *desc <= '9')
836 assert(!"We can't get here");
843 static game_state *new_game(midend *me, const game_params *params,
846 int w = params->w, a = w*w;
847 game_state *state = snew(game_state);
850 state->par = *params; /* structure copy */
851 state->grid = snewn(a, digit);
852 state->immutable = snewn(a, unsigned char);
853 state->pencil = snewn(a, int);
854 for (i = 0; i < a; i++) {
856 state->immutable[i] = 0;
857 state->pencil[i] = 0;
859 state->sequence = snewn(w, digit);
860 state->dividers = snewn(w, int);
861 for (i = 0; i < w; i++) {
862 state->sequence[i] = i;
863 state->dividers[i] = -1;
866 desc = spec_to_grid(desc, state->grid, a);
867 for (i = 0; i < a; i++)
868 if (state->grid[i] != 0)
869 state->immutable[i] = TRUE;
871 state->completed = state->cheated = FALSE;
876 static game_state *dup_game(const game_state *state)
878 int w = state->par.w, a = w*w;
879 game_state *ret = snew(game_state);
881 ret->par = state->par; /* structure copy */
883 ret->grid = snewn(a, digit);
884 ret->immutable = snewn(a, unsigned char);
885 ret->pencil = snewn(a, int);
886 ret->sequence = snewn(w, digit);
887 ret->dividers = snewn(w, int);
888 memcpy(ret->grid, state->grid, a*sizeof(digit));
889 memcpy(ret->immutable, state->immutable, a*sizeof(unsigned char));
890 memcpy(ret->pencil, state->pencil, a*sizeof(int));
891 memcpy(ret->sequence, state->sequence, w*sizeof(digit));
892 memcpy(ret->dividers, state->dividers, w*sizeof(int));
894 ret->completed = state->completed;
895 ret->cheated = state->cheated;
900 static void free_game(game_state *state)
903 sfree(state->immutable);
904 sfree(state->pencil);
905 sfree(state->sequence);
909 static char *solve_game(const game_state *state, const game_state *currstate,
910 const char *aux, const char **error)
912 int w = state->par.w, a = w*w;
920 soln = snewn(a, digit);
921 memcpy(soln, state->grid, a*sizeof(digit));
923 ret = solver(&state->par, soln, DIFFCOUNT-1);
925 if (ret == diff_impossible) {
926 *error = "No solution exists for this puzzle";
928 } else if (ret == diff_ambiguous) {
929 *error = "Multiple solutions exist for this puzzle";
932 out = snewn(a+2, char);
934 for (i = 0; i < a; i++)
935 out[i+1] = TOCHAR(soln[i], state->par.id);
943 static int game_can_format_as_text_now(const game_params *params)
948 static char *game_text_format(const game_state *state)
950 int w = state->par.w;
954 ret = snewn(2*w*w+1, char); /* leave room for terminating NUL */
957 for (y = 0; y < w; y++) {
958 for (x = 0; x < w; x++) {
959 digit d = state->grid[y*w+x];
964 ch = TOCHAR(d, state->par.id);
976 assert(p - ret == 2*w*w);
983 * These are the coordinates of the primary highlighted square on
984 * the grid, if hshow = 1.
988 * These are the coordinates hx,hy _before_ they go through
993 * These variables give the length and displacement of a diagonal
994 * sequence of highlighted squares starting at ohx,ohy (still if
995 * hshow = 1). To find the squares' real coordinates, for 0<=i<dn,
996 * compute ohx+i*odx and ohy+i*ody and then map through
1001 * This indicates whether the current highlight is a
1002 * pencil-mark one or a real one.
1006 * This indicates whether or not we're showing the highlight
1007 * (used to be hx = hy = -1); important so that when we're
1008 * using the cursor keys it doesn't keep coming back at a
1009 * fixed position. When hshow = 1, pressing a valid number
1010 * or letter key or Space will enter that number or letter in the grid.
1014 * This indicates whether we're using the highlight as a cursor;
1015 * it means that it doesn't vanish on a keypress, and that it is
1016 * allowed on immutable squares.
1020 * This indicates whether we're dragging a table header to
1021 * reposition an entire row or column.
1023 int drag; /* 0=none 1=row 2=col */
1024 int dragnum; /* element being dragged */
1025 int dragpos; /* its current position */
1029 static game_ui *new_ui(const game_state *state)
1031 game_ui *ui = snew(game_ui);
1033 ui->hx = ui->hy = 0;
1034 ui->hpencil = ui->hshow = ui->hcursor = 0;
1040 static void free_ui(game_ui *ui)
1045 static char *encode_ui(const game_ui *ui)
1050 static void decode_ui(game_ui *ui, const char *encoding)
1054 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1055 const game_state *newstate)
1057 int w = newstate->par.w;
1059 * We prevent pencil-mode highlighting of a filled square, unless
1060 * we're using the cursor keys. So if the user has just filled in
1061 * a square which we had a pencil-mode highlight in (by Undo, or
1062 * by Redo, or by Solve), then we cancel the highlight.
1064 if (ui->hshow && ui->hpencil && !ui->hcursor &&
1065 newstate->grid[ui->hy * w + ui->hx] != 0) {
1068 if (ui->hshow && ui->odn > 1) {
1070 * Reordering of rows or columns within the range of a
1071 * multifill selection cancels the multifill and deselects
1075 for (i = 0; i < ui->odn; i++) {
1076 if (oldstate->sequence[ui->ohx + i*ui->odx] !=
1077 newstate->sequence[ui->ohx + i*ui->odx]) {
1081 if (oldstate->sequence[ui->ohy + i*ui->ody] !=
1082 newstate->sequence[ui->ohy + i*ui->ody]) {
1087 } else if (ui->hshow &&
1088 (newstate->sequence[ui->ohx] != ui->hx ||
1089 newstate->sequence[ui->ohy] != ui->hy)) {
1091 * Otherwise, reordering of the row or column containing the
1092 * selection causes the selection to move with it.
1095 for (i = 0; i < w; i++) {
1096 if (newstate->sequence[i] == ui->hx)
1098 if (newstate->sequence[i] == ui->hy)
1104 #define PREFERRED_TILESIZE 48
1105 #define TILESIZE (ds->tilesize)
1106 #define BORDER (TILESIZE / 2)
1107 #define LEGEND (TILESIZE)
1108 #define GRIDEXTRA max((TILESIZE / 32),1)
1109 #define COORD(x) ((x)*TILESIZE + BORDER + LEGEND)
1110 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER-LEGEND)) / TILESIZE - 1)
1112 #define FLASH_TIME 0.4F
1114 #define DF_DIVIDER_TOP 0x1000
1115 #define DF_DIVIDER_BOT 0x2000
1116 #define DF_DIVIDER_LEFT 0x4000
1117 #define DF_DIVIDER_RIGHT 0x8000
1118 #define DF_HIGHLIGHT 0x0400
1119 #define DF_HIGHLIGHT_PENCIL 0x0200
1120 #define DF_IMMUTABLE 0x0100
1121 #define DF_LEGEND 0x0080
1122 #define DF_DIGIT_MASK 0x001F
1124 #define EF_DIGIT_SHIFT 5
1125 #define EF_DIGIT_MASK ((1 << EF_DIGIT_SHIFT) - 1)
1126 #define EF_LEFT_SHIFT 0
1127 #define EF_RIGHT_SHIFT (3*EF_DIGIT_SHIFT)
1128 #define EF_LEFT_MASK ((1UL << (3*EF_DIGIT_SHIFT)) - 1UL)
1129 #define EF_RIGHT_MASK (EF_LEFT_MASK << EF_RIGHT_SHIFT)
1130 #define EF_LATIN (1UL << (6*EF_DIGIT_SHIFT))
1132 struct game_drawstate {
1136 long *tiles, *legend, *pencil, *errors;
1141 static int check_errors(const game_state *state, long *errors)
1143 int w = state->par.w, a = w*w;
1144 digit *grid = state->grid;
1145 int i, j, k, x, y, errs = FALSE;
1148 * To verify that we have a valid group table, it suffices to
1149 * test latin-square-hood and associativity only. All the other
1150 * group axioms follow from those two.
1154 * Associativity is given; closure is obvious from latin-
1155 * square-hood. We need to show that an identity exists and that
1156 * every element has an inverse.
1158 * Identity: take any element a. There will be some element e
1159 * such that ea=a (in a latin square, every element occurs in
1160 * every row and column, so a must occur somewhere in the a
1161 * column, say on row e). For any other element b, there must
1162 * exist x such that ax=b (same argument from latin-square-hood
1163 * again), and then associativity gives us eb = e(ax) = (ea)x =
1164 * ax = b. Hence eb=b for all b, i.e. e is a left-identity. A
1165 * similar argument tells us that there must be some f which is
1166 * a right-identity, and then we show they are the same element
1167 * by observing that ef must simultaneously equal e and equal f.
1169 * Inverses: given any a, by the latin-square argument again,
1170 * there must exist p and q such that pa=e and aq=e (i.e. left-
1171 * and right-inverses). We can show these are equal by
1172 * associativity: p = pe = p(aq) = (pa)q = eq = q. []
1176 for (i = 0; i < a; i++)
1179 for (y = 0; y < w; y++) {
1180 unsigned long mask = 0, errmask = 0;
1181 for (x = 0; x < w; x++) {
1182 unsigned long bit = 1UL << grid[y*w+x];
1183 errmask |= (mask & bit);
1187 if (mask != (1 << (w+1)) - (1 << 1)) {
1191 for (x = 0; x < w; x++)
1192 if (errmask & (1UL << grid[y*w+x]))
1193 errors[y*w+x] |= EF_LATIN;
1198 for (x = 0; x < w; x++) {
1199 unsigned long mask = 0, errmask = 0;
1200 for (y = 0; y < w; y++) {
1201 unsigned long bit = 1UL << grid[y*w+x];
1202 errmask |= (mask & bit);
1206 if (mask != (1 << (w+1)) - (1 << 1)) {
1210 for (y = 0; y < w; y++)
1211 if (errmask & (1UL << grid[y*w+x]))
1212 errors[y*w+x] |= EF_LATIN;
1217 for (i = 1; i < w; i++)
1218 for (j = 1; j < w; j++)
1219 for (k = 1; k < w; k++)
1220 if (grid[i*w+j] && grid[j*w+k] &&
1221 grid[(grid[i*w+j]-1)*w+k] &&
1222 grid[i*w+(grid[j*w+k]-1)] &&
1223 grid[(grid[i*w+j]-1)*w+k] != grid[i*w+(grid[j*w+k]-1)]) {
1225 int a = i+1, b = j+1, c = k+1;
1226 int ab = grid[i*w+j], bc = grid[j*w+k];
1227 int left = (ab-1)*w+(c-1), right = (a-1)*w+(bc-1);
1229 * If the appropriate error slot is already
1230 * used for one of the squares, we don't
1231 * fill either of them.
1233 if (!(errors[left] & EF_LEFT_MASK) &&
1234 !(errors[right] & EF_RIGHT_MASK)) {
1237 err = (err << EF_DIGIT_SHIFT) | b;
1238 err = (err << EF_DIGIT_SHIFT) | c;
1239 errors[left] |= err << EF_LEFT_SHIFT;
1240 errors[right] |= err << EF_RIGHT_SHIFT;
1249 static int find_in_sequence(digit *seq, int len, digit n)
1253 for (i = 0; i < len; i++)
1257 assert(!"Should never get here");
1261 static char *interpret_move(const game_state *state, game_ui *ui,
1262 const game_drawstate *ds,
1263 int x, int y, int button)
1265 int w = state->par.w;
1269 button &= ~MOD_MASK;
1275 if (IS_MOUSE_DRAG(button)) {
1276 int tcoord = ((ui->drag &~ 4) == 1 ? ty : tx);
1277 ui->drag |= 4; /* some movement has happened */
1278 if (tcoord >= 0 && tcoord < w) {
1279 ui->dragpos = tcoord;
1282 } else if (IS_MOUSE_RELEASE(button)) {
1284 ui->drag = 0; /* end drag */
1285 if (state->sequence[ui->dragpos] == ui->dragnum)
1286 return UI_UPDATE; /* drag was a no-op overall */
1287 sprintf(buf, "D%d,%d", ui->dragnum, ui->dragpos);
1290 ui->drag = 0; /* end 'drag' */
1291 if (ui->edgepos > 0 && ui->edgepos < w) {
1292 sprintf(buf, "V%d,%d",
1293 state->sequence[ui->edgepos-1],
1294 state->sequence[ui->edgepos]);
1297 return UI_UPDATE; /* no-op */
1300 } else if (IS_MOUSE_DOWN(button)) {
1301 if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1302 int otx = tx, oty = ty;
1303 tx = state->sequence[tx];
1304 ty = state->sequence[ty];
1305 if (button == LEFT_BUTTON) {
1306 if (tx == ui->hx && ty == ui->hy &&
1307 ui->hshow && ui->hpencil == 0) {
1314 ui->odx = ui->ody = 0;
1316 ui->hshow = !state->immutable[ty*w+tx];
1322 if (button == RIGHT_BUTTON) {
1324 * Pencil-mode highlighting for non filled squares.
1326 if (state->grid[ty*w+tx] == 0) {
1327 if (tx == ui->hx && ty == ui->hy &&
1328 ui->hshow && ui->hpencil) {
1336 ui->odx = ui->ody = 0;
1346 } else if (tx >= 0 && tx < w && ty == -1) {
1348 ui->dragnum = state->sequence[tx];
1350 ui->edgepos = FROMCOORD(x + TILESIZE/2);
1352 } else if (ty >= 0 && ty < w && tx == -1) {
1354 ui->dragnum = state->sequence[ty];
1356 ui->edgepos = FROMCOORD(y + TILESIZE/2);
1359 } else if (IS_MOUSE_DRAG(button)) {
1361 tx >= 0 && tx < w && ty >= 0 && ty < w &&
1362 abs(tx - ui->ohx) == abs(ty - ui->ohy)) {
1363 ui->odn = abs(tx - ui->ohx) + 1;
1364 ui->odx = (tx < ui->ohx ? -1 : +1);
1365 ui->ody = (ty < ui->ohy ? -1 : +1);
1367 ui->odx = ui->ody = 0;
1373 if (IS_CURSOR_MOVE(button)) {
1374 int cx = find_in_sequence(state->sequence, w, ui->hx);
1375 int cy = find_in_sequence(state->sequence, w, ui->hy);
1376 move_cursor(button, &cx, &cy, w, w, 0);
1377 ui->hx = state->sequence[cx];
1378 ui->hy = state->sequence[cy];
1379 ui->hshow = ui->hcursor = 1;
1383 (button == CURSOR_SELECT)) {
1384 ui->hpencil = 1 - ui->hpencil;
1390 ((ISCHAR(button) && FROMCHAR(button, state->par.id) <= w) ||
1391 button == CURSOR_SELECT2 || button == '\b')) {
1392 int n = FROMCHAR(button, state->par.id);
1396 if (button == CURSOR_SELECT2 || button == '\b')
1399 for (i = 0; i < ui->odn; i++) {
1400 int x = state->sequence[ui->ohx + i*ui->odx];
1401 int y = state->sequence[ui->ohy + i*ui->ody];
1405 * Can't make pencil marks in a filled square. This can only
1406 * become highlighted if we're using cursor keys.
1408 if (ui->hpencil && state->grid[index])
1412 * Can't do anything to an immutable square. Exception:
1413 * trying to set it to what it already was is OK (so that
1414 * multifilling can set a whole diagonal to a without
1415 * having to detour round the one immutable square in the
1416 * middle that already said a).
1418 if (!ui->hpencil && state->grid[index] == n)
1419 /* OK even if it is immutable */;
1420 else if (state->immutable[index])
1424 movebuf = snewn(80 * ui->odn, char);
1425 buflen = sprintf(movebuf, "%c%d,%d,%d",
1426 (char)(ui->hpencil && n > 0 ? 'P' : 'R'),
1428 for (i = 1; i < ui->odn; i++) {
1429 assert(buflen < i*80);
1430 buflen += sprintf(movebuf + buflen, "+%d,%d",
1431 state->sequence[ui->ohx + i*ui->odx],
1432 state->sequence[ui->ohy + i*ui->ody]);
1434 movebuf = sresize(movebuf, buflen+1, char);
1436 if (!ui->hcursor) ui->hshow = 0;
1441 if (button == 'M' || button == 'm')
1447 static game_state *execute_move(const game_state *from, const char *move)
1449 int w = from->par.w, a = w*w;
1451 int x, y, i, j, n, pos;
1453 if (move[0] == 'S') {
1454 ret = dup_game(from);
1455 ret->completed = ret->cheated = TRUE;
1457 for (i = 0; i < a; i++) {
1458 if (!ISCHAR(move[i+1]) || FROMCHAR(move[i+1], from->par.id) > w) {
1462 ret->grid[i] = FROMCHAR(move[i+1], from->par.id);
1466 if (move[a+1] != '\0') {
1472 } else if ((move[0] == 'P' || move[0] == 'R') &&
1473 sscanf(move+1, "%d,%d,%d%n", &x, &y, &n, &pos) == 3 &&
1475 const char *mp = move + 1 + pos;
1476 int pencil = (move[0] == 'P');
1477 ret = dup_game(from);
1480 if (x < 0 || x >= w || y < 0 || y >= w) {
1484 if (from->immutable[y*w+x] && !(!pencil && from->grid[y*w+x] == n))
1487 if (move[0] == 'P' && n > 0) {
1488 ret->pencil[y*w+x] ^= 1 << n;
1490 ret->grid[y*w+x] = n;
1491 ret->pencil[y*w+x] = 0;
1499 if (sscanf(mp, "+%d,%d%n", &x, &y, &pos) < 2)
1504 if (!ret->completed && !check_errors(ret, NULL))
1505 ret->completed = TRUE;
1508 } else if (move[0] == 'M') {
1510 * Fill in absolutely all pencil marks everywhere. (I
1511 * wouldn't use this for actual play, but it's a handy
1512 * starting point when following through a set of
1513 * diagnostics output by the standalone solver.)
1515 ret = dup_game(from);
1516 for (i = 0; i < a; i++) {
1518 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1521 } else if (move[0] == 'D' &&
1522 sscanf(move+1, "%d,%d", &x, &y) == 2) {
1524 * Reorder the rows and columns so that digit x is in position
1527 ret = dup_game(from);
1528 for (i = j = 0; i < w; i++) {
1530 ret->sequence[i] = x;
1532 if (from->sequence[j] == x)
1534 ret->sequence[i] = from->sequence[j++];
1538 * Eliminate any obsoleted dividers.
1540 for (x = 0; x < w; x++) {
1541 int i = ret->sequence[x];
1542 int j = (x+1 < w ? ret->sequence[x+1] : -1);
1543 if (ret->dividers[i] != j)
1544 ret->dividers[i] = -1;
1547 } else if (move[0] == 'V' &&
1548 sscanf(move+1, "%d,%d", &i, &j) == 2) {
1549 ret = dup_game(from);
1550 if (ret->dividers[i] == j)
1551 ret->dividers[i] = -1;
1553 ret->dividers[i] = j;
1556 return NULL; /* couldn't parse move string */
1559 /* ----------------------------------------------------------------------
1563 #define SIZE(w) ((w) * TILESIZE + 2*BORDER + LEGEND)
1565 static void game_compute_size(const game_params *params, int tilesize,
1568 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1569 struct { int tilesize; } ads, *ds = &ads;
1570 ads.tilesize = tilesize;
1572 *x = *y = SIZE(params->w);
1575 static void game_set_size(drawing *dr, game_drawstate *ds,
1576 const game_params *params, int tilesize)
1578 ds->tilesize = tilesize;
1581 static float *game_colours(frontend *fe, int *ncolours)
1583 float *ret = snewn(3 * NCOLOURS, float);
1585 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1587 ret[COL_GRID * 3 + 0] = 0.0F;
1588 ret[COL_GRID * 3 + 1] = 0.0F;
1589 ret[COL_GRID * 3 + 2] = 0.0F;
1591 ret[COL_USER * 3 + 0] = 0.0F;
1592 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1593 ret[COL_USER * 3 + 2] = 0.0F;
1595 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1596 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1597 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1599 ret[COL_ERROR * 3 + 0] = 1.0F;
1600 ret[COL_ERROR * 3 + 1] = 0.0F;
1601 ret[COL_ERROR * 3 + 2] = 0.0F;
1603 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1604 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1605 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1607 ret[COL_DIAGONAL * 3 + 0] = 0.95F * ret[COL_BACKGROUND * 3 + 0];
1608 ret[COL_DIAGONAL * 3 + 1] = 0.95F * ret[COL_BACKGROUND * 3 + 1];
1609 ret[COL_DIAGONAL * 3 + 2] = 0.95F * ret[COL_BACKGROUND * 3 + 2];
1611 *ncolours = NCOLOURS;
1615 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1617 int w = state->par.w, a = w*w;
1618 struct game_drawstate *ds = snew(struct game_drawstate);
1622 ds->par = state->par; /* structure copy */
1624 ds->started = FALSE;
1625 ds->tiles = snewn(a, long);
1626 ds->legend = snewn(w, long);
1627 ds->pencil = snewn(a, long);
1628 ds->errors = snewn(a, long);
1629 ds->sequence = snewn(a, digit);
1630 for (i = 0; i < a; i++)
1631 ds->tiles[i] = ds->pencil[i] = -1;
1632 for (i = 0; i < w; i++)
1634 ds->errtmp = snewn(a, long);
1639 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1645 sfree(ds->sequence);
1649 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, long tile,
1650 long pencil, long error)
1652 int w = ds->w /* , a = w*w */;
1657 tx = BORDER + LEGEND + x * TILESIZE + 1;
1658 ty = BORDER + LEGEND + y * TILESIZE + 1;
1662 cw = tw = TILESIZE-1;
1663 ch = th = TILESIZE-1;
1665 if (tile & DF_LEGEND) {
1670 tile |= DF_IMMUTABLE;
1673 clip(dr, cx, cy, cw, ch);
1675 /* background needs erasing */
1676 draw_rect(dr, cx, cy, cw, ch,
1677 (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT :
1678 (x == y) ? COL_DIAGONAL : COL_BACKGROUND);
1681 if (tile & DF_DIVIDER_TOP)
1682 draw_rect(dr, cx, cy, cw, 1, COL_GRID);
1683 if (tile & DF_DIVIDER_BOT)
1684 draw_rect(dr, cx, cy+ch-1, cw, 1, COL_GRID);
1685 if (tile & DF_DIVIDER_LEFT)
1686 draw_rect(dr, cx, cy, 1, ch, COL_GRID);
1687 if (tile & DF_DIVIDER_RIGHT)
1688 draw_rect(dr, cx+cw-1, cy, 1, ch, COL_GRID);
1690 /* pencil-mode highlight */
1691 if (tile & DF_HIGHLIGHT_PENCIL) {
1695 coords[2] = cx+cw/2;
1698 coords[5] = cy+ch/2;
1699 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1702 /* new number needs drawing? */
1703 if (tile & DF_DIGIT_MASK) {
1705 str[0] = TOCHAR(tile & DF_DIGIT_MASK, ds->par.id);
1706 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1707 FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1708 (error & EF_LATIN) ? COL_ERROR :
1709 (tile & DF_IMMUTABLE) ? COL_GRID : COL_USER, str);
1711 if (error & EF_LEFT_MASK) {
1712 int a = (error >> (EF_LEFT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1713 int b = (error >> (EF_LEFT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1714 int c = (error >> (EF_LEFT_SHIFT ))&EF_DIGIT_MASK;
1716 sprintf(buf, "(%c%c)%c", TOCHAR(a, ds->par.id),
1717 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1718 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/6,
1719 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1722 if (error & EF_RIGHT_MASK) {
1723 int a = (error >> (EF_RIGHT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1724 int b = (error >> (EF_RIGHT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1725 int c = (error >> (EF_RIGHT_SHIFT ))&EF_DIGIT_MASK;
1727 sprintf(buf, "%c(%c%c)", TOCHAR(a, ds->par.id),
1728 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1729 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE - TILESIZE/6,
1730 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1737 int pw, ph, minph, pbest, fontsize;
1739 /* Count the pencil marks required. */
1740 for (i = 1, npencil = 0; i <= w; i++)
1741 if (pencil & (1 << i))
1748 * Determine the bounding rectangle within which we're going
1749 * to put the pencil marks.
1751 /* Start with the whole square */
1752 pl = tx + GRIDEXTRA;
1753 pr = pl + TILESIZE - GRIDEXTRA;
1754 pt = ty + GRIDEXTRA;
1755 pb = pt + TILESIZE - GRIDEXTRA;
1758 * We arrange our pencil marks in a grid layout, with
1759 * the number of rows and columns adjusted to allow the
1760 * maximum font size.
1762 * So now we work out what the grid size ought to be.
1767 for (pw = 3; pw < max(npencil,4); pw++) {
1770 ph = (npencil + pw - 1) / pw;
1771 ph = max(ph, minph);
1772 fw = (pr - pl) / (float)pw;
1773 fh = (pb - pt) / (float)ph;
1775 if (fs > bestsize) {
1782 ph = (npencil + pw - 1) / pw;
1783 ph = max(ph, minph);
1786 * Now we've got our grid dimensions, work out the pixel
1787 * size of a grid element, and round it to the nearest
1788 * pixel. (We don't want rounding errors to make the
1789 * grid look uneven at low pixel sizes.)
1791 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1794 * Centre the resulting figure in the square.
1796 pl = tx + (TILESIZE - fontsize * pw) / 2;
1797 pt = ty + (TILESIZE - fontsize * ph) / 2;
1800 * Now actually draw the pencil marks.
1802 for (i = 1, j = 0; i <= w; i++)
1803 if (pencil & (1 << i)) {
1804 int dx = j % pw, dy = j / pw;
1807 str[0] = TOCHAR(i, ds->par.id);
1808 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1809 pt + fontsize * (2*dy+1) / 2,
1810 FONT_VARIABLE, fontsize,
1811 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1819 draw_update(dr, cx, cy, cw, ch);
1822 static void game_redraw(drawing *dr, game_drawstate *ds,
1823 const game_state *oldstate, const game_state *state,
1824 int dir, const game_ui *ui,
1825 float animtime, float flashtime)
1827 int w = state->par.w /*, a = w*w */;
1832 * The initial contents of the window are not guaranteed and
1833 * can vary with front ends. To be on the safe side, all
1834 * games should start by drawing a big background-colour
1835 * rectangle covering the whole window.
1837 draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1840 * Big containing rectangle.
1842 draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1843 w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1846 draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1851 check_errors(state, ds->errtmp);
1854 * Construct a modified version of state->sequence which takes
1855 * into account an unfinished drag operation.
1863 for (i = j = 0; i < w; i++) {
1865 ds->sequence[i] = x;
1867 if (state->sequence[j] == x)
1869 ds->sequence[i] = state->sequence[j++];
1874 * Draw the table legend.
1876 for (x = 0; x < w; x++) {
1877 int sx = ds->sequence[x];
1878 long tile = (sx+1) | DF_LEGEND;
1879 if (ds->legend[x] != tile) {
1880 ds->legend[x] = tile;
1881 draw_tile(dr, ds, -1, x, tile, 0, 0);
1882 draw_tile(dr, ds, x, -1, tile, 0, 0);
1886 for (y = 0; y < w; y++) {
1887 int sy = ds->sequence[y];
1888 for (x = 0; x < w; x++) {
1889 long tile = 0L, pencil = 0L, error;
1890 int sx = ds->sequence[x];
1892 if (state->grid[sy*w+sx])
1893 tile = state->grid[sy*w+sx];
1895 pencil = (long)state->pencil[sy*w+sx];
1897 if (state->immutable[sy*w+sx])
1898 tile |= DF_IMMUTABLE;
1900 if ((ui->drag == 5 && ui->dragnum == sy) ||
1901 (ui->drag == 6 && ui->dragnum == sx)) {
1902 tile |= DF_HIGHLIGHT;
1903 } else if (ui->hshow) {
1904 int i = abs(x - ui->ohx);
1908 * When a diagonal multifill selection is shown,
1909 * we show it in its original grid position
1910 * regardless of in-progress row/col drags. Moving
1911 * every square about would be horrible.
1913 if (i >= 0 && i < ui->odn &&
1914 x == ui->ohx + i*ui->odx &&
1915 y == ui->ohy + i*ui->ody)
1919 * For a single square, we move its highlight
1920 * around with the drag.
1922 highlight = (ui->hx == sx && ui->hy == sy);
1925 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
1928 if (flashtime > 0 &&
1929 (flashtime <= FLASH_TIME/3 ||
1930 flashtime >= FLASH_TIME*2/3))
1931 tile |= DF_HIGHLIGHT; /* completion flash */
1933 if (y <= 0 || state->dividers[ds->sequence[y-1]] == sy)
1934 tile |= DF_DIVIDER_TOP;
1935 if (y+1 >= w || state->dividers[sy] == ds->sequence[y+1])
1936 tile |= DF_DIVIDER_BOT;
1937 if (x <= 0 || state->dividers[ds->sequence[x-1]] == sx)
1938 tile |= DF_DIVIDER_LEFT;
1939 if (x+1 >= w || state->dividers[sx] == ds->sequence[x+1])
1940 tile |= DF_DIVIDER_RIGHT;
1942 error = ds->errtmp[sy*w+sx];
1944 if (ds->tiles[y*w+x] != tile ||
1945 ds->pencil[y*w+x] != pencil ||
1946 ds->errors[y*w+x] != error) {
1947 ds->tiles[y*w+x] = tile;
1948 ds->pencil[y*w+x] = pencil;
1949 ds->errors[y*w+x] = error;
1950 draw_tile(dr, ds, x, y, tile, pencil, error);
1956 static float game_anim_length(const game_state *oldstate,
1957 const game_state *newstate, int dir, game_ui *ui)
1962 static float game_flash_length(const game_state *oldstate,
1963 const game_state *newstate, int dir, game_ui *ui)
1965 if (!oldstate->completed && newstate->completed &&
1966 !oldstate->cheated && !newstate->cheated)
1971 static int game_status(const game_state *state)
1973 return state->completed ? +1 : 0;
1976 static int game_timing_state(const game_state *state, game_ui *ui)
1978 if (state->completed)
1983 static void game_print_size(const game_params *params, float *x, float *y)
1988 * We use 9mm squares by default, like Solo.
1990 game_compute_size(params, 900, &pw, &ph);
1995 static void game_print(drawing *dr, const game_state *state, int tilesize)
1997 int w = state->par.w;
1998 int ink = print_mono_colour(dr, 0);
2001 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2002 game_drawstate ads, *ds = &ads;
2003 game_set_size(dr, ds, NULL, tilesize);
2008 print_line_width(dr, 3 * TILESIZE / 40);
2009 draw_rect_outline(dr, BORDER + LEGEND, BORDER + LEGEND,
2010 w*TILESIZE, w*TILESIZE, ink);
2015 for (x = 0; x < w; x++) {
2018 str[0] = TOCHAR(x+1, state->par.id);
2019 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
2020 BORDER + TILESIZE/2,
2021 FONT_VARIABLE, TILESIZE/2,
2022 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2023 draw_text(dr, BORDER + TILESIZE/2,
2024 BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
2025 FONT_VARIABLE, TILESIZE/2,
2026 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2032 for (x = 1; x < w; x++) {
2033 print_line_width(dr, TILESIZE / 40);
2034 draw_line(dr, BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND,
2035 BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND+w*TILESIZE, ink);
2037 for (y = 1; y < w; y++) {
2038 print_line_width(dr, TILESIZE / 40);
2039 draw_line(dr, BORDER+LEGEND, BORDER+LEGEND+y*TILESIZE,
2040 BORDER+LEGEND+w*TILESIZE, BORDER+LEGEND+y*TILESIZE, ink);
2046 for (y = 0; y < w; y++)
2047 for (x = 0; x < w; x++)
2048 if (state->grid[y*w+x]) {
2051 str[0] = TOCHAR(state->grid[y*w+x], state->par.id);
2052 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
2053 BORDER+LEGEND + y*TILESIZE + TILESIZE/2,
2054 FONT_VARIABLE, TILESIZE/2,
2055 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2060 #define thegame group
2063 const struct game thegame = {
2064 "Group", NULL, NULL,
2066 game_fetch_preset, NULL,
2071 TRUE, game_configure, custom_params,
2079 TRUE, game_can_format_as_text_now, game_text_format,
2087 PREFERRED_TILESIZE, game_compute_size, game_set_size,
2090 game_free_drawstate,
2095 TRUE, FALSE, game_print_size, game_print,
2096 FALSE, /* wants_statusbar */
2097 FALSE, game_timing_state,
2098 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
2101 #ifdef STANDALONE_SOLVER
2105 int main(int argc, char **argv)
2109 char *id = NULL, *desc;
2113 int ret, diff, really_show_working = FALSE;
2115 while (--argc > 0) {
2117 if (!strcmp(p, "-v")) {
2118 really_show_working = TRUE;
2119 } else if (!strcmp(p, "-g")) {
2121 } else if (*p == '-') {
2122 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2130 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2134 desc = strchr(id, ':');
2136 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2141 p = default_params();
2142 decode_params(p, id);
2143 err = validate_desc(p, desc);
2145 fprintf(stderr, "%s: %s\n", argv[0], err);
2148 s = new_game(NULL, p, desc);
2150 grid = snewn(p->w * p->w, digit);
2153 * When solving a Normal puzzle, we don't want to bother the
2154 * user with Hard-level deductions. For this reason, we grade
2155 * the puzzle internally before doing anything else.
2157 ret = -1; /* placate optimiser */
2158 solver_show_working = FALSE;
2159 for (diff = 0; diff < DIFFCOUNT; diff++) {
2160 memcpy(grid, s->grid, p->w * p->w);
2161 ret = solver(&s->par, grid, diff);
2166 if (diff == DIFFCOUNT) {
2168 printf("Difficulty rating: ambiguous\n");
2170 printf("Unable to find a unique solution\n");
2173 if (ret == diff_impossible)
2174 printf("Difficulty rating: impossible (no solution exists)\n");
2176 printf("Difficulty rating: %s\n", group_diffnames[ret]);
2178 solver_show_working = really_show_working;
2179 memcpy(grid, s->grid, p->w * p->w);
2180 ret = solver(&s->par, grid, diff);
2182 printf("Puzzle is inconsistent\n");
2184 memcpy(s->grid, grid, p->w * p->w);
2185 fputs(game_text_format(s), stdout);
2195 /* vim: set shiftwidth=4 tabstop=8: */