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)
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.
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) )
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))
86 unsigned char *immutable;
87 int *pencil; /* bitmaps using bits 1<<1..1<<n */
88 int completed, cheated;
89 digit *sequence; /* sequence of group elements shown */
92 * This array indicates thick lines separating rows and columns
93 * placed and unplaced manually by the user as a visual aid, e.g.
94 * to delineate a subgroup and its cosets.
96 * When a line is placed, it's deemed to be between the two
97 * particular group elements that are on either side of it at the
98 * time; dragging those two away from each other automatically
99 * gets rid of the line. Hence, for a given element i, dividers[i]
100 * is either -1 (indicating no divider to the right of i), or some
101 * other element (indicating a divider to the right of i iff that
102 * element is the one right of it). These are eagerly cleared
105 int *dividers; /* thick lines between rows/cols */
108 static game_params *default_params(void)
110 game_params *ret = snew(game_params);
113 ret->diff = DIFF_NORMAL;
119 const static struct game_params group_presets[] = {
120 { 6, DIFF_NORMAL, TRUE },
121 { 6, DIFF_NORMAL, FALSE },
122 { 8, DIFF_NORMAL, TRUE },
123 { 8, DIFF_NORMAL, FALSE },
124 { 8, DIFF_HARD, TRUE },
125 { 8, DIFF_HARD, FALSE },
126 { 12, DIFF_NORMAL, TRUE },
129 static int game_fetch_preset(int i, char **name, game_params **params)
134 if (i < 0 || i >= lenof(group_presets))
137 ret = snew(game_params);
138 *ret = group_presets[i]; /* structure copy */
140 sprintf(buf, "%dx%d %s%s", ret->w, ret->w, group_diffnames[ret->diff],
141 ret->id ? "" : ", identity hidden");
148 static void free_params(game_params *params)
153 static game_params *dup_params(const game_params *params)
155 game_params *ret = snew(game_params);
156 *ret = *params; /* structure copy */
160 static void decode_params(game_params *params, char const *string)
162 char const *p = string;
165 while (*p && isdigit((unsigned char)*p)) p++;
166 params->diff = DIFF_NORMAL;
173 params->diff = DIFFCOUNT+1; /* ...which is invalid */
175 for (i = 0; i < DIFFCOUNT; i++) {
176 if (*p == group_diffchars[i])
181 } else if (*p == 'i') {
185 /* unrecognised character */
191 static char *encode_params(const game_params *params, int full)
195 sprintf(ret, "%d", params->w);
197 sprintf(ret + strlen(ret), "d%c", group_diffchars[params->diff]);
199 sprintf(ret + strlen(ret), "i");
204 static config_item *game_configure(const game_params *params)
209 ret = snewn(4, config_item);
211 ret[0].name = "Grid size";
212 ret[0].type = C_STRING;
213 sprintf(buf, "%d", params->w);
214 ret[0].sval = dupstr(buf);
217 ret[1].name = "Difficulty";
218 ret[1].type = C_CHOICES;
219 ret[1].sval = DIFFCONFIG;
220 ret[1].ival = params->diff;
222 ret[2].name = "Show identity";
223 ret[2].type = C_BOOLEAN;
225 ret[2].ival = params->id;
235 static game_params *custom_params(const config_item *cfg)
237 game_params *ret = snew(game_params);
239 ret->w = atoi(cfg[0].sval);
240 ret->diff = cfg[1].ival;
241 ret->id = cfg[2].ival;
246 static char *validate_params(const game_params *params, int full)
248 if (params->w < 3 || params->w > 26)
249 return "Grid size must be between 3 and 26";
250 if (params->diff >= DIFFCOUNT)
251 return "Unknown difficulty rating";
252 if (!params->id && params->diff == DIFF_TRIVIAL) {
254 * We can't have a Trivial-difficulty puzzle (i.e. latin
255 * square deductions only) without a clear identity, because
256 * identityless puzzles always have two rows and two columns
257 * entirely blank, and no latin-square deduction permits the
258 * distinguishing of two such rows.
260 return "Trivial puzzles must have an identity";
262 if (!params->id && params->w == 3) {
264 * We can't have a 3x3 puzzle without an identity either,
265 * because 3x3 puzzles can't ever be harder than Trivial
266 * (there are no 3x3 latin squares which aren't also valid
267 * group tables, so enabling group-based deductions doesn't
268 * rule out any possible solutions) and - as above - Trivial
269 * puzzles can't not have an identity.
271 return "3x3 puzzles must have an identity";
276 /* ----------------------------------------------------------------------
280 static int solver_normal(struct latin_solver *solver, void *vctx)
283 #ifdef STANDALONE_SOLVER
284 char **names = solver->names;
286 digit *grid = solver->grid;
290 * Deduce using associativity: (ab)c = a(bc).
292 * So we pick any a,b,c we like; then if we know ab, bc, and
293 * (ab)c we can fill in a(bc).
295 for (i = 1; i < w; i++)
296 for (j = 1; j < w; j++)
297 for (k = 1; k < w; k++) {
298 if (!grid[i*w+j] || !grid[j*w+k])
300 if (grid[(grid[i*w+j]-1)*w+k] &&
301 !grid[i*w+(grid[j*w+k]-1)]) {
302 int x = grid[j*w+k]-1, y = i;
303 int n = grid[(grid[i*w+j]-1)*w+k];
304 #ifdef STANDALONE_SOLVER
305 if (solver_show_working) {
306 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
307 solver_recurse_depth*4, "",
308 names[i], names[j], names[k],
309 names[grid[i*w+j]-1], names[k],
310 names[i], names[grid[j*w+k]-1]);
311 printf("%*s placing %s at (%d,%d)\n",
312 solver_recurse_depth*4, "",
313 names[n-1], x+1, y+1);
316 if (solver->cube[(x*w+y)*w+n-1]) {
317 latin_solver_place(solver, x, y, n);
320 #ifdef STANDALONE_SOLVER
321 if (solver_show_working)
322 printf("%*s contradiction!\n",
323 solver_recurse_depth*4, "");
328 if (!grid[(grid[i*w+j]-1)*w+k] &&
329 grid[i*w+(grid[j*w+k]-1)]) {
330 int x = k, y = grid[i*w+j]-1;
331 int n = grid[i*w+(grid[j*w+k]-1)];
332 #ifdef STANDALONE_SOLVER
333 if (solver_show_working) {
334 printf("%*sassociativity on %s,%s,%s: %s*%s = %s*%s\n",
335 solver_recurse_depth*4, "",
336 names[i], names[j], names[k],
337 names[grid[i*w+j]-1], names[k],
338 names[i], names[grid[j*w+k]-1]);
339 printf("%*s placing %s at (%d,%d)\n",
340 solver_recurse_depth*4, "",
341 names[n-1], x+1, y+1);
344 if (solver->cube[(x*w+y)*w+n-1]) {
345 latin_solver_place(solver, x, y, n);
348 #ifdef STANDALONE_SOLVER
349 if (solver_show_working)
350 printf("%*s contradiction!\n",
351 solver_recurse_depth*4, "");
361 #define SOLVER(upper,title,func,lower) func,
362 static usersolver_t const group_solvers[] = { DIFFLIST(SOLVER) };
364 static int solver(const game_params *params, digit *grid, int maxdiff)
368 struct latin_solver solver;
369 #ifdef STANDALONE_SOLVER
370 char *p, text[100], *names[50];
374 latin_solver_alloc(&solver, grid, w);
375 #ifdef STANDALONE_SOLVER
376 for (i = 0, p = text; i < w; i++) {
378 *p++ = TOCHAR(i+1, params->id);
381 solver.names = names;
384 ret = latin_solver_main(&solver, maxdiff,
385 DIFF_TRIVIAL, DIFF_HARD, DIFF_EXTREME,
386 DIFF_EXTREME, DIFF_UNREASONABLE,
387 group_solvers, NULL, NULL, NULL);
389 latin_solver_free(&solver);
394 /* ----------------------------------------------------------------------
398 static char *encode_grid(char *desc, digit *grid, int area)
404 for (i = 0; i <= area; i++) {
405 int n = (i < area ? grid[i] : -1);
412 int c = 'a' - 1 + run;
416 run -= c - ('a' - 1);
420 * If there's a number in the very top left or
421 * bottom right, there's no point putting an
422 * unnecessary _ before or after it.
424 if (p > desc && n > 0)
428 p += sprintf(p, "%d", n);
435 /* ----- data generated by group.gap begins ----- */
438 unsigned long autosize;
444 const struct group *groups;
447 static const struct group groupdata[] = {
454 {6L, 4, 2, "BADC" "CDAB"},
458 {6L, 6, 2, "CFEBAD" "BADCFE"},
459 {2L, 6, 1, "DCFEBA"},
461 {6L, 7, 1, "BCDEFGA"},
463 {4L, 8, 1, "BCEFDGHA"},
464 {8L, 8, 2, "BDEFGAHC" "EGBHDCFA"},
465 {8L, 8, 2, "EGBHDCFA" "BAEFCDHG"},
466 {24L, 8, 2, "BDEFGAHC" "CHDGBEAF"},
467 {168L, 8, 3, "BAEFCDHG" "CEAGBHDF" "DFGAHBCE"},
469 {6L, 9, 1, "BDECGHFIA"},
470 {48L, 9, 2, "BDEAGHCIF" "CEFGHAIBD"},
472 {20L, 10, 2, "CJEBGDIFAH" "BADCFEHGJI"},
473 {4L, 10, 1, "DCFEHGJIBA"},
475 {10L, 11, 1, "BCDEFGHIJKA"},
477 {12L, 12, 2, "GLDKJEHCBIAF" "BCEFAGIJDKLH"},
478 {4L, 12, 1, "EHIJKCBLDGFA"},
479 {24L, 12, 2, "BEFGAIJKCDLH" "FJBKHLEGDCIA"},
480 {12L, 12, 2, "GLDKJEHCBIAF" "BAEFCDIJGHLK"},
481 {12L, 12, 2, "FDIJGHLBKAEC" "GIDKFLHCJEAB"},
483 {12L, 13, 1, "BCDEFGHIJKLMA"},
485 {42L, 14, 2, "ELGNIBKDMFAHCJ" "BADCFEHGJILKNM"},
486 {6L, 14, 1, "FEHGJILKNMBADC"},
488 {8L, 15, 1, "EGHCJKFMNIOBLDA"},
490 {8L, 16, 1, "MKNPFOADBGLCIEHJ"},
491 {96L, 16, 2, "ILKCONFPEDJHGMAB" "BDFGHIAKLMNCOEPJ"},
492 {32L, 16, 2, "MIHPFDCONBLAKJGE" "BEFGHJKALMNOCDPI"},
493 {32L, 16, 2, "IFACOGLMDEJBNPKH" "BEFGHJKALMNOCDPI"},
494 {16L, 16, 2, "MOHPFKCINBLADJGE" "BDFGHIEKLMNJOAPC"},
495 {16L, 16, 2, "MIHPFDJONBLEKCGA" "BDFGHIEKLMNJOAPC"},
496 {32L, 16, 2, "MOHPFDCINBLEKJGA" "BAFGHCDELMNIJKPO"},
497 {16L, 16, 2, "MIHPFKJONBLADCGE" "GDPHNOEKFLBCIAMJ"},
498 {32L, 16, 2, "MIBPFDJOGHLEKCNA" "CLEIJGMPKAOHNFDB"},
500 "MCHPFAIJNBLDEOGK" "BEFGHJKALMNOCDPI" "GKLBNOEDFPHJIAMC"},
501 {64L, 16, 3, "MCHPFAIJNBLDEOGK" "LOGFPKJIBNMEDCHA" "CMAIJHPFDEONBLKG"},
503 "IPKCOGMLEDJBNFAH" "BEFGHJKALMNOCDPI" "CMEIJBPFKAOGHLDN"},
504 {48L, 16, 3, "IPDJONFLEKCBGMAH" "FJBLMEOCGHPKAIND" "DGIEKLHNJOAMPBCF"},
506 "EHJKAMNBOCDPFGIL" "BAFGHCDELMNIJKPO" "CFAIJBLMDEOGHPKN"
509 {16L, 17, 1, "EFGHIJKLMNOPQABCD"},
511 {54L, 18, 2, "MKIQOPNAGLRECDBJHF" "BAEFCDJKLGHIOPMNRQ"},
512 {6L, 18, 1, "ECJKGHFOPDMNLRIQBA"},
513 {12L, 18, 2, "ECJKGHBOPAMNFRDQLI" "KNOPQCFREIGHLJAMBD"},
515 "IFNAKLQCDOPBGHREMJ" "NOQCFRIGHKLJAMPBDE" "BAEFCDJKLGHIOPMNRQ"},
516 {48L, 18, 2, "ECJKGHBOPAMNFRDQLI" "FDKLHIOPBMNAREQCJG"},
518 {18L, 19, 1, "EFGHIJKLMNOPQRSABCD"},
520 {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "EABICDFMGHJQKLNTOPRS"},
521 {8L, 20, 1, "EHIJLCMNPGQRSKBTDOFA"},
522 {20L, 20, 2, "DJSHQNCLTRGPEBKAIFOM" "EABICDFMGHJQKLNTOPRS"},
523 {40L, 20, 2, "GTDKREHOBILSFMPCJQAN" "ECBIAGFMDKJQHONTLSRP"},
524 {24L, 20, 2, "IGFMDKJQHONTLSREPCBA" "FDIJGHMNKLQROPTBSAEC"},
526 {42L, 21, 2, "ITLSBOUERDHAGKCJNFMQP" "EJHLMKOPNRSQAUTCDBFGI"},
527 {12L, 21, 1, "EGHCJKFMNIPQLSTOUBRDA"},
529 {110L, 22, 2, "ETGVIBKDMFOHQJSLUNAPCR" "BADCFEHGJILKNMPORQTSVU"},
530 {10L, 22, 1, "FEHGJILKNMPORQTSVUBADC"},
532 {22L, 23, 1, "EFGHIJKLMNOPQRSTUVWABCD"},
534 {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "HRNOPSWCTUVBLDIJXFGAKQME"},
535 {8L, 24, 1, "MQBTUDRWFGHXJELINOPKSAVC"},
536 {24L, 24, 2, "IOQRBEUVFWGHKLAXMNPSCDTJ" "NJXOVGDKSMTFIPQELCURBWAH"},
537 {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "HSNOPWLDTUVBRIAKXFGCQEMJ"},
538 {24L, 24, 2, "QXEJWPUMKLRIVBFTSACGHNDO" "TWHNXLRIOPUMSACQVBFDEJGK"},
539 {48L, 24, 2, "QUEJWVXFKLRIPGMNSACBOTDH" "BAFGHCDEMNOPIJKLTUVQRSXW"},
541 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
542 "HSNOPWLDTUVBRIAKXFGCQEMJ"},
544 "QUKJWPXFESRIVBMNLDCGHTAO" "JXEQRVUMKLWCPGFTSAIBONDH"
545 "TRONXLWCHVUMSAIJPGFDEQBK"},
546 {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "VKXHOQASNTPBCWDEUFGIJLMR"},
547 {16L, 24, 2, "MRGTULWIOPFXSDJQBVNEKCHA" "RMLWIGTUSDJQOPFXEKCBVNAH"},
548 {48L, 24, 2, "IULQRGXMSDCWOPNTEKJBVFAH" "GLMOPRSDTUBVWIEKFXHJQANC"},
549 {24L, 24, 2, "UJPXMRCSNHGTLWIKFVBEDQOA" "NRUFVLWIPXMOJEDQHGTCSABK"},
550 {24L, 24, 2, "MIBTUAQRFGHXCDEWNOPJKLVS" "OKXVFWSCGUTNDRQJBPMALIHE"},
552 "QXKJWVUMESRIPGFTLDCBONAH" "JUEQRPXFKLWCVBMNSAIGHTDO"
553 "BAFGHCDEMNOPIJKLTUVQRSXW"},
555 "QTKJWONXESRIHVUMLDCPGFAB" "JNEQRHTUKLWCOPXFSAIVBMDG"
556 "HENOPJKLTUVBQRSAXFGWCDMI"},
558 {20L, 25, 1, "EHILMNPQRSFTUVBJWXDOYGAKC"},
559 {480L, 25, 2, "EHILMNPQRSCTUVBFWXDJYGOKA" "BDEGHIKLMNAPQRSCTUVFWXJYO"},
562 "EXGZIBKDMFOHQJSLUNWPYRATCV" "BADCFEHGJILKNMPORQTSVUXWZY"},
563 {12L, 26, 1, "FEHGJILKNMPORQTSVUXWZYBADC"},
566 static const struct groups groups[] = {
567 {0, NULL}, /* trivial case: 0 */
568 {0, NULL}, /* trivial case: 1 */
569 {1, groupdata + 0}, /* 2 */
570 {1, groupdata + 1}, /* 3 */
571 {2, groupdata + 2}, /* 4 */
572 {1, groupdata + 4}, /* 5 */
573 {2, groupdata + 5}, /* 6 */
574 {1, groupdata + 7}, /* 7 */
575 {5, groupdata + 8}, /* 8 */
576 {2, groupdata + 13}, /* 9 */
577 {2, groupdata + 15}, /* 10 */
578 {1, groupdata + 17}, /* 11 */
579 {5, groupdata + 18}, /* 12 */
580 {1, groupdata + 23}, /* 13 */
581 {2, groupdata + 24}, /* 14 */
582 {1, groupdata + 26}, /* 15 */
583 {14, groupdata + 27}, /* 16 */
584 {1, groupdata + 41}, /* 17 */
585 {5, groupdata + 42}, /* 18 */
586 {1, groupdata + 47}, /* 19 */
587 {5, groupdata + 48}, /* 20 */
588 {2, groupdata + 53}, /* 21 */
589 {2, groupdata + 55}, /* 22 */
590 {1, groupdata + 57}, /* 23 */
591 {15, groupdata + 58}, /* 24 */
592 {2, groupdata + 73}, /* 25 */
593 {2, groupdata + 75}, /* 26 */
596 /* ----- data generated by group.gap ends ----- */
598 static char *new_game_desc(const game_params *params, random_state *rs,
599 char **aux, int interactive)
601 int w = params->w, a = w*w;
602 digit *grid, *soln, *soln2;
605 int diff = params->diff;
606 const struct group *group;
610 * Difficulty exceptions: some combinations of size and
611 * difficulty cannot be satisfied, because all puzzles of at
612 * most that difficulty are actually even easier.
614 * Remember to re-test this whenever a change is made to the
617 * I tested it using the following shell command:
619 for d in t n h x u; do
622 echo -n "./group --generate 1 ${i}d${d}${id}: "
623 perl -e 'alarm 30; exec @ARGV' \
624 ./group --generate 1 ${i}d${d}${id} >/dev/null && echo ok
629 * Of course, it's better to do that after taking the exceptions
630 * _out_, so as to detect exceptions that should be removed as
631 * well as those which should be added.
633 if (w < 5 && diff == DIFF_UNREASONABLE)
635 if ((w < 5 || ((w == 6 || w == 8) && params->id)) && diff == DIFF_EXTREME)
637 if ((w < 6 || (w == 6 && params->id)) && diff == DIFF_HARD)
639 if ((w < 4 || (w == 4 && params->id)) && diff == DIFF_NORMAL)
642 grid = snewn(a, digit);
643 soln = snewn(a, digit);
644 soln2 = snewn(a, digit);
645 indices = snewn(a, int);
649 * Construct a valid group table, by picking a group from
650 * the above data table, decompressing it into a full
651 * representation by BFS, and then randomly permuting its
652 * non-identity elements.
654 * We build the canonical table in 'soln' (and use 'grid' as
655 * our BFS queue), then transfer the table into 'grid'
656 * having shuffled the rows.
659 assert(w < lenof(groups));
660 group = groups[w].groups + random_upto(rs, groups[w].ngroups);
661 assert(group->order == w);
663 for (i = 0; i < w; i++)
671 row = soln + (i-1)*w;
673 for (j = 0; j < group->ngens; j++) {
675 const char *gen = group->gens + j*w;
678 * Apply each group generator to row, constructing a
681 nri = gen[row[0]-1] - 'A' + 1; /* which row is it? */
682 newrow = soln + (nri-1)*w;
683 if (!newrow[0]) { /* not done yet */
684 for (k = 0; k < w; k++)
685 newrow[k] = gen[row[k]-1] - 'A' + 1;
690 /* That's got the canonical table. Now shuffle it. */
691 for (i = 0; i < w; i++)
693 if (params->id) /* do we shuffle in the identity? */
694 shuffle(soln2+1, w-1, sizeof(*soln2), rs);
696 shuffle(soln2, w, sizeof(*soln2), rs);
697 for (i = 0; i < w; i++)
698 for (j = 0; j < w; j++)
699 grid[(soln2[i])*w+(soln2[j])] = soln2[soln[i*w+j]-1]+1;
702 * Remove entries one by one while the puzzle is still
703 * soluble at the appropriate difficulty level.
705 memcpy(soln, grid, a);
708 * Start by blanking the entire identity row and column,
709 * and also another row and column so that the player
710 * can't trivially determine which element is the
714 j = 1 + random_upto(rs, w-1); /* pick a second row/col to blank */
715 for (i = 0; i < w; i++) {
716 grid[(soln2[0])*w+i] = grid[i*w+(soln2[0])] = 0;
717 grid[(soln2[j])*w+i] = grid[i*w+(soln2[j])] = 0;
720 memcpy(soln2, grid, a);
721 if (solver(params, soln2, diff) > diff)
722 continue; /* go round again if that didn't work */
726 for (i = (params->id ? 1 : 0); i < w; i++)
727 for (j = (params->id ? 1 : 0); j < w; j++)
729 indices[k++] = i*w+j;
730 shuffle(indices, k, sizeof(*indices), rs);
732 for (i = 0; i < k; i++) {
733 memcpy(soln2, grid, a);
734 soln2[indices[i]] = 0;
735 if (solver(params, soln2, diff) <= diff)
736 grid[indices[i]] = 0;
740 * Make sure the puzzle isn't too easy.
743 memcpy(soln2, grid, a);
744 if (solver(params, soln2, diff-1) < diff)
745 continue; /* go round and try again */
755 * Encode the puzzle description.
757 desc = snewn(a*20, char);
758 p = encode_grid(desc, grid, a);
760 desc = sresize(desc, p - desc, char);
763 * Encode the solution.
765 *aux = snewn(a+2, char);
767 for (i = 0; i < a; i++)
768 (*aux)[i+1] = TOCHAR(soln[i], params->id);
779 /* ----------------------------------------------------------------------
783 static char *validate_grid_desc(const char **pdesc, int range, int area)
785 const char *desc = *pdesc;
787 while (*desc && *desc != ',') {
789 if (n >= 'a' && n <= 'z') {
790 squares += n - 'a' + 1;
791 } else if (n == '_') {
793 } else if (n > '0' && n <= '9') {
794 int val = atoi(desc-1);
795 if (val < 1 || val > range)
796 return "Out-of-range number in game description";
798 while (*desc >= '0' && *desc <= '9')
801 return "Invalid character in game description";
805 return "Not enough data to fill grid";
808 return "Too much data to fit in grid";
813 static char *validate_desc(const game_params *params, const char *desc)
815 int w = params->w, a = w*w;
816 const char *p = desc;
818 return validate_grid_desc(&p, w, a);
821 static const char *spec_to_grid(const char *desc, digit *grid, int area)
824 while (*desc && *desc != ',') {
826 if (n >= 'a' && n <= 'z') {
827 int run = n - 'a' + 1;
828 assert(i + run <= area);
831 } else if (n == '_') {
833 } else if (n > '0' && n <= '9') {
835 grid[i++] = atoi(desc-1);
836 while (*desc >= '0' && *desc <= '9')
839 assert(!"We can't get here");
846 static game_state *new_game(midend *me, const game_params *params,
849 int w = params->w, a = w*w;
850 game_state *state = snew(game_state);
853 state->par = *params; /* structure copy */
854 state->grid = snewn(a, digit);
855 state->immutable = snewn(a, unsigned char);
856 state->pencil = snewn(a, int);
857 for (i = 0; i < a; i++) {
859 state->immutable[i] = 0;
860 state->pencil[i] = 0;
862 state->sequence = snewn(w, digit);
863 state->dividers = snewn(w, int);
864 for (i = 0; i < w; i++) {
865 state->sequence[i] = i;
866 state->dividers[i] = -1;
869 desc = spec_to_grid(desc, state->grid, a);
870 for (i = 0; i < a; i++)
871 if (state->grid[i] != 0)
872 state->immutable[i] = TRUE;
874 state->completed = state->cheated = FALSE;
879 static game_state *dup_game(const game_state *state)
881 int w = state->par.w, a = w*w;
882 game_state *ret = snew(game_state);
884 ret->par = state->par; /* structure copy */
886 ret->grid = snewn(a, digit);
887 ret->immutable = snewn(a, unsigned char);
888 ret->pencil = snewn(a, int);
889 ret->sequence = snewn(w, digit);
890 ret->dividers = snewn(w, int);
891 memcpy(ret->grid, state->grid, a*sizeof(digit));
892 memcpy(ret->immutable, state->immutable, a*sizeof(unsigned char));
893 memcpy(ret->pencil, state->pencil, a*sizeof(int));
894 memcpy(ret->sequence, state->sequence, w*sizeof(digit));
895 memcpy(ret->dividers, state->dividers, w*sizeof(int));
897 ret->completed = state->completed;
898 ret->cheated = state->cheated;
903 static void free_game(game_state *state)
906 sfree(state->immutable);
907 sfree(state->pencil);
908 sfree(state->sequence);
912 static char *solve_game(const game_state *state, const game_state *currstate,
913 const char *aux, char **error)
915 int w = state->par.w, a = w*w;
923 soln = snewn(a, digit);
924 memcpy(soln, state->grid, a*sizeof(digit));
926 ret = solver(&state->par, soln, DIFFCOUNT-1);
928 if (ret == diff_impossible) {
929 *error = "No solution exists for this puzzle";
931 } else if (ret == diff_ambiguous) {
932 *error = "Multiple solutions exist for this puzzle";
935 out = snewn(a+2, char);
937 for (i = 0; i < a; i++)
938 out[i+1] = TOCHAR(soln[i], state->par.id);
946 static int game_can_format_as_text_now(const game_params *params)
951 static char *game_text_format(const game_state *state)
953 int w = state->par.w;
957 ret = snewn(2*w*w+1, char); /* leave room for terminating NUL */
960 for (y = 0; y < w; y++) {
961 for (x = 0; x < w; x++) {
962 digit d = state->grid[y*w+x];
967 ch = TOCHAR(d, state->par.id);
979 assert(p - ret == 2*w*w);
986 * These are the coordinates of the currently highlighted
987 * square on the grid, if hshow = 1.
991 * This indicates whether the current highlight is a
992 * pencil-mark one or a real one.
996 * This indicates whether or not we're showing the highlight
997 * (used to be hx = hy = -1); important so that when we're
998 * using the cursor keys it doesn't keep coming back at a
999 * fixed position. When hshow = 1, pressing a valid number
1000 * or letter key or Space will enter that number or letter in the grid.
1004 * This indicates whether we're using the highlight as a cursor;
1005 * it means that it doesn't vanish on a keypress, and that it is
1006 * allowed on immutable squares.
1010 * This indicates whether we're dragging a table header to
1011 * reposition an entire row or column.
1013 int drag; /* 0=none 1=row 2=col */
1014 int dragnum; /* element being dragged */
1015 int dragpos; /* its current position */
1019 static game_ui *new_ui(const game_state *state)
1021 game_ui *ui = snew(game_ui);
1023 ui->hx = ui->hy = 0;
1024 ui->hpencil = ui->hshow = ui->hcursor = 0;
1030 static void free_ui(game_ui *ui)
1035 static char *encode_ui(const game_ui *ui)
1040 static void decode_ui(game_ui *ui, const char *encoding)
1044 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1045 const game_state *newstate)
1047 int w = newstate->par.w;
1049 * We prevent pencil-mode highlighting of a filled square, unless
1050 * we're using the cursor keys. So if the user has just filled in
1051 * a square which we had a pencil-mode highlight in (by Undo, or
1052 * by Redo, or by Solve), then we cancel the highlight.
1054 if (ui->hshow && ui->hpencil && !ui->hcursor &&
1055 newstate->grid[ui->hy * w + ui->hx] != 0) {
1060 #define PREFERRED_TILESIZE 48
1061 #define TILESIZE (ds->tilesize)
1062 #define BORDER (TILESIZE / 2)
1063 #define LEGEND (TILESIZE)
1064 #define GRIDEXTRA max((TILESIZE / 32),1)
1065 #define COORD(x) ((x)*TILESIZE + BORDER + LEGEND)
1066 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER-LEGEND)) / TILESIZE - 1)
1068 #define FLASH_TIME 0.4F
1070 #define DF_DIVIDER_TOP 0x1000
1071 #define DF_DIVIDER_BOT 0x2000
1072 #define DF_DIVIDER_LEFT 0x4000
1073 #define DF_DIVIDER_RIGHT 0x8000
1074 #define DF_HIGHLIGHT 0x0400
1075 #define DF_HIGHLIGHT_PENCIL 0x0200
1076 #define DF_IMMUTABLE 0x0100
1077 #define DF_LEGEND 0x0080
1078 #define DF_DIGIT_MASK 0x001F
1080 #define EF_DIGIT_SHIFT 5
1081 #define EF_DIGIT_MASK ((1 << EF_DIGIT_SHIFT) - 1)
1082 #define EF_LEFT_SHIFT 0
1083 #define EF_RIGHT_SHIFT (3*EF_DIGIT_SHIFT)
1084 #define EF_LEFT_MASK ((1UL << (3*EF_DIGIT_SHIFT)) - 1UL)
1085 #define EF_RIGHT_MASK (EF_LEFT_MASK << EF_RIGHT_SHIFT)
1086 #define EF_LATIN (1UL << (6*EF_DIGIT_SHIFT))
1088 struct game_drawstate {
1092 long *tiles, *legend, *pencil, *errors;
1097 static int check_errors(const game_state *state, long *errors)
1099 int w = state->par.w, a = w*w;
1100 digit *grid = state->grid;
1101 int i, j, k, x, y, errs = FALSE;
1104 * To verify that we have a valid group table, it suffices to
1105 * test latin-square-hood and associativity only. All the other
1106 * group axioms follow from those two.
1110 * Associativity is given; closure is obvious from latin-
1111 * square-hood. We need to show that an identity exists and that
1112 * every element has an inverse.
1114 * Identity: take any element a. There will be some element e
1115 * such that ea=a (in a latin square, every element occurs in
1116 * every row and column, so a must occur somewhere in the a
1117 * column, say on row e). For any other element b, there must
1118 * exist x such that ax=b (same argument from latin-square-hood
1119 * again), and then associativity gives us eb = e(ax) = (ea)x =
1120 * ax = b. Hence eb=b for all b, i.e. e is a left-identity. A
1121 * similar argument tells us that there must be some f which is
1122 * a right-identity, and then we show they are the same element
1123 * by observing that ef must simultaneously equal e and equal f.
1125 * Inverses: given any a, by the latin-square argument again,
1126 * there must exist p and q such that pa=e and aq=e (i.e. left-
1127 * and right-inverses). We can show these are equal by
1128 * associativity: p = pe = p(aq) = (pa)q = eq = q. []
1132 for (i = 0; i < a; i++)
1135 for (y = 0; y < w; y++) {
1136 unsigned long mask = 0, errmask = 0;
1137 for (x = 0; x < w; x++) {
1138 unsigned long bit = 1UL << grid[y*w+x];
1139 errmask |= (mask & bit);
1143 if (mask != (1 << (w+1)) - (1 << 1)) {
1147 for (x = 0; x < w; x++)
1148 if (errmask & (1UL << grid[y*w+x]))
1149 errors[y*w+x] |= EF_LATIN;
1154 for (x = 0; x < w; x++) {
1155 unsigned long mask = 0, errmask = 0;
1156 for (y = 0; y < w; y++) {
1157 unsigned long bit = 1UL << grid[y*w+x];
1158 errmask |= (mask & bit);
1162 if (mask != (1 << (w+1)) - (1 << 1)) {
1166 for (y = 0; y < w; y++)
1167 if (errmask & (1UL << grid[y*w+x]))
1168 errors[y*w+x] |= EF_LATIN;
1173 for (i = 1; i < w; i++)
1174 for (j = 1; j < w; j++)
1175 for (k = 1; k < w; k++)
1176 if (grid[i*w+j] && grid[j*w+k] &&
1177 grid[(grid[i*w+j]-1)*w+k] &&
1178 grid[i*w+(grid[j*w+k]-1)] &&
1179 grid[(grid[i*w+j]-1)*w+k] != grid[i*w+(grid[j*w+k]-1)]) {
1181 int a = i+1, b = j+1, c = k+1;
1182 int ab = grid[i*w+j], bc = grid[j*w+k];
1183 int left = (ab-1)*w+(c-1), right = (a-1)*w+(bc-1);
1185 * If the appropriate error slot is already
1186 * used for one of the squares, we don't
1187 * fill either of them.
1189 if (!(errors[left] & EF_LEFT_MASK) &&
1190 !(errors[right] & EF_RIGHT_MASK)) {
1193 err = (err << EF_DIGIT_SHIFT) | b;
1194 err = (err << EF_DIGIT_SHIFT) | c;
1195 errors[left] |= err << EF_LEFT_SHIFT;
1196 errors[right] |= err << EF_RIGHT_SHIFT;
1205 static int find_in_sequence(digit *seq, int len, digit n)
1209 for (i = 0; i < len; i++)
1213 assert(!"Should never get here");
1217 static char *interpret_move(const game_state *state, game_ui *ui,
1218 const game_drawstate *ds,
1219 int x, int y, int button)
1221 int w = state->par.w;
1225 button &= ~MOD_MASK;
1231 if (IS_MOUSE_DRAG(button)) {
1232 int tcoord = ((ui->drag &~ 4) == 1 ? ty : tx);
1233 ui->drag |= 4; /* some movement has happened */
1234 if (tcoord >= 0 && tcoord < w) {
1235 ui->dragpos = tcoord;
1238 } else if (IS_MOUSE_RELEASE(button)) {
1240 ui->drag = 0; /* end drag */
1241 if (state->sequence[ui->dragpos] == ui->dragnum)
1242 return ""; /* drag was a no-op overall */
1243 sprintf(buf, "D%d,%d", ui->dragnum, ui->dragpos);
1246 ui->drag = 0; /* end 'drag' */
1247 if (ui->edgepos > 0 && ui->edgepos < w) {
1248 sprintf(buf, "V%d,%d",
1249 state->sequence[ui->edgepos-1],
1250 state->sequence[ui->edgepos]);
1253 return ""; /* no-op */
1256 } else if (IS_MOUSE_DOWN(button)) {
1257 if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1258 tx = state->sequence[tx];
1259 ty = state->sequence[ty];
1260 if (button == LEFT_BUTTON) {
1261 if (tx == ui->hx && ty == ui->hy &&
1262 ui->hshow && ui->hpencil == 0) {
1267 ui->hshow = !state->immutable[ty*w+tx];
1271 return ""; /* UI activity occurred */
1273 if (button == RIGHT_BUTTON) {
1275 * Pencil-mode highlighting for non filled squares.
1277 if (state->grid[ty*w+tx] == 0) {
1278 if (tx == ui->hx && ty == ui->hy &&
1279 ui->hshow && ui->hpencil) {
1291 return ""; /* UI activity occurred */
1293 } else if (tx >= 0 && tx < w && ty == -1) {
1295 ui->dragnum = state->sequence[tx];
1297 ui->edgepos = FROMCOORD(x + TILESIZE/2);
1299 } else if (ty >= 0 && ty < w && tx == -1) {
1301 ui->dragnum = state->sequence[ty];
1303 ui->edgepos = FROMCOORD(y + TILESIZE/2);
1308 if (IS_CURSOR_MOVE(button)) {
1309 int cx = find_in_sequence(state->sequence, w, ui->hx);
1310 int cy = find_in_sequence(state->sequence, w, ui->hy);
1311 move_cursor(button, &cx, &cy, w, w, 0);
1312 ui->hx = state->sequence[cx];
1313 ui->hy = state->sequence[cy];
1314 ui->hshow = ui->hcursor = 1;
1318 (button == CURSOR_SELECT)) {
1319 ui->hpencil = 1 - ui->hpencil;
1325 ((ISCHAR(button) && FROMCHAR(button, state->par.id) <= w) ||
1326 button == CURSOR_SELECT2 || button == '\b')) {
1327 int n = FROMCHAR(button, state->par.id);
1328 if (button == CURSOR_SELECT2 || button == '\b')
1332 * Can't make pencil marks in a filled square. This can only
1333 * become highlighted if we're using cursor keys.
1335 if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1339 * Can't do anything to an immutable square.
1341 if (state->immutable[ui->hy*w+ui->hx])
1344 sprintf(buf, "%c%d,%d,%d",
1345 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1347 if (!ui->hcursor) ui->hshow = 0;
1352 if (button == 'M' || button == 'm')
1358 static game_state *execute_move(const game_state *from, const char *move)
1360 int w = from->par.w, a = w*w;
1364 if (move[0] == 'S') {
1365 ret = dup_game(from);
1366 ret->completed = ret->cheated = TRUE;
1368 for (i = 0; i < a; i++) {
1369 if (!ISCHAR(move[i+1]) || FROMCHAR(move[i+1], from->par.id) > w) {
1373 ret->grid[i] = FROMCHAR(move[i+1], from->par.id);
1377 if (move[a+1] != '\0') {
1383 } else if ((move[0] == 'P' || move[0] == 'R') &&
1384 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1385 x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1386 if (from->immutable[y*w+x])
1389 ret = dup_game(from);
1390 if (move[0] == 'P' && n > 0) {
1391 ret->pencil[y*w+x] ^= 1 << n;
1393 ret->grid[y*w+x] = n;
1394 ret->pencil[y*w+x] = 0;
1396 if (!ret->completed && !check_errors(ret, NULL))
1397 ret->completed = TRUE;
1400 } else if (move[0] == 'M') {
1402 * Fill in absolutely all pencil marks everywhere. (I
1403 * wouldn't use this for actual play, but it's a handy
1404 * starting point when following through a set of
1405 * diagnostics output by the standalone solver.)
1407 ret = dup_game(from);
1408 for (i = 0; i < a; i++) {
1410 ret->pencil[i] = (1 << (w+1)) - (1 << 1);
1413 } else if (move[0] == 'D' &&
1414 sscanf(move+1, "%d,%d", &x, &y) == 2) {
1416 * Reorder the rows and columns so that digit x is in position
1419 ret = dup_game(from);
1420 for (i = j = 0; i < w; i++) {
1422 ret->sequence[i] = x;
1424 if (from->sequence[j] == x)
1426 ret->sequence[i] = from->sequence[j++];
1430 * Eliminate any obsoleted dividers.
1432 for (x = 0; x+1 < w; x++) {
1433 int i = ret->sequence[x], j = ret->sequence[x+1];
1434 if (ret->dividers[i] != j)
1435 ret->dividers[i] = -1;
1438 } else if (move[0] == 'V' &&
1439 sscanf(move+1, "%d,%d", &i, &j) == 2) {
1440 ret = dup_game(from);
1441 if (ret->dividers[i] == j)
1442 ret->dividers[i] = -1;
1444 ret->dividers[i] = j;
1447 return NULL; /* couldn't parse move string */
1450 /* ----------------------------------------------------------------------
1454 #define SIZE(w) ((w) * TILESIZE + 2*BORDER + LEGEND)
1456 static void game_compute_size(const game_params *params, int tilesize,
1459 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1460 struct { int tilesize; } ads, *ds = &ads;
1461 ads.tilesize = tilesize;
1463 *x = *y = SIZE(params->w);
1466 static void game_set_size(drawing *dr, game_drawstate *ds,
1467 const game_params *params, int tilesize)
1469 ds->tilesize = tilesize;
1472 static float *game_colours(frontend *fe, int *ncolours)
1474 float *ret = snewn(3 * NCOLOURS, float);
1476 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1478 ret[COL_GRID * 3 + 0] = 0.0F;
1479 ret[COL_GRID * 3 + 1] = 0.0F;
1480 ret[COL_GRID * 3 + 2] = 0.0F;
1482 ret[COL_USER * 3 + 0] = 0.0F;
1483 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1484 ret[COL_USER * 3 + 2] = 0.0F;
1486 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1487 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1488 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1490 ret[COL_ERROR * 3 + 0] = 1.0F;
1491 ret[COL_ERROR * 3 + 1] = 0.0F;
1492 ret[COL_ERROR * 3 + 2] = 0.0F;
1494 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1495 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1496 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1498 *ncolours = NCOLOURS;
1502 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1504 int w = state->par.w, a = w*w;
1505 struct game_drawstate *ds = snew(struct game_drawstate);
1509 ds->par = state->par; /* structure copy */
1511 ds->started = FALSE;
1512 ds->tiles = snewn(a, long);
1513 ds->legend = snewn(w, long);
1514 ds->pencil = snewn(a, long);
1515 ds->errors = snewn(a, long);
1516 ds->sequence = snewn(a, digit);
1517 for (i = 0; i < a; i++)
1518 ds->tiles[i] = ds->pencil[i] = -1;
1519 for (i = 0; i < w; i++)
1521 ds->errtmp = snewn(a, long);
1526 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1532 sfree(ds->sequence);
1536 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, long tile,
1537 long pencil, long error)
1539 int w = ds->w /* , a = w*w */;
1544 tx = BORDER + LEGEND + x * TILESIZE + 1;
1545 ty = BORDER + LEGEND + y * TILESIZE + 1;
1549 cw = tw = TILESIZE-1;
1550 ch = th = TILESIZE-1;
1552 if (tile & DF_LEGEND) {
1557 tile |= DF_IMMUTABLE;
1560 clip(dr, cx, cy, cw, ch);
1562 /* background needs erasing */
1563 draw_rect(dr, cx, cy, cw, ch,
1564 (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND);
1567 if (tile & DF_DIVIDER_TOP)
1568 draw_rect(dr, cx, cy, cw, 1, COL_GRID);
1569 if (tile & DF_DIVIDER_BOT)
1570 draw_rect(dr, cx, cy+ch-1, cw, 1, COL_GRID);
1571 if (tile & DF_DIVIDER_LEFT)
1572 draw_rect(dr, cx, cy, 1, ch, COL_GRID);
1573 if (tile & DF_DIVIDER_RIGHT)
1574 draw_rect(dr, cx+cw-1, cy, 1, ch, COL_GRID);
1576 /* pencil-mode highlight */
1577 if (tile & DF_HIGHLIGHT_PENCIL) {
1581 coords[2] = cx+cw/2;
1584 coords[5] = cy+ch/2;
1585 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1588 /* new number needs drawing? */
1589 if (tile & DF_DIGIT_MASK) {
1591 str[0] = TOCHAR(tile & DF_DIGIT_MASK, ds->par.id);
1592 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1593 FONT_VARIABLE, TILESIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1594 (error & EF_LATIN) ? COL_ERROR :
1595 (tile & DF_IMMUTABLE) ? COL_GRID : COL_USER, str);
1597 if (error & EF_LEFT_MASK) {
1598 int a = (error >> (EF_LEFT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1599 int b = (error >> (EF_LEFT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1600 int c = (error >> (EF_LEFT_SHIFT ))&EF_DIGIT_MASK;
1602 sprintf(buf, "(%c%c)%c", TOCHAR(a, ds->par.id),
1603 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1604 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/6,
1605 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1608 if (error & EF_RIGHT_MASK) {
1609 int a = (error >> (EF_RIGHT_SHIFT+2*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1610 int b = (error >> (EF_RIGHT_SHIFT+1*EF_DIGIT_SHIFT))&EF_DIGIT_MASK;
1611 int c = (error >> (EF_RIGHT_SHIFT ))&EF_DIGIT_MASK;
1613 sprintf(buf, "%c(%c%c)", TOCHAR(a, ds->par.id),
1614 TOCHAR(b, ds->par.id), TOCHAR(c, ds->par.id));
1615 draw_text(dr, tx + TILESIZE/2, ty + TILESIZE - TILESIZE/6,
1616 FONT_VARIABLE, TILESIZE/6, ALIGN_VCENTRE | ALIGN_HCENTRE,
1623 int pw, ph, minph, pbest, fontsize;
1625 /* Count the pencil marks required. */
1626 for (i = 1, npencil = 0; i <= w; i++)
1627 if (pencil & (1 << i))
1634 * Determine the bounding rectangle within which we're going
1635 * to put the pencil marks.
1637 /* Start with the whole square */
1638 pl = tx + GRIDEXTRA;
1639 pr = pl + TILESIZE - GRIDEXTRA;
1640 pt = ty + GRIDEXTRA;
1641 pb = pt + TILESIZE - GRIDEXTRA;
1644 * We arrange our pencil marks in a grid layout, with
1645 * the number of rows and columns adjusted to allow the
1646 * maximum font size.
1648 * So now we work out what the grid size ought to be.
1653 for (pw = 3; pw < max(npencil,4); pw++) {
1656 ph = (npencil + pw - 1) / pw;
1657 ph = max(ph, minph);
1658 fw = (pr - pl) / (float)pw;
1659 fh = (pb - pt) / (float)ph;
1661 if (fs > bestsize) {
1668 ph = (npencil + pw - 1) / pw;
1669 ph = max(ph, minph);
1672 * Now we've got our grid dimensions, work out the pixel
1673 * size of a grid element, and round it to the nearest
1674 * pixel. (We don't want rounding errors to make the
1675 * grid look uneven at low pixel sizes.)
1677 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1680 * Centre the resulting figure in the square.
1682 pl = tx + (TILESIZE - fontsize * pw) / 2;
1683 pt = ty + (TILESIZE - fontsize * ph) / 2;
1686 * Now actually draw the pencil marks.
1688 for (i = 1, j = 0; i <= w; i++)
1689 if (pencil & (1 << i)) {
1690 int dx = j % pw, dy = j / pw;
1693 str[0] = TOCHAR(i, ds->par.id);
1694 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1695 pt + fontsize * (2*dy+1) / 2,
1696 FONT_VARIABLE, fontsize,
1697 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1705 draw_update(dr, cx, cy, cw, ch);
1708 static void game_redraw(drawing *dr, game_drawstate *ds,
1709 const game_state *oldstate, const game_state *state,
1710 int dir, const game_ui *ui,
1711 float animtime, float flashtime)
1713 int w = state->par.w /*, a = w*w */;
1718 * The initial contents of the window are not guaranteed and
1719 * can vary with front ends. To be on the safe side, all
1720 * games should start by drawing a big background-colour
1721 * rectangle covering the whole window.
1723 draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1726 * Big containing rectangle.
1728 draw_rect(dr, COORD(0) - GRIDEXTRA, COORD(0) - GRIDEXTRA,
1729 w*TILESIZE+1+GRIDEXTRA*2, w*TILESIZE+1+GRIDEXTRA*2,
1732 draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1737 check_errors(state, ds->errtmp);
1740 * Construct a modified version of state->sequence which takes
1741 * into account an unfinished drag operation.
1749 for (i = j = 0; i < w; i++) {
1751 ds->sequence[i] = x;
1753 if (state->sequence[j] == x)
1755 ds->sequence[i] = state->sequence[j++];
1760 * Draw the table legend.
1762 for (x = 0; x < w; x++) {
1763 int sx = ds->sequence[x];
1764 long tile = (sx+1) | DF_LEGEND;
1765 if (ds->legend[x] != tile) {
1766 ds->legend[x] = tile;
1767 draw_tile(dr, ds, -1, x, tile, 0, 0);
1768 draw_tile(dr, ds, x, -1, tile, 0, 0);
1772 for (y = 0; y < w; y++) {
1773 int sy = ds->sequence[y];
1774 for (x = 0; x < w; x++) {
1775 long tile = 0L, pencil = 0L, error;
1776 int sx = ds->sequence[x];
1778 if (state->grid[sy*w+sx])
1779 tile = state->grid[sy*w+sx];
1781 pencil = (long)state->pencil[sy*w+sx];
1783 if (state->immutable[sy*w+sx])
1784 tile |= DF_IMMUTABLE;
1786 if ((ui->drag == 5 && ui->dragnum == sy) ||
1787 (ui->drag == 6 && ui->dragnum == sx))
1788 tile |= DF_HIGHLIGHT;
1789 else if (ui->hshow && ui->hx == sx && ui->hy == sy)
1790 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
1792 if (flashtime > 0 &&
1793 (flashtime <= FLASH_TIME/3 ||
1794 flashtime >= FLASH_TIME*2/3))
1795 tile |= DF_HIGHLIGHT; /* completion flash */
1797 if (y <= 0 || state->dividers[ds->sequence[y-1]] == sy)
1798 tile |= DF_DIVIDER_TOP;
1799 if (y+1 >= w || state->dividers[sy] == ds->sequence[y+1])
1800 tile |= DF_DIVIDER_BOT;
1801 if (x <= 0 || state->dividers[ds->sequence[x-1]] == sx)
1802 tile |= DF_DIVIDER_LEFT;
1803 if (x+1 >= w || state->dividers[sx] == ds->sequence[x+1])
1804 tile |= DF_DIVIDER_RIGHT;
1806 error = ds->errtmp[sy*w+sx];
1808 if (ds->tiles[y*w+x] != tile ||
1809 ds->pencil[y*w+x] != pencil ||
1810 ds->errors[y*w+x] != error) {
1811 ds->tiles[y*w+x] = tile;
1812 ds->pencil[y*w+x] = pencil;
1813 ds->errors[y*w+x] = error;
1814 draw_tile(dr, ds, x, y, tile, pencil, error);
1820 static float game_anim_length(const game_state *oldstate,
1821 const game_state *newstate, int dir, game_ui *ui)
1826 static float game_flash_length(const game_state *oldstate,
1827 const game_state *newstate, int dir, game_ui *ui)
1829 if (!oldstate->completed && newstate->completed &&
1830 !oldstate->cheated && !newstate->cheated)
1835 static int game_status(const game_state *state)
1837 return state->completed ? +1 : 0;
1840 static int game_timing_state(const game_state *state, game_ui *ui)
1842 if (state->completed)
1847 static void game_print_size(const game_params *params, float *x, float *y)
1852 * We use 9mm squares by default, like Solo.
1854 game_compute_size(params, 900, &pw, &ph);
1859 static void game_print(drawing *dr, const game_state *state, int tilesize)
1861 int w = state->par.w;
1862 int ink = print_mono_colour(dr, 0);
1865 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1866 game_drawstate ads, *ds = &ads;
1867 game_set_size(dr, ds, NULL, tilesize);
1872 print_line_width(dr, 3 * TILESIZE / 40);
1873 draw_rect_outline(dr, BORDER + LEGEND, BORDER + LEGEND,
1874 w*TILESIZE, w*TILESIZE, ink);
1879 for (x = 0; x < w; x++) {
1882 str[0] = TOCHAR(x+1, state->par.id);
1883 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1884 BORDER + TILESIZE/2,
1885 FONT_VARIABLE, TILESIZE/2,
1886 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1887 draw_text(dr, BORDER + TILESIZE/2,
1888 BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1889 FONT_VARIABLE, TILESIZE/2,
1890 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1896 for (x = 1; x < w; x++) {
1897 print_line_width(dr, TILESIZE / 40);
1898 draw_line(dr, BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND,
1899 BORDER+LEGEND+x*TILESIZE, BORDER+LEGEND+w*TILESIZE, ink);
1901 for (y = 1; y < w; y++) {
1902 print_line_width(dr, TILESIZE / 40);
1903 draw_line(dr, BORDER+LEGEND, BORDER+LEGEND+y*TILESIZE,
1904 BORDER+LEGEND+w*TILESIZE, BORDER+LEGEND+y*TILESIZE, ink);
1910 for (y = 0; y < w; y++)
1911 for (x = 0; x < w; x++)
1912 if (state->grid[y*w+x]) {
1915 str[0] = TOCHAR(state->grid[y*w+x], state->par.id);
1916 draw_text(dr, BORDER+LEGEND + x*TILESIZE + TILESIZE/2,
1917 BORDER+LEGEND + y*TILESIZE + TILESIZE/2,
1918 FONT_VARIABLE, TILESIZE/2,
1919 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1924 #define thegame group
1927 const struct game thegame = {
1928 "Group", NULL, NULL,
1935 TRUE, game_configure, custom_params,
1943 TRUE, game_can_format_as_text_now, game_text_format,
1951 PREFERRED_TILESIZE, game_compute_size, game_set_size,
1954 game_free_drawstate,
1959 TRUE, FALSE, game_print_size, game_print,
1960 FALSE, /* wants_statusbar */
1961 FALSE, game_timing_state,
1962 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
1965 #ifdef STANDALONE_SOLVER
1969 int main(int argc, char **argv)
1973 char *id = NULL, *desc, *err;
1976 int ret, diff, really_show_working = FALSE;
1978 while (--argc > 0) {
1980 if (!strcmp(p, "-v")) {
1981 really_show_working = TRUE;
1982 } else if (!strcmp(p, "-g")) {
1984 } else if (*p == '-') {
1985 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
1993 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
1997 desc = strchr(id, ':');
1999 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2004 p = default_params();
2005 decode_params(p, id);
2006 err = validate_desc(p, desc);
2008 fprintf(stderr, "%s: %s\n", argv[0], err);
2011 s = new_game(NULL, p, desc);
2013 grid = snewn(p->w * p->w, digit);
2016 * When solving a Normal puzzle, we don't want to bother the
2017 * user with Hard-level deductions. For this reason, we grade
2018 * the puzzle internally before doing anything else.
2020 ret = -1; /* placate optimiser */
2021 solver_show_working = FALSE;
2022 for (diff = 0; diff < DIFFCOUNT; diff++) {
2023 memcpy(grid, s->grid, p->w * p->w);
2024 ret = solver(&s->par, grid, diff);
2029 if (diff == DIFFCOUNT) {
2031 printf("Difficulty rating: ambiguous\n");
2033 printf("Unable to find a unique solution\n");
2036 if (ret == diff_impossible)
2037 printf("Difficulty rating: impossible (no solution exists)\n");
2039 printf("Difficulty rating: %s\n", group_diffnames[ret]);
2041 solver_show_working = really_show_working;
2042 memcpy(grid, s->grid, p->w * p->w);
2043 ret = solver(&s->par, grid, diff);
2045 printf("Puzzle is inconsistent\n");
2047 memcpy(s->grid, grid, p->w * p->w);
2048 fputs(game_text_format(s), stdout);
2058 /* vim: set shiftwidth=4 tabstop=8: */