chiark / gitweb /
Fix completion checking in Killer Solo.
[sgt-puzzles.git] / magnets.c
1 /*
2  * magnets.c: implementation of janko.at 'magnets puzzle' game.
3  *
4  * http://64.233.179.104/translate_c?hl=en&u=http://www.janko.at/Raetsel/Magnete/Beispiel.htm
5  *
6  * Puzzle definition is just the size, and then the list of + (across then
7  * down) and - (across then down) present, then domino edges.
8  *
9  * An example:
10  *
11  *  + 2 0 1
12  *   +-----+
13  *  1|+ -| |1
14  *   |-+-+ |
15  *  0|-|#| |1
16  *   | +-+-|
17  *  2|+|- +|1
18  *   +-----+
19  *    1 2 0 -
20  *
21  * 3x3:201,102,120,111,LRTT*BBLR
22  *
23  * 'Zotmeister' examples:
24  * 5x5:.2..1,3..1.,.2..2,2..2.,LRLRTTLRTBBT*BTTBLRBBLRLR
25  * 9x9:3.51...33,.2..23.13,..33.33.2,12...5.3.,**TLRTLR*,*TBLRBTLR,TBLRLRBTT,BLRTLRTBB,LRTB*TBLR,LRBLRBLRT,TTTLRLRTB,BBBTLRTB*,*LRBLRB**
26  *
27  * Janko 6x6 with solution:
28  * 6x6:322223,323132,232223,232223,LRTLRTTTBLRBBBTTLRLRBBLRTTLRTTBBLRBB
29  *
30  * janko 8x8:
31  * 8x8:34131323,23131334,43122323,21332243,LRTLRLRT,LRBTTTTB,LRTBBBBT,TTBTLRTB,BBTBTTBT,TTBTBBTB,BBTBLRBT,LRBLRLRB
32  */
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <assert.h>
38 #include <ctype.h>
39 #include <math.h>
40
41 #include "puzzles.h"
42
43 #ifdef STANDALONE_SOLVER
44 int verbose = 0;
45 #endif
46
47 enum {
48     COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
49     COL_TEXT, COL_ERROR, COL_CURSOR, COL_DONE,
50     COL_NEUTRAL, COL_NEGATIVE, COL_POSITIVE, COL_NOT,
51     NCOLOURS
52 };
53
54 /* Cell states. */
55 enum { EMPTY = 0, NEUTRAL = EMPTY, POSITIVE = 1, NEGATIVE = 2 };
56
57 #if defined DEBUGGING || defined STANDALONE_SOLVER
58 static const char *cellnames[3] = { "neutral", "positive", "negative" };
59 #define NAME(w) ( ((w) < 0 || (w) > 2) ? "(out of range)" : cellnames[(w)] )
60 #endif
61
62 #define GRID2CHAR(g) ( ((g) >= 0 && (g) <= 2) ? ".+-"[(g)] : '?' )
63 #define CHAR2GRID(c) ( (c) == '+' ? POSITIVE : (c) == '-' ? NEGATIVE : NEUTRAL )
64
65 #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
66
67 #define OPPOSITE(x) ( ((x)*2) % 3 ) /* 0 --> 0,
68                                        1 --> 2,
69                                        2 --> 4 --> 1 */
70
71 #define FLASH_TIME 0.7F
72
73 /* Macro ickery copied from slant.c */
74 #define DIFFLIST(A) \
75     A(EASY,Easy,e) \
76     A(TRICKY,Tricky,t)
77 #define ENUM(upper,title,lower) DIFF_ ## upper,
78 #define TITLE(upper,title,lower) #title,
79 #define ENCODE(upper,title,lower) #lower
80 #define CONFIG(upper,title,lower) ":" #title
81 enum { DIFFLIST(ENUM) DIFFCOUNT };
82 static char const *const magnets_diffnames[] = { DIFFLIST(TITLE) "(count)" };
83 static char const magnets_diffchars[] = DIFFLIST(ENCODE);
84 #define DIFFCONFIG DIFFLIST(CONFIG)
85
86
87 /* --------------------------------------------------------------- */
88 /* Game parameter functions. */
89
90 struct game_params {
91     int w, h, diff, stripclues;
92 };
93
94 #define DEFAULT_PRESET 2
95
96 static const struct game_params magnets_presets[] = {
97     {6, 5, DIFF_EASY, 0},
98     {6, 5, DIFF_TRICKY, 0},
99     {6, 5, DIFF_TRICKY, 1},
100     {8, 7, DIFF_EASY, 0},
101     {8, 7, DIFF_TRICKY, 0},
102     {8, 7, DIFF_TRICKY, 1},
103     {10, 9, DIFF_TRICKY, 0},
104     {10, 9, DIFF_TRICKY, 1}
105 };
106
107 static game_params *default_params(void)
108 {
109     game_params *ret = snew(game_params);
110
111     *ret = magnets_presets[DEFAULT_PRESET];
112
113     return ret;
114 }
115
116 static int game_fetch_preset(int i, char **name, game_params **params)
117 {
118     game_params *ret;
119     char buf[64];
120
121     if (i < 0 || i >= lenof(magnets_presets)) return FALSE;
122
123     ret = default_params();
124     *ret = magnets_presets[i]; /* struct copy */
125     *params = ret;
126
127     sprintf(buf, "%dx%d %s%s",
128             magnets_presets[i].w, magnets_presets[i].h,
129             magnets_diffnames[magnets_presets[i].diff],
130             magnets_presets[i].stripclues ? ", strip clues" : "");
131     *name = dupstr(buf);
132
133     return TRUE;
134 }
135
136 static void free_params(game_params *params)
137 {
138     sfree(params);
139 }
140
141 static game_params *dup_params(const game_params *params)
142 {
143     game_params *ret = snew(game_params);
144     *ret = *params;       /* structure copy */
145     return ret;
146 }
147
148 static void decode_params(game_params *ret, char const *string)
149 {
150     ret->w = ret->h = atoi(string);
151     while (*string && isdigit((unsigned char) *string)) ++string;
152     if (*string == 'x') {
153         string++;
154         ret->h = atoi(string);
155         while (*string && isdigit((unsigned char)*string)) string++;
156     }
157
158     ret->diff = DIFF_EASY;
159     if (*string == 'd') {
160         int i;
161         string++;
162         for (i = 0; i < DIFFCOUNT; i++)
163             if (*string == magnets_diffchars[i])
164                 ret->diff = i;
165         if (*string) string++;
166     }
167
168     ret->stripclues = 0;
169     if (*string == 'S') {
170         string++;
171         ret->stripclues = 1;
172     }
173 }
174
175 static char *encode_params(const game_params *params, int full)
176 {
177     char buf[256];
178     sprintf(buf, "%dx%d", params->w, params->h);
179     if (full)
180         sprintf(buf + strlen(buf), "d%c%s",
181                 magnets_diffchars[params->diff],
182                 params->stripclues ? "S" : "");
183     return dupstr(buf);
184 }
185
186 static config_item *game_configure(const game_params *params)
187 {
188     config_item *ret;
189     char buf[64];
190
191     ret = snewn(5, config_item);
192
193     ret[0].name = "Width";
194     ret[0].type = C_STRING;
195     sprintf(buf, "%d", params->w);
196     ret[0].sval = dupstr(buf);
197     ret[0].ival = 0;
198
199     ret[1].name = "Height";
200     ret[1].type = C_STRING;
201     sprintf(buf, "%d", params->h);
202     ret[1].sval = dupstr(buf);
203     ret[1].ival = 0;
204
205     ret[2].name = "Difficulty";
206     ret[2].type = C_CHOICES;
207     ret[2].sval = DIFFCONFIG;
208     ret[2].ival = params->diff;
209
210     ret[3].name = "Strip clues";
211     ret[3].type = C_BOOLEAN;
212     ret[3].sval = NULL;
213     ret[3].ival = params->stripclues;
214
215     ret[4].name = NULL;
216     ret[4].type = C_END;
217     ret[4].sval = NULL;
218     ret[4].ival = 0;
219
220     return ret;
221 }
222
223 static game_params *custom_params(const config_item *cfg)
224 {
225     game_params *ret = snew(game_params);
226
227     ret->w = atoi(cfg[0].sval);
228     ret->h = atoi(cfg[1].sval);
229     ret->diff = cfg[2].ival;
230     ret->stripclues = cfg[3].ival;
231
232     return ret;
233 }
234
235 static char *validate_params(const game_params *params, int full)
236 {
237     if (params->w < 2) return "Width must be at least one";
238     if (params->h < 2) return "Height must be at least one";
239     if (params->diff < 0 || params->diff >= DIFFCOUNT)
240         return "Unknown difficulty level";
241
242     return NULL;
243 }
244
245 /* --------------------------------------------------------------- */
246 /* Game state allocation, deallocation. */
247
248 struct game_common {
249     int *dominoes;      /* size w*h, dominoes[i] points to other end of domino. */
250     int *rowcount;      /* size 3*h, array of [plus, minus, neutral] counts */
251     int *colcount;      /* size 3*w, ditto */
252     int refcount;
253 };
254
255 #define GS_ERROR        1
256 #define GS_SET          2
257 #define GS_NOTPOSITIVE  4
258 #define GS_NOTNEGATIVE  8
259 #define GS_NOTNEUTRAL  16
260 #define GS_MARK        32
261
262 #define GS_NOTMASK (GS_NOTPOSITIVE|GS_NOTNEGATIVE|GS_NOTNEUTRAL)
263
264 #define NOTFLAG(w) ( (w) == NEUTRAL ? GS_NOTNEUTRAL : \
265                      (w) == POSITIVE ? GS_NOTPOSITIVE : \
266                      (w) == NEGATIVE ? GS_NOTNEGATIVE : \
267                      0 )
268
269 #define POSSIBLE(f,w) (!(state->flags[(f)] & NOTFLAG(w)))
270
271 struct game_state {
272     int w, h, wh;
273     int *grid;                  /* size w*h, for cell state (pos/neg) */
274     unsigned int *flags;        /* size w*h */
275     int solved, completed, numbered;
276     unsigned char *counts_done;
277
278     struct game_common *common; /* domino layout never changes. */
279 };
280
281 static void clear_state(game_state *ret)
282 {
283     int i;
284
285     ret->solved = ret->completed = ret->numbered = 0;
286
287     memset(ret->common->rowcount, 0, ret->h*3*sizeof(int));
288     memset(ret->common->colcount, 0, ret->w*3*sizeof(int));
289     memset(ret->counts_done, 0, (ret->h + ret->w) * 2 * sizeof(unsigned char));
290
291     for (i = 0; i < ret->wh; i++) {
292         ret->grid[i] = EMPTY;
293         ret->flags[i] = 0;
294         ret->common->dominoes[i] = i;
295     }
296 }
297
298 static game_state *new_state(int w, int h)
299 {
300     game_state *ret = snew(game_state);
301
302     memset(ret, 0, sizeof(game_state));
303     ret->w = w;
304     ret->h = h;
305     ret->wh = w*h;
306
307     ret->grid = snewn(ret->wh, int);
308     ret->flags = snewn(ret->wh, unsigned int);
309     ret->counts_done = snewn((ret->h + ret->w) * 2, unsigned char);
310
311     ret->common = snew(struct game_common);
312     ret->common->refcount = 1;
313
314     ret->common->dominoes = snewn(ret->wh, int);
315     ret->common->rowcount = snewn(ret->h*3, int);
316     ret->common->colcount = snewn(ret->w*3, int);
317
318     clear_state(ret);
319
320     return ret;
321 }
322
323 static game_state *dup_game(const game_state *src)
324 {
325     game_state *dest = snew(game_state);
326
327     dest->w = src->w;
328     dest->h = src->h;
329     dest->wh = src->wh;
330
331     dest->solved = src->solved;
332     dest->completed = src->completed;
333     dest->numbered = src->numbered;
334
335     dest->common = src->common;
336     dest->common->refcount++;
337
338     dest->grid = snewn(dest->wh, int);
339     memcpy(dest->grid, src->grid, dest->wh*sizeof(int));
340
341     dest->counts_done = snewn((dest->h + dest->w) * 2, unsigned char);
342     memcpy(dest->counts_done, src->counts_done,
343            (dest->h + dest->w) * 2 * sizeof(unsigned char));
344
345     dest->flags = snewn(dest->wh, unsigned int);
346     memcpy(dest->flags, src->flags, dest->wh*sizeof(unsigned int));
347
348     return dest;
349 }
350
351 static void free_game(game_state *state)
352 {
353     state->common->refcount--;
354     if (state->common->refcount == 0) {
355         sfree(state->common->dominoes);
356         sfree(state->common->rowcount);
357         sfree(state->common->colcount);
358         sfree(state->common);
359     }
360     sfree(state->counts_done);
361     sfree(state->flags);
362     sfree(state->grid);
363     sfree(state);
364 }
365
366 /* --------------------------------------------------------------- */
367 /* Game generation and reading. */
368
369 /* For a game of size w*h the game description is:
370  * w-sized string of column + numbers (L-R), or '.' for none
371  * semicolon
372  * h-sized string of row + numbers (T-B), or '.'
373  * semicolon
374  * w-sized string of column - numbers (L-R), or '.'
375  * semicolon
376  * h-sized string of row - numbers (T-B), or '.'
377  * semicolon
378  * w*h-sized string of 'L', 'R', 'U', 'D' for domino associations,
379  *   or '*' for a black singleton square.
380  *
381  * for a total length of 2w + 2h + wh + 4.
382  */
383
384 static char n2c(int num) { /* XXX cloned from singles.c */
385     if (num == -1)
386         return '.';
387     if (num < 10)
388         return '0' + num;
389     else if (num < 10+26)
390         return 'a' + num - 10;
391     else
392         return 'A' + num - 10 - 26;
393     return '?';
394 }
395
396 static int c2n(char c) { /* XXX cloned from singles.c */
397     if (isdigit((unsigned char)c))
398         return (int)(c - '0');
399     else if (c >= 'a' && c <= 'z')
400         return (int)(c - 'a' + 10);
401     else if (c >= 'A' && c <= 'Z')
402         return (int)(c - 'A' + 10 + 26);
403     return -1;
404 }
405
406 static const char *readrow(const char *desc, int n, int *array, int off,
407                            const char **prob)
408 {
409     int i, num;
410     char c;
411
412     for (i = 0; i < n; i++) {
413         c = *desc++;
414         if (c == 0) goto badchar;
415         if (c == '.')
416             num = -1;
417         else {
418             num = c2n(c);
419             if (num < 0) goto badchar;
420         }
421         array[i*3+off] = num;
422     }
423     c = *desc++;
424     if (c != ',') goto badchar;
425     return desc;
426
427 badchar:
428     *prob = (c == 0) ?
429                 "Game description too short" :
430                 "Game description contained unexpected characters";
431     return NULL;
432 }
433
434 static game_state *new_game_int(const game_params *params, const char *desc,
435                                 const char **prob)
436 {
437     game_state *state = new_state(params->w, params->h);
438     int x, y, idx, *count;
439     char c;
440
441     *prob = NULL;
442
443     /* top row, left-to-right */
444     desc = readrow(desc, state->w, state->common->colcount, POSITIVE, prob);
445     if (*prob) goto done;
446
447     /* left column, top-to-bottom */
448     desc = readrow(desc, state->h, state->common->rowcount, POSITIVE, prob);
449     if (*prob) goto done;
450
451     /* bottom row, left-to-right */
452     desc = readrow(desc, state->w, state->common->colcount, NEGATIVE, prob);
453     if (*prob) goto done;
454
455     /* right column, top-to-bottom */
456     desc = readrow(desc, state->h, state->common->rowcount, NEGATIVE, prob);
457     if (*prob) goto done;
458
459     /* Add neutral counts (== size - pos - neg) to columns and rows.
460      * Any singleton cells will just be treated as permanently neutral. */
461     count = state->common->colcount;
462     for (x = 0; x < state->w; x++) {
463         if (count[x*3+POSITIVE] < 0 || count[x*3+NEGATIVE] < 0)
464             count[x*3+NEUTRAL] = -1;
465         else {
466             count[x*3+NEUTRAL] =
467                 state->h - count[x*3+POSITIVE] - count[x*3+NEGATIVE];
468             if (count[x*3+NEUTRAL] < 0) {
469                 *prob = "Column counts inconsistent";
470                 goto done;
471             }
472         }
473     }
474     count = state->common->rowcount;
475     for (y = 0; y < state->h; y++) {
476         if (count[y*3+POSITIVE] < 0 || count[y*3+NEGATIVE] < 0)
477             count[y*3+NEUTRAL] = -1;
478         else {
479             count[y*3+NEUTRAL] =
480                 state->w - count[y*3+POSITIVE] - count[y*3+NEGATIVE];
481             if (count[y*3+NEUTRAL] < 0) {
482                 *prob = "Row counts inconsistent";
483                 goto done;
484             }
485         }
486     }
487
488
489     for (y = 0; y < state->h; y++) {
490         for (x = 0; x < state->w; x++) {
491             idx = y*state->w + x;
492 nextchar:
493             c = *desc++;
494
495             if (c == 'L') /* this square is LHS of a domino */
496                 state->common->dominoes[idx] = idx+1;
497             else if (c == 'R') /* ... RHS of a domino */
498                 state->common->dominoes[idx] = idx-1;
499             else if (c == 'T') /* ... top of a domino */
500                 state->common->dominoes[idx] = idx+state->w;
501             else if (c == 'B') /* ... bottom of a domino */
502                 state->common->dominoes[idx] = idx-state->w;
503             else if (c == '*') /* singleton */
504                 state->common->dominoes[idx] = idx;
505             else if (c == ',') /* spacer, ignore */
506                 goto nextchar;
507             else goto badchar;
508         }
509     }
510
511     /* Check dominoes as input are sensibly consistent
512      * (i.e. each end points to the other) */
513     for (idx = 0; idx < state->wh; idx++) {
514         if (state->common->dominoes[idx] < 0 ||
515             state->common->dominoes[idx] > state->wh ||
516             state->common->dominoes[state->common->dominoes[idx]] != idx) {
517             *prob = "Domino descriptions inconsistent";
518             goto done;
519         }
520         if (state->common->dominoes[idx] == idx) {
521             state->grid[idx] = NEUTRAL;
522             state->flags[idx] |= GS_SET;
523         }
524     }
525     /* Success. */
526     state->numbered = 1;
527     goto done;
528
529 badchar:
530     *prob = (c == 0) ?
531                 "Game description too short" :
532                 "Game description contained unexpected characters";
533
534 done:
535     if (*prob) {
536         free_game(state);
537         return NULL;
538     }
539     return state;
540 }
541
542 static char *validate_desc(const game_params *params, const char *desc)
543 {
544     const char *prob;
545     game_state *st = new_game_int(params, desc, &prob);
546     if (!st) return (char*)prob;
547     free_game(st);
548     return NULL;
549 }
550
551 static game_state *new_game(midend *me, const game_params *params,
552                             const char *desc)
553 {
554     const char *prob;
555     game_state *st = new_game_int(params, desc, &prob);
556     assert(st);
557     return st;
558 }
559
560 static char *generate_desc(game_state *new)
561 {
562     int x, y, idx, other, w = new->w, h = new->h;
563     char *desc = snewn(new->wh + 2*(w + h) + 5, char), *p = desc;
564
565     for (x = 0; x < w; x++) *p++ = n2c(new->common->colcount[x*3+POSITIVE]);
566     *p++ = ',';
567     for (y = 0; y < h; y++) *p++ = n2c(new->common->rowcount[y*3+POSITIVE]);
568     *p++ = ',';
569
570     for (x = 0; x < w; x++) *p++ = n2c(new->common->colcount[x*3+NEGATIVE]);
571     *p++ = ',';
572     for (y = 0; y < h; y++) *p++ = n2c(new->common->rowcount[y*3+NEGATIVE]);
573     *p++ = ',';
574
575     for (y = 0; y < h; y++) {
576         for (x = 0; x < w; x++) {
577             idx = y*w + x;
578             other = new->common->dominoes[idx];
579
580             if (other == idx) *p++ = '*';
581             else if (other == idx+1) *p++ = 'L';
582             else if (other == idx-1) *p++ = 'R';
583             else if (other == idx+w) *p++ = 'T';
584             else if (other == idx-w) *p++ = 'B';
585             else assert(!"mad domino orientation");
586         }
587     }
588     *p = '\0';
589
590     return desc;
591 }
592
593 static void game_text_hborder(const game_state *state, char **p_r)
594 {
595     char *p = *p_r;
596     int x;
597
598     *p++ = ' ';
599     *p++ = '+';
600     for (x = 0; x < state->w*2-1; x++) *p++ = '-';
601     *p++ = '+';
602     *p++ = '\n';
603
604     *p_r = p;
605 }
606
607 static int game_can_format_as_text_now(const game_params *params)
608 {
609     return TRUE;
610 }
611
612 static char *game_text_format(const game_state *state)
613 {
614     int len, x, y, i;
615     char *ret, *p;
616
617     len = ((state->w*2)+4) * ((state->h*2)+4) + 2;
618     p = ret = snewn(len, char);
619
620     /* top row: '+' then column totals for plus. */
621     *p++ = '+';
622     for (x = 0; x < state->w; x++) {
623         *p++ = ' ';
624         *p++ = n2c(state->common->colcount[x*3+POSITIVE]);
625     }
626     *p++ = '\n';
627
628     /* top border. */
629     game_text_hborder(state, &p);
630
631     for (y = 0; y < state->h; y++) {
632         *p++ = n2c(state->common->rowcount[y*3+POSITIVE]);
633         *p++ = '|';
634         for (x = 0; x < state->w; x++) {
635             i = y*state->w+x;
636             *p++ = state->common->dominoes[i] == i ? '#' :
637                 state->grid[i] == POSITIVE ? '+' :
638                 state->grid[i] == NEGATIVE ? '-' :
639                 state->flags[i] & GS_SET ? '*' : ' ';
640             if (x < (state->w-1))
641                 *p++ = state->common->dominoes[i] == i+1 ? ' ' : '|';
642         }
643         *p++ = '|';
644         *p++ = n2c(state->common->rowcount[y*3+NEGATIVE]);
645         *p++ = '\n';
646
647         if (y < (state->h-1)) {
648             *p++ = ' ';
649             *p++ = '|';
650             for (x = 0; x < state->w; x++) {
651                 i = y*state->w+x;
652                 *p++ = state->common->dominoes[i] == i+state->w ? ' ' : '-';
653                 if (x < (state->w-1))
654                     *p++ = '+';
655             }
656             *p++ = '|';
657             *p++ = '\n';
658         }
659     }
660
661     /* bottom border. */
662     game_text_hborder(state, &p);
663
664     /* bottom row: column totals for minus then '-'. */
665     *p++ = ' ';
666     for (x = 0; x < state->w; x++) {
667         *p++ = ' ';
668         *p++ = n2c(state->common->colcount[x*3+NEGATIVE]);
669     }
670     *p++ = ' ';
671     *p++ = '-';
672     *p++ = '\n';
673     *p++ = '\0';
674
675     return ret;
676 }
677
678 static void game_debug(game_state *state, const char *desc)
679 {
680     char *fmt = game_text_format(state);
681     debug(("%s:\n%s\n", desc, fmt));
682     sfree(fmt);
683 }
684
685 enum { ROW, COLUMN };
686
687 typedef struct rowcol {
688     int i, di, n, roworcol, num;
689     int *targets;
690     const char *name;
691 } rowcol;
692
693 static rowcol mkrowcol(const game_state *state, int num, int roworcol)
694 {
695     rowcol rc;
696
697     rc.roworcol = roworcol;
698     rc.num = num;
699
700     if (roworcol == ROW) {
701         rc.i = num * state->w;
702         rc.di = 1;
703         rc.n = state->w;
704         rc.targets = &(state->common->rowcount[num*3]);
705         rc.name = "row";
706     } else if (roworcol == COLUMN) {
707         rc.i = num;
708         rc.di = state->w;
709         rc.n = state->h;
710         rc.targets = &(state->common->colcount[num*3]);
711         rc.name = "column";
712     } else {
713         assert(!"unknown roworcol");
714     }
715     return rc;
716 }
717
718 static int count_rowcol(const game_state *state, int num, int roworcol,
719                         int which)
720 {
721     int i, count = 0;
722     rowcol rc = mkrowcol(state, num, roworcol);
723
724     for (i = 0; i < rc.n; i++, rc.i += rc.di) {
725         if (which < 0) {
726             if (state->grid[rc.i] == EMPTY &&
727                 !(state->flags[rc.i] & GS_SET))
728                 count++;
729         } else if (state->grid[rc.i] == which)
730             count++;
731     }
732     return count;
733 }
734
735 static void check_rowcol(game_state *state, int num, int roworcol, int which,
736                         int *wrong, int *incomplete)
737 {
738     int count, target = mkrowcol(state, num, roworcol).targets[which];
739
740     if (target == -1) return; /* no number to check against. */
741
742     count = count_rowcol(state, num, roworcol, which);
743     if (count < target) *incomplete = 1;
744     if (count > target) *wrong = 1;
745 }
746
747 static int check_completion(game_state *state)
748 {
749     int i, j, x, y, idx, w = state->w, h = state->h;
750     int which = POSITIVE, wrong = 0, incomplete = 0;
751
752     /* Check row and column counts for magnets. */
753     for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
754         for (i = 0; i < w; i++)
755             check_rowcol(state, i, COLUMN, which, &wrong, &incomplete);
756
757         for (i = 0; i < h; i++)
758             check_rowcol(state, i, ROW, which, &wrong, &incomplete);
759     }
760     /* Check each domino has been filled, and that we don't have
761      * touching identical terminals. */
762     for (i = 0; i < state->wh; i++) state->flags[i] &= ~GS_ERROR;
763     for (x = 0; x < w; x++) {
764         for (y = 0; y < h; y++) {
765             idx = y*w + x;
766             if (state->common->dominoes[idx] == idx)
767                 continue; /* no domino here */
768
769             if (!(state->flags[idx] & GS_SET))
770                 incomplete = 1;
771
772             which = state->grid[idx];
773             if (which != NEUTRAL) {
774 #define CHECK(xx,yy) do { \
775     if (INGRID(state,xx,yy) && \
776         (state->grid[(yy)*w+(xx)] == which)) { \
777         wrong = 1; \
778         state->flags[(yy)*w+(xx)] |= GS_ERROR; \
779         state->flags[y*w+x] |= GS_ERROR; \
780     } \
781 } while(0)
782                 CHECK(x,y-1);
783                 CHECK(x,y+1);
784                 CHECK(x-1,y);
785                 CHECK(x+1,y);
786 #undef CHECK
787             }
788         }
789     }
790     return wrong ? -1 : incomplete ? 0 : 1;
791 }
792
793 static const int dx[4] = {-1, 1, 0, 0};
794 static const int dy[4] = {0, 0, -1, 1};
795
796 static void solve_clearflags(game_state *state)
797 {
798     int i;
799
800     for (i = 0; i < state->wh; i++) {
801         state->flags[i] &= ~GS_NOTMASK;
802         if (state->common->dominoes[i] != i)
803             state->flags[i] &= ~GS_SET;
804     }
805 }
806
807 /* Knowing a given cell cannot be a certain colour also tells us
808  * something about the other cell in that domino. */
809 static int solve_unflag(game_state *state, int i, int which,
810                         const char *why, rowcol *rc)
811 {
812     int ii, ret = 0;
813 #if defined DEBUGGING || defined STANDALONE_SOLVER
814     int w = state->w;
815 #endif
816
817     assert(i >= 0 && i < state->wh);
818     ii = state->common->dominoes[i];
819     if (ii == i) return 0;
820
821     if (rc)
822         debug(("solve_unflag: (%d,%d) for %s %d", i%w, i/w, rc->name, rc->num));
823
824     if ((state->flags[i] & GS_SET) && (state->grid[i] == which)) {
825         debug(("solve_unflag: (%d,%d) already %s, cannot unflag (for %s).",
826                i%w, i/w, NAME(which), why));
827         return -1;
828     }
829     if ((state->flags[ii] & GS_SET) && (state->grid[ii] == OPPOSITE(which))) {
830         debug(("solve_unflag: (%d,%d) opposite already %s, cannot unflag (for %s).",
831                ii%w, ii/w, NAME(OPPOSITE(which)), why));
832         return -1;
833     }
834     if (POSSIBLE(i, which)) {
835         state->flags[i] |= NOTFLAG(which);
836         ret++;
837         debug(("solve_unflag: (%d,%d) CANNOT be %s (%s)",
838                i%w, i/w, NAME(which), why));
839     }
840     if (POSSIBLE(ii, OPPOSITE(which))) {
841         state->flags[ii] |= NOTFLAG(OPPOSITE(which));
842         ret++;
843         debug(("solve_unflag: (%d,%d) CANNOT be %s (%s, other half)",
844                ii%w, ii/w, NAME(OPPOSITE(which)), why));
845     }
846 #ifdef STANDALONE_SOLVER
847     if (verbose && ret) {
848         printf("(%d,%d)", i%w, i/w);
849         if (rc) printf(" in %s %d", rc->name, rc->num);
850         printf(" cannot be %s (%s); opposite (%d,%d) not %s.\n",
851                NAME(which), why, ii%w, ii/w, NAME(OPPOSITE(which)));
852     }
853 #endif
854     return ret;
855 }
856
857 static int solve_unflag_surrounds(game_state *state, int i, int which)
858 {
859     int x = i%state->w, y = i/state->w, xx, yy, j, ii;
860
861     assert(INGRID(state, x, y));
862
863     for (j = 0; j < 4; j++) {
864         xx = x+dx[j]; yy = y+dy[j];
865         if (!INGRID(state, xx, yy)) continue;
866
867         ii = yy*state->w+xx;
868         if (solve_unflag(state, ii, which, "adjacent to set cell", NULL) < 0)
869             return -1;
870     }
871     return 0;
872 }
873
874 /* Sets a cell to a particular colour, and also perform other
875  * housekeeping around that. */
876 static int solve_set(game_state *state, int i, int which,
877                      const char *why, rowcol *rc)
878 {
879     int ii;
880 #if defined DEBUGGING || defined STANDALONE_SOLVER
881     int w = state->w;
882 #endif
883
884     ii = state->common->dominoes[i];
885
886     if (state->flags[i] & GS_SET) {
887         if (state->grid[i] == which) {
888             return 0; /* was already set and held, do nothing. */
889         } else {
890             debug(("solve_set: (%d,%d) is held and %s, cannot set to %s",
891                    i%w, i/w, NAME(state->grid[i]), NAME(which)));
892             return -1;
893         }
894     }
895     if ((state->flags[ii] & GS_SET) && state->grid[ii] != OPPOSITE(which)) {
896         debug(("solve_set: (%d,%d) opposite is held and %s, cannot set to %s",
897                 ii%w, ii/w, NAME(state->grid[ii]), NAME(OPPOSITE(which))));
898         return -1;
899     }
900     if (!POSSIBLE(i, which)) {
901         debug(("solve_set: (%d,%d) NOT %s, cannot set.", i%w, i/w, NAME(which)));
902         return -1;
903     }
904     if (!POSSIBLE(ii, OPPOSITE(which))) {
905         debug(("solve_set: (%d,%d) NOT %s, cannot set (%d,%d).",
906                ii%w, ii/w, NAME(OPPOSITE(which)), i%w, i/w));
907         return -1;
908     }
909
910 #ifdef STANDALONE_SOLVER
911     if (verbose) {
912         printf("(%d,%d)", i%w, i/w);
913         if (rc) printf(" in %s %d", rc->name, rc->num);
914         printf(" set to %s (%s), opposite (%d,%d) set to %s.\n",
915                NAME(which), why, ii%w, ii/w, NAME(OPPOSITE(which)));
916     }
917 #endif
918     if (rc)
919         debug(("solve_set: (%d,%d) for %s %d", i%w, i/w, rc->name, rc->num));
920     debug(("solve_set: (%d,%d) setting to %s (%s), surrounds first:",
921            i%w, i/w, NAME(which), why));
922
923     if (which != NEUTRAL) {
924         if (solve_unflag_surrounds(state, i, which) < 0)
925             return -1;
926         if (solve_unflag_surrounds(state, ii, OPPOSITE(which)) < 0)
927             return -1;
928     }
929
930     state->grid[i] = which;
931     state->grid[ii] = OPPOSITE(which);
932
933     state->flags[i] |= GS_SET;
934     state->flags[ii] |= GS_SET;
935
936     debug(("solve_set: (%d,%d) set to %s (%s)", i%w, i/w, NAME(which), why));
937
938     return 1;
939 }
940
941 /* counts should be int[4]. */
942 static void solve_counts(game_state *state, rowcol rc, int *counts, int *unset)
943 {
944     int i, j, which;
945
946     assert(counts);
947     for (i = 0; i < 4; i++) {
948         counts[i] = 0;
949         if (unset) unset[i] = 0;
950     }
951
952     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
953         if (state->flags[i] & GS_SET) {
954             assert(state->grid[i] < 3);
955             counts[state->grid[i]]++;
956         } else if (unset) {
957             for (which = 0; which <= 2; which++) {
958                 if (POSSIBLE(i, which))
959                     unset[which]++;
960             }
961         }
962     }
963 }
964
965 static int solve_checkfull(game_state *state, rowcol rc, int *counts)
966 {
967     int starti = rc.i, j, which, didsth = 0, target;
968     int unset[4];
969
970     assert(state->numbered); /* only useful (should only be called) if numbered. */
971
972     solve_counts(state, rc, counts, unset);
973
974     for (which = 0; which <= 2; which++) {
975         target = rc.targets[which];
976         if (target == -1) continue;
977
978         /*debug(("%s %d for %s: target %d, count %d, unset %d",
979                rc.name, rc.num, NAME(which),
980                target, counts[which], unset[which]));*/
981
982         if (target < counts[which]) {
983             debug(("%s %d has too many (%d) %s squares (target %d), impossible!",
984                    rc.name, rc.num, counts[which], NAME(which), target));
985             return -1;
986         }
987         if (target == counts[which]) {
988             /* We have the correct no. of the colour in this row/column
989              * already; unflag all the rest. */
990             for (rc.i = starti, j = 0; j < rc.n; rc.i += rc.di, j++) {
991                 if (state->flags[rc.i] & GS_SET) continue;
992                 if (!POSSIBLE(rc.i, which)) continue;
993
994                 if (solve_unflag(state, rc.i, which, "row/col full", &rc) < 0)
995                     return -1;
996                 didsth = 1;
997             }
998         } else if ((target - counts[which]) == unset[which]) {
999             /* We need all the remaining unset squares for this colour;
1000              * set them all. */
1001             for (rc.i = starti, j = 0; j < rc.n; rc.i += rc.di, j++) {
1002                 if (state->flags[rc.i] & GS_SET) continue;
1003                 if (!POSSIBLE(rc.i, which)) continue;
1004
1005                 if (solve_set(state, rc.i, which, "row/col needs all unset", &rc) < 0)
1006                     return -1;
1007                 didsth = 1;
1008             }
1009         }
1010     }
1011     return didsth;
1012 }
1013
1014 static int solve_startflags(game_state *state)
1015 {
1016     int x, y, i;
1017
1018     for (x = 0; x < state->w; x++) {
1019         for (y = 0; y < state->h; y++) {
1020             i = y*state->w+x;
1021             if (state->common->dominoes[i] == i) continue;
1022             if (state->grid[i] != NEUTRAL ||
1023                 state->flags[i] & GS_SET) {
1024                 if (solve_set(state, i, state->grid[i], "initial set-and-hold", NULL) < 0)
1025                     return -1;
1026             }
1027         }
1028     }
1029     return 0;
1030 }
1031
1032 typedef int (*rowcolfn)(game_state *state, rowcol rc, int *counts);
1033
1034 static int solve_rowcols(game_state *state, rowcolfn fn)
1035 {
1036     int x, y, didsth = 0, ret;
1037     rowcol rc;
1038     int counts[4];
1039
1040     for (x = 0; x < state->w; x++) {
1041         rc = mkrowcol(state, x, COLUMN);
1042         solve_counts(state, rc, counts, NULL);
1043
1044         ret = fn(state, rc, counts);
1045         if (ret < 0) return ret;
1046         didsth += ret;
1047     }
1048     for (y = 0; y < state->h; y++) {
1049         rc = mkrowcol(state, y, ROW);
1050         solve_counts(state, rc, counts, NULL);
1051
1052         ret = fn(state, rc, counts);
1053         if (ret < 0) return ret;
1054         didsth += ret;
1055     }
1056     return didsth;
1057 }
1058
1059 static int solve_force(game_state *state)
1060 {
1061     int i, which, didsth = 0;
1062     unsigned long f;
1063
1064     for (i = 0; i < state->wh; i++) {
1065         if (state->flags[i] & GS_SET) continue;
1066         if (state->common->dominoes[i] == i) continue;
1067
1068         f = state->flags[i] & GS_NOTMASK;
1069         which = -1;
1070         if (f == (GS_NOTPOSITIVE|GS_NOTNEGATIVE))
1071             which = NEUTRAL;
1072         if (f == (GS_NOTPOSITIVE|GS_NOTNEUTRAL))
1073             which = NEGATIVE;
1074         if (f == (GS_NOTNEGATIVE|GS_NOTNEUTRAL))
1075             which = POSITIVE;
1076         if (which != -1) {
1077             if (solve_set(state, i, which, "forced by flags", NULL) < 0)
1078                 return -1;
1079             didsth = 1;
1080         }
1081     }
1082     return didsth;
1083 }
1084
1085 static int solve_neither(game_state *state)
1086 {
1087     int i, j, didsth = 0;
1088
1089     for (i = 0; i < state->wh; i++) {
1090         if (state->flags[i] & GS_SET) continue;
1091         j = state->common->dominoes[i];
1092         if (i == j) continue;
1093
1094         if (((state->flags[i] & GS_NOTPOSITIVE) &&
1095              (state->flags[j] & GS_NOTPOSITIVE)) ||
1096             ((state->flags[i] & GS_NOTNEGATIVE) &&
1097              (state->flags[j] & GS_NOTNEGATIVE))) {
1098             if (solve_set(state, i, NEUTRAL, "neither tile magnet", NULL) < 0)
1099                 return -1;
1100             didsth = 1;
1101         }
1102     }
1103     return didsth;
1104 }
1105
1106 static int solve_advancedfull(game_state *state, rowcol rc, int *counts)
1107 {
1108     int i, j, nfound = 0, clearpos = 0, clearneg = 0, ret = 0;
1109
1110     /* For this row/col, look for a domino entirely within the row where
1111      * both ends can only be + or - (but isn't held).
1112      * The +/- counts can thus be decremented by 1 each, and the 'unset'
1113      * count by 2.
1114      *
1115      * Once that's done for all such dominoes (and they're marked), try
1116      * and made usual deductions about rest of the row based on new totals. */
1117
1118     if (rc.targets[POSITIVE] == -1 && rc.targets[NEGATIVE] == -1)
1119         return 0; /* don't have a target for either colour, nothing to do. */
1120     if ((rc.targets[POSITIVE] >= 0 && counts[POSITIVE] == rc.targets[POSITIVE]) &&
1121         (rc.targets[NEGATIVE] >= 0 && counts[NEGATIVE] == rc.targets[NEGATIVE]))
1122         return 0; /* both colours are full up already, nothing to do. */
1123
1124     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++)
1125         state->flags[i] &= ~GS_MARK;
1126
1127     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1128         if (state->flags[i] & GS_SET) continue;
1129
1130         /* We're looking for a domino in our row/col, thus if
1131          * dominoes[i] -> i+di we've found one. */
1132         if (state->common->dominoes[i] != i+rc.di) continue;
1133
1134         /* We need both squares of this domino to be either + or -
1135          * (i.e. both NOTNEUTRAL only). */
1136         if (((state->flags[i] & GS_NOTMASK) != GS_NOTNEUTRAL) ||
1137             ((state->flags[i+rc.di] & GS_NOTMASK) != GS_NOTNEUTRAL))
1138             continue;
1139
1140         debug(("Domino in %s %d at (%d,%d) must be polarised.",
1141                rc.name, rc.num, i%state->w, i/state->w));
1142         state->flags[i] |= GS_MARK;
1143         state->flags[i+rc.di] |= GS_MARK;
1144         nfound++;
1145     }
1146     if (nfound == 0) return 0;
1147
1148     /* nfound is #dominoes we matched, which will all be marked. */
1149     counts[POSITIVE] += nfound;
1150     counts[NEGATIVE] += nfound;
1151
1152     if (rc.targets[POSITIVE] >= 0 && counts[POSITIVE] == rc.targets[POSITIVE]) {
1153         debug(("%s %d has now filled POSITIVE:", rc.name, rc.num));
1154         clearpos = 1;
1155     }
1156     if (rc.targets[NEGATIVE] >= 0 && counts[NEGATIVE] == rc.targets[NEGATIVE]) {
1157         debug(("%s %d has now filled NEGATIVE:", rc.name, rc.num));
1158         clearneg = 1;
1159     }
1160
1161     if (!clearpos && !clearneg) return 0;
1162
1163     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1164         if (state->flags[i] & GS_SET) continue;
1165         if (state->flags[i] & GS_MARK) continue;
1166
1167         if (clearpos && !(state->flags[i] & GS_NOTPOSITIVE)) {
1168             if (solve_unflag(state, i, POSITIVE, "row/col full (+ve) [tricky]", &rc) < 0)
1169                 return -1;
1170             ret++;
1171         }
1172         if (clearneg && !(state->flags[i] & GS_NOTNEGATIVE)) {
1173             if (solve_unflag(state, i, NEGATIVE, "row/col full (-ve) [tricky]", &rc) < 0)
1174                 return -1;
1175             ret++;
1176         }
1177     }
1178
1179     return ret;
1180 }
1181
1182 /* If we only have one neutral still to place on a row/column then no
1183    dominoes entirely in that row/column can be neutral. */
1184 static int solve_nonneutral(game_state *state, rowcol rc, int *counts)
1185 {
1186     int i, j, ret = 0;
1187
1188     if (rc.targets[NEUTRAL] != counts[NEUTRAL]+1)
1189         return 0;
1190
1191     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1192         if (state->flags[i] & GS_SET) continue;
1193         if (state->common->dominoes[i] != i+rc.di) continue;
1194
1195         if (!(state->flags[i] & GS_NOTNEUTRAL)) {
1196             if (solve_unflag(state, i, NEUTRAL, "single neutral in row/col [tricky]", &rc) < 0)
1197                 return -1;
1198             ret++;
1199         }
1200     }
1201     return ret;
1202 }
1203
1204 /* If we need to fill all unfilled cells with +-, and we need 1 more of
1205  * one than the other, and we have a single odd-numbered region of unfilled
1206  * cells, that odd-numbered region must start and end with the extra number. */
1207 static int solve_oddlength(game_state *state, rowcol rc, int *counts)
1208 {
1209     int i, j, ret = 0, extra, tpos, tneg;
1210     int start = -1, length = 0, inempty = 0, startodd = -1;
1211
1212     /* need zero neutral cells still to find... */
1213     if (rc.targets[NEUTRAL] != counts[NEUTRAL])
1214         return 0;
1215
1216     /* ...and #positive and #negative to differ by one. */
1217     tpos = rc.targets[POSITIVE] - counts[POSITIVE];
1218     tneg = rc.targets[NEGATIVE] - counts[NEGATIVE];
1219     if (tpos == tneg+1)
1220         extra = POSITIVE;
1221     else if (tneg == tpos+1)
1222         extra = NEGATIVE;
1223     else return 0;
1224
1225     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1226         if (state->flags[i] & GS_SET) {
1227             if (inempty) {
1228                 if (length % 2) {
1229                     /* we've just finished an odd-length section. */
1230                     if (startodd != -1) goto twoodd;
1231                     startodd = start;
1232                 }
1233                 inempty = 0;
1234             }
1235         } else {
1236             if (inempty)
1237                 length++;
1238             else {
1239                 start = i;
1240                 length = 1;
1241                 inempty = 1;
1242             }
1243         }
1244     }
1245     if (inempty && (length % 2)) {
1246         if (startodd != -1) goto twoodd;
1247         startodd = start;
1248     }
1249     if (startodd != -1)
1250         ret = solve_set(state, startodd, extra, "odd-length section start", &rc);
1251
1252     return ret;
1253
1254 twoodd:
1255     debug(("%s %d has >1 odd-length sections, starting at %d,%d and %d,%d.",
1256            rc.name, rc.num,
1257            startodd%state->w, startodd/state->w,
1258            start%state->w, start/state->w));
1259     return 0;
1260 }
1261
1262 /* Count the number of remaining empty dominoes in any row/col.
1263  * If that number is equal to the #remaining positive,
1264  * or to the #remaining negative, no empty cells can be neutral. */
1265 static int solve_countdominoes_neutral(game_state *state, rowcol rc, int *counts)
1266 {
1267     int i, j, ndom = 0, nonn = 0, ret = 0;
1268
1269     if ((rc.targets[POSITIVE] == -1) && (rc.targets[NEGATIVE] == -1))
1270         return 0; /* need at least one target to compare. */
1271
1272     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1273         if (state->flags[i] & GS_SET) continue;
1274         assert(state->grid[i] == EMPTY);
1275
1276         /* Skip solo cells, or second cell in domino. */
1277         if ((state->common->dominoes[i] == i) ||
1278             (state->common->dominoes[i] == i-rc.di))
1279             continue;
1280
1281         ndom++;
1282     }
1283
1284     if ((rc.targets[POSITIVE] != -1) &&
1285         (rc.targets[POSITIVE]-counts[POSITIVE] == ndom))
1286         nonn = 1;
1287     if ((rc.targets[NEGATIVE] != -1) &&
1288         (rc.targets[NEGATIVE]-counts[NEGATIVE] == ndom))
1289         nonn = 1;
1290
1291     if (!nonn) return 0;
1292
1293     for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1294         if (state->flags[i] & GS_SET) continue;
1295
1296         if (!(state->flags[i] & GS_NOTNEUTRAL)) {
1297             if (solve_unflag(state, i, NEUTRAL, "all dominoes +/- [tricky]", &rc) < 0)
1298                 return -1;
1299             ret++;
1300         }
1301     }
1302     return ret;
1303 }
1304
1305 static int solve_domino_count(game_state *state, rowcol rc, int i, int which)
1306 {
1307     int nposs = 0;
1308
1309     /* Skip solo cells or 2nd in domino. */
1310     if ((state->common->dominoes[i] == i) ||
1311         (state->common->dominoes[i] == i-rc.di))
1312         return 0;
1313
1314     if (state->flags[i] & GS_SET)
1315         return 0;
1316
1317     if (POSSIBLE(i, which))
1318         nposs++;
1319
1320     if (state->common->dominoes[i] == i+rc.di) {
1321         /* second cell of domino is on our row: test that too. */
1322         if (POSSIBLE(i+rc.di, which))
1323             nposs++;
1324     }
1325     return nposs;
1326 }
1327
1328 /* Count number of dominoes we could put each of + and - into. If it is equal
1329  * to the #left, any domino we can only put + or - in one cell of must have it. */
1330 static int solve_countdominoes_nonneutral(game_state *state, rowcol rc, int *counts)
1331 {
1332     int which, w, i, j, ndom = 0, didsth = 0, toset;
1333
1334     for (which = POSITIVE, w = 0; w < 2; which = OPPOSITE(which), w++) {
1335         if (rc.targets[which] == -1) continue;
1336
1337         for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1338             if (solve_domino_count(state, rc, i, which) > 0)
1339                 ndom++;
1340         }
1341
1342         if ((rc.targets[which] - counts[which]) != ndom)
1343             continue;
1344
1345         for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
1346             if (solve_domino_count(state, rc, i, which) == 1) {
1347                 if (POSSIBLE(i, which))
1348                     toset = i;
1349                 else {
1350                     /* paranoia, should have been checked by solve_domino_count. */
1351                     assert(state->common->dominoes[i] == i+rc.di);
1352                     assert(POSSIBLE(i+rc.di, which));
1353                     toset = i+rc.di;
1354                 }
1355                 if (solve_set(state, toset, which, "all empty dominoes need +/- [tricky]", &rc) < 0)
1356                     return -1;
1357                 didsth++;
1358             }
1359         }
1360     }
1361     return didsth;
1362 }
1363
1364 /* danger, evil macro. can't use the do { ... } while(0) trick because
1365  * the continue breaks. */
1366 #define SOLVE_FOR_ROWCOLS(fn) \
1367     ret = solve_rowcols(state, fn); \
1368     if (ret < 0) { debug(("%s said impossible, cannot solve", #fn)); return -1; } \
1369     if (ret > 0) continue
1370
1371 static int solve_state(game_state *state, int diff)
1372 {
1373     int ret;
1374
1375     debug(("solve_state, difficulty %s", magnets_diffnames[diff]));
1376
1377     solve_clearflags(state);
1378     if (solve_startflags(state) < 0) return -1;
1379
1380     while (1) {
1381         ret = solve_force(state);
1382         if (ret > 0) continue;
1383         if (ret < 0) return -1;
1384
1385         ret = solve_neither(state);
1386         if (ret > 0) continue;
1387         if (ret < 0) return -1;
1388
1389         SOLVE_FOR_ROWCOLS(solve_checkfull);
1390         SOLVE_FOR_ROWCOLS(solve_oddlength);
1391
1392         if (diff < DIFF_TRICKY) break;
1393
1394         SOLVE_FOR_ROWCOLS(solve_advancedfull);
1395         SOLVE_FOR_ROWCOLS(solve_nonneutral);
1396         SOLVE_FOR_ROWCOLS(solve_countdominoes_neutral);
1397         SOLVE_FOR_ROWCOLS(solve_countdominoes_nonneutral);
1398
1399         /* more ... */
1400
1401         break;
1402     }
1403     return check_completion(state);
1404 }
1405
1406
1407 static char *game_state_diff(const game_state *src, const game_state *dst,
1408                              int issolve)
1409 {
1410     char *ret = NULL, buf[80], c;
1411     int retlen = 0, x, y, i, k;
1412
1413     assert(src->w == dst->w && src->h == dst->h);
1414
1415     if (issolve) {
1416         ret = sresize(ret, 3, char);
1417         ret[0] = 'S'; ret[1] = ';'; ret[2] = '\0';
1418         retlen += 2;
1419     }
1420     for (x = 0; x < dst->w; x++) {
1421         for (y = 0; y < dst->h; y++) {
1422             i = y*dst->w+x;
1423
1424             if (src->common->dominoes[i] == i) continue;
1425
1426 #define APPEND do { \
1427     ret = sresize(ret, retlen + k + 1, char); \
1428     strcpy(ret + retlen, buf); \
1429     retlen += k; \
1430 } while(0)
1431
1432             if ((src->grid[i] != dst->grid[i]) ||
1433                 ((src->flags[i] & GS_SET) != (dst->flags[i] & GS_SET))) {
1434                 if (dst->grid[i] == EMPTY && !(dst->flags[i] & GS_SET))
1435                     c = ' ';
1436                 else
1437                     c = GRID2CHAR(dst->grid[i]);
1438                 k = sprintf(buf, "%c%d,%d;", (int)c, x, y);
1439                 APPEND;
1440             }
1441         }
1442     }
1443     debug(("game_state_diff returns %s", ret));
1444     return ret;
1445 }
1446
1447 static void solve_from_aux(const game_state *state, const char *aux)
1448 {
1449     int i;
1450     assert(strlen(aux) == state->wh);
1451     for (i = 0; i < state->wh; i++) {
1452         state->grid[i] = CHAR2GRID(aux[i]);
1453         state->flags[i] |= GS_SET;
1454     }
1455 }
1456
1457 static char *solve_game(const game_state *state, const game_state *currstate,
1458                         const char *aux, char **error)
1459 {
1460     game_state *solved = dup_game(currstate);
1461     char *move = NULL;
1462     int ret;
1463
1464     if (aux && strlen(aux) == state->wh) {
1465         solve_from_aux(solved, aux);
1466         goto solved;
1467     }
1468
1469     if (solve_state(solved, DIFFCOUNT) > 0) goto solved;
1470     free_game(solved);
1471
1472     solved = dup_game(state);
1473     ret = solve_state(solved, DIFFCOUNT);
1474     if (ret > 0) goto solved;
1475     free_game(solved);
1476
1477     *error = (ret < 0) ? "Puzzle is impossible." : "Unable to solve puzzle.";
1478     return NULL;
1479
1480 solved:
1481     move = game_state_diff(currstate, solved, 1);
1482     free_game(solved);
1483     return move;
1484 }
1485
1486 static int solve_unnumbered(game_state *state)
1487 {
1488     int i, ret;
1489     while (1) {
1490         ret = solve_force(state);
1491         if (ret > 0) continue;
1492         if (ret < 0) return -1;
1493
1494         ret = solve_neither(state);
1495         if (ret > 0) continue;
1496         if (ret < 0) return -1;
1497
1498         break;
1499     }
1500     for (i = 0; i < state->wh; i++) {
1501         if (!(state->flags[i] & GS_SET)) return 0;
1502     }
1503     return 1;
1504 }
1505
1506 static int lay_dominoes(game_state *state, random_state *rs, int *scratch)
1507 {
1508     int n, i, ret = 0, nlaid = 0, n_initial_neutral;
1509
1510     for (i = 0; i < state->wh; i++) {
1511         scratch[i] = i;
1512         state->grid[i] = EMPTY;
1513         state->flags[i] = (state->common->dominoes[i] == i) ? GS_SET : 0;
1514     }
1515     shuffle(scratch, state->wh, sizeof(int), rs);
1516
1517     n_initial_neutral = (state->wh > 100) ? 5 : (state->wh / 10);
1518
1519     for (n = 0; n < state->wh; n++) {
1520         /* Find a space ... */
1521
1522         i = scratch[n];
1523         if (state->flags[i] & GS_SET) continue; /* already laid here. */
1524
1525         /* ...and lay a domino if we can. */
1526
1527         debug(("Laying domino at i:%d, (%d,%d)\n", i, i%state->w, i/state->w));
1528
1529         /* The choice of which type of domino to lay here leads to subtle differences
1530          * in the sorts of boards that get produced. Too much bias towards magnets
1531          * leads to games that are too easy.
1532          *
1533          * Currently, it lays a small set of dominoes at random as neutral, and
1534          * then lays the rest preferring to be magnets -- however, if the
1535          * current layout is such that a magnet won't go there, then it lays
1536          * another neutral.
1537          *
1538          * The number of initially neutral dominoes is limited as grids get bigger:
1539          * too many neutral dominoes invariably ends up with insoluble puzzle at
1540          * this size, and the positioning process means it'll always end up laying
1541          * more than the initial 5 anyway.
1542          */
1543
1544         /* We should always be able to lay a neutral anywhere. */
1545         assert(!(state->flags[i] & GS_NOTNEUTRAL));
1546
1547         if (n < n_initial_neutral) {
1548             debug(("  ...laying neutral\n"));
1549             ret = solve_set(state, i, NEUTRAL, "layout initial neutral", NULL);
1550         } else {
1551             debug(("  ... preferring magnet\n"));
1552             if (!(state->flags[i] & GS_NOTPOSITIVE))
1553                 ret = solve_set(state, i, POSITIVE, "layout", NULL);
1554             else if (!(state->flags[i] & GS_NOTNEGATIVE))
1555                 ret = solve_set(state, i, NEGATIVE, "layout", NULL);
1556             else
1557                 ret = solve_set(state, i, NEUTRAL, "layout", NULL);
1558         }
1559         if (!ret) {
1560             debug(("Unable to lay anything at (%d,%d), giving up.",
1561                    i%state->w, i/state->w));
1562             ret = -1;
1563             break;
1564         }
1565
1566         nlaid++;
1567         ret = solve_unnumbered(state);
1568         if (ret == -1)
1569             debug(("solve_unnumbered decided impossible.\n"));
1570         if (ret != 0)
1571             break;
1572     }
1573
1574     debug(("Laid %d dominoes, total %d dominoes.\n", nlaid, state->wh/2));
1575     game_debug(state, "Final layout");
1576     return ret;
1577 }
1578
1579 static void gen_game(game_state *new, random_state *rs)
1580 {
1581     int ret, x, y, val;
1582     int *scratch = snewn(new->wh, int);
1583
1584 #ifdef STANDALONE_SOLVER
1585     if (verbose) printf("Generating new game...\n");
1586 #endif
1587
1588     clear_state(new);
1589     sfree(new->common->dominoes); /* bit grotty. */
1590     new->common->dominoes = domino_layout(new->w, new->h, rs);
1591
1592     do {
1593         ret = lay_dominoes(new, rs, scratch);
1594     } while(ret == -1);
1595
1596     /* for each cell, update colcount/rowcount as appropriate. */
1597     memset(new->common->colcount, 0, new->w*3*sizeof(int));
1598     memset(new->common->rowcount, 0, new->h*3*sizeof(int));
1599     for (x = 0; x < new->w; x++) {
1600         for (y = 0; y < new->h; y++) {
1601             val = new->grid[y*new->w+x];
1602             new->common->colcount[x*3+val]++;
1603             new->common->rowcount[y*3+val]++;
1604         }
1605     }
1606     new->numbered = 1;
1607
1608     sfree(scratch);
1609 }
1610
1611 static void generate_aux(game_state *new, char *aux)
1612 {
1613     int i;
1614     for (i = 0; i < new->wh; i++)
1615         aux[i] = GRID2CHAR(new->grid[i]);
1616     aux[new->wh] = '\0';
1617 }
1618
1619 static int check_difficulty(const game_params *params, game_state *new,
1620                             random_state *rs)
1621 {
1622     int *scratch, *grid_correct, slen, i;
1623
1624     memset(new->grid, EMPTY, new->wh*sizeof(int));
1625
1626     if (params->diff > DIFF_EASY) {
1627         /* If this is too easy, return. */
1628         if (solve_state(new, params->diff-1) > 0) {
1629             debug(("Puzzle is too easy."));
1630             return -1;
1631         }
1632     }
1633     if (solve_state(new, params->diff) <= 0) {
1634         debug(("Puzzle is not soluble at requested difficulty."));
1635         return -1;
1636     }
1637     if (!params->stripclues) return 0;
1638
1639     /* Copy the correct grid away. */
1640     grid_correct = snewn(new->wh, int);
1641     memcpy(grid_correct, new->grid, new->wh*sizeof(int));
1642
1643     /* Create shuffled array of side-clue locations. */
1644     slen = new->w*2 + new->h*2;
1645     scratch = snewn(slen, int);
1646     for (i = 0; i < slen; i++) scratch[i] = i;
1647     shuffle(scratch, slen, sizeof(int), rs);
1648
1649     /* For each clue, check whether removing it makes the puzzle unsoluble;
1650      * put it back if so. */
1651     for (i = 0; i < slen; i++) {
1652         int num = scratch[i], which, roworcol, target, targetn, ret;
1653         rowcol rc;
1654
1655         /* work out which clue we meant. */
1656         if (num < new->w+new->h) { which = POSITIVE; }
1657         else { which = NEGATIVE; num -= new->w+new->h; }
1658
1659         if (num < new->w) { roworcol = COLUMN; }
1660         else { roworcol = ROW; num -= new->w; }
1661
1662         /* num is now the row/column index in question. */
1663         rc = mkrowcol(new, num, roworcol);
1664
1665         /* Remove clue, storing original... */
1666         target = rc.targets[which];
1667         targetn = rc.targets[NEUTRAL];
1668         rc.targets[which] = -1;
1669         rc.targets[NEUTRAL] = -1;
1670
1671         /* ...and see if we can still solve it. */
1672         game_debug(new, "removed clue, new board:");
1673         memset(new->grid, EMPTY, new->wh * sizeof(int));
1674         ret = solve_state(new, params->diff);
1675         assert(ret != -1);
1676
1677         if (ret == 0 ||
1678             memcmp(new->grid, grid_correct, new->wh*sizeof(int)) != 0) {
1679             /* We made it ambiguous: put clue back. */
1680             debug(("...now impossible/different, put clue back."));
1681             rc.targets[which] = target;
1682             rc.targets[NEUTRAL] = targetn;
1683         }
1684     }
1685     sfree(scratch);
1686     sfree(grid_correct);
1687
1688     return 0;
1689 }
1690
1691 static char *new_game_desc(const game_params *params, random_state *rs,
1692                            char **aux_r, int interactive)
1693 {
1694     game_state *new = new_state(params->w, params->h);
1695     char *desc, *aux = snewn(new->wh+1, char);
1696
1697     do {
1698         gen_game(new, rs);
1699         generate_aux(new, aux);
1700     } while (check_difficulty(params, new, rs) < 0);
1701
1702     /* now we're complete, generate the description string
1703      * and an aux_info for the completed game. */
1704     desc = generate_desc(new);
1705
1706     free_game(new);
1707
1708     *aux_r = aux;
1709     return desc;
1710 }
1711
1712 struct game_ui {
1713     int cur_x, cur_y, cur_visible;
1714 };
1715
1716 static game_ui *new_ui(const game_state *state)
1717 {
1718     game_ui *ui = snew(game_ui);
1719     ui->cur_x = ui->cur_y = 0;
1720     ui->cur_visible = 0;
1721     return ui;
1722 }
1723
1724 static void free_ui(game_ui *ui)
1725 {
1726     sfree(ui);
1727 }
1728
1729 static char *encode_ui(const game_ui *ui)
1730 {
1731     return NULL;
1732 }
1733
1734 static void decode_ui(game_ui *ui, const char *encoding)
1735 {
1736 }
1737
1738 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1739                                const game_state *newstate)
1740 {
1741     if (!oldstate->completed && newstate->completed)
1742         ui->cur_visible = 0;
1743 }
1744
1745 struct game_drawstate {
1746     int tilesize, started, solved;
1747     int w, h;
1748     unsigned long *what;                /* size w*h */
1749     unsigned long *colwhat, *rowwhat;   /* size 3*w, 3*h */
1750 };
1751
1752 #define DS_WHICH_MASK 0xf
1753
1754 #define DS_ERROR    0x10
1755 #define DS_CURSOR   0x20
1756 #define DS_SET      0x40
1757 #define DS_NOTPOS   0x80
1758 #define DS_NOTNEG   0x100
1759 #define DS_NOTNEU   0x200
1760 #define DS_FLASH    0x400
1761
1762 #define PREFERRED_TILE_SIZE 32
1763 #define TILE_SIZE (ds->tilesize)
1764 #define BORDER    (TILE_SIZE / 8)
1765
1766 #define COORD(x) ( (x+1) * TILE_SIZE + BORDER )
1767 #define FROMCOORD(x) ( (x - BORDER) / TILE_SIZE - 1 )
1768
1769 static int is_clue(const game_state *state, int x, int y)
1770 {
1771     int h = state->h, w = state->w;
1772
1773     if (((x == -1 || x == w) && y >= 0 && y < h) ||
1774         ((y == -1 || y == h) && x >= 0 && x < w))
1775         return TRUE;
1776
1777     return FALSE;
1778 }
1779
1780 static int clue_index(const game_state *state, int x, int y)
1781 {
1782     int h = state->h, w = state->w;
1783
1784     if (y == -1)
1785         return x;
1786     else if (x == w)
1787         return w + y;
1788     else if (y == h)
1789         return 2 * w + h - x - 1;
1790     else if (x == -1)
1791         return 2 * (w + h) - y - 1;
1792
1793     return -1;
1794 }
1795
1796 static char *interpret_move(const game_state *state, game_ui *ui,
1797                             const game_drawstate *ds,
1798                             int x, int y, int button)
1799 {
1800     int gx = FROMCOORD(x), gy = FROMCOORD(y), idx, curr;
1801     char *nullret = NULL, buf[80], movech;
1802     enum { CYCLE_MAGNET, CYCLE_NEUTRAL } action;
1803
1804     if (IS_CURSOR_MOVE(button)) {
1805         move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, 0);
1806         ui->cur_visible = 1;
1807         return "";
1808     } else if (IS_CURSOR_SELECT(button)) {
1809         if (!ui->cur_visible) {
1810             ui->cur_visible = 1;
1811             return "";
1812         }
1813         action = (button == CURSOR_SELECT) ? CYCLE_MAGNET : CYCLE_NEUTRAL;
1814         gx = ui->cur_x;
1815         gy = ui->cur_y;
1816     } else if (INGRID(state, gx, gy) &&
1817                (button == LEFT_BUTTON || button == RIGHT_BUTTON)) {
1818         if (ui->cur_visible) {
1819             ui->cur_visible = 0;
1820             nullret = "";
1821         }
1822         action = (button == LEFT_BUTTON) ? CYCLE_MAGNET : CYCLE_NEUTRAL;
1823     } else if (button == LEFT_BUTTON && is_clue(state, gx, gy)) {
1824         sprintf(buf, "D%d,%d", gx, gy);
1825         return dupstr(buf);
1826     } else
1827         return NULL;
1828
1829     idx = gy * state->w + gx;
1830     if (state->common->dominoes[idx] == idx) return nullret;
1831     curr = state->grid[idx];
1832
1833     if (action == CYCLE_MAGNET) {
1834         /* ... empty --> positive --> negative --> empty ... */
1835
1836         if (state->grid[idx] == NEUTRAL && state->flags[idx] & GS_SET)
1837             return nullret; /* can't cycle a magnet from a neutral. */
1838         movech = (curr == EMPTY) ? '+' : (curr == POSITIVE) ? '-' : ' ';
1839     } else if (action == CYCLE_NEUTRAL) {
1840         /* ... empty -> neutral -> !neutral --> empty ... */
1841
1842         if (state->grid[idx] != NEUTRAL)
1843             return nullret; /* can't cycle through neutral from a magnet. */
1844
1845         /* All of these are grid == EMPTY == NEUTRAL; it twiddles
1846          * combinations of flags. */
1847         if (state->flags[idx] & GS_SET) /* neutral */
1848             movech = '?';
1849         else if (state->flags[idx] & GS_NOTNEUTRAL) /* !neutral */
1850             movech = ' ';
1851         else
1852             movech = '.';
1853     } else {
1854         assert(!"unknown action");
1855         movech = 0;                    /* placate optimiser */
1856     }
1857
1858     sprintf(buf, "%c%d,%d", movech, gx, gy);
1859
1860     return dupstr(buf);
1861 }
1862
1863 static game_state *execute_move(const game_state *state, const char *move)
1864 {
1865     game_state *ret = dup_game(state);
1866     int x, y, n, idx, idx2;
1867     char c;
1868
1869     if (!*move) goto badmove;
1870     while (*move) {
1871         c = *move++;
1872         if (c == 'S') {
1873             ret->solved = TRUE;
1874             n = 0;
1875         } else if (c == '+' || c == '-' ||
1876                    c == '.' || c == ' ' || c == '?') {
1877             if ((sscanf(move, "%d,%d%n", &x, &y, &n) != 2) ||
1878                 !INGRID(state, x, y)) goto badmove;
1879
1880             idx = y*state->w + x;
1881             idx2 = state->common->dominoes[idx];
1882             if (idx == idx2) goto badmove;
1883
1884             ret->flags[idx] &= ~GS_NOTMASK;
1885             ret->flags[idx2] &= ~GS_NOTMASK;
1886
1887             if (c == ' ' || c == '?') {
1888                 ret->grid[idx] = EMPTY;
1889                 ret->grid[idx2] = EMPTY;
1890                 ret->flags[idx] &= ~GS_SET;
1891                 ret->flags[idx2] &= ~GS_SET;
1892                 if (c == '?') {
1893                     ret->flags[idx] |= GS_NOTNEUTRAL;
1894                     ret->flags[idx2] |= GS_NOTNEUTRAL;
1895                 }
1896             } else {
1897                 ret->grid[idx] = CHAR2GRID(c);
1898                 ret->grid[idx2] = OPPOSITE(CHAR2GRID(c));
1899                 ret->flags[idx] |= GS_SET;
1900                 ret->flags[idx2] |= GS_SET;
1901             }
1902         } else if (c == 'D' && sscanf(move, "%d,%d%n", &x, &y, &n) == 2 &&
1903                    is_clue(ret, x, y)) {
1904             ret->counts_done[clue_index(ret, x, y)] ^= 1;
1905         } else
1906             goto badmove;
1907
1908         move += n;
1909         if (*move == ';') move++;
1910         else if (*move) goto badmove;
1911     }
1912     if (check_completion(ret) == 1)
1913         ret->completed = 1;
1914
1915     return ret;
1916
1917 badmove:
1918     free_game(ret);
1919     return NULL;
1920 }
1921
1922 /* ----------------------------------------------------------------------
1923  * Drawing routines.
1924  */
1925
1926 static void game_compute_size(const game_params *params, int tilesize,
1927                               int *x, int *y)
1928 {
1929     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1930     struct { int tilesize; } ads, *ds = &ads;
1931     ads.tilesize = tilesize;
1932
1933     *x = TILE_SIZE * (params->w+2) + 2 * BORDER;
1934     *y = TILE_SIZE * (params->h+2) + 2 * BORDER;
1935 }
1936
1937 static void game_set_size(drawing *dr, game_drawstate *ds,
1938                           const game_params *params, int tilesize)
1939 {
1940     ds->tilesize = tilesize;
1941 }
1942
1943 static float *game_colours(frontend *fe, int *ncolours)
1944 {
1945     float *ret = snewn(3 * NCOLOURS, float);
1946     int i;
1947
1948     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1949
1950     for (i = 0; i < 3; i++) {
1951         ret[COL_TEXT * 3 + i] = 0.0F;
1952         ret[COL_NEGATIVE * 3 + i] = 0.0F;
1953         ret[COL_CURSOR * 3 + i] = 0.9F;
1954         ret[COL_DONE * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.5F;
1955     }
1956
1957     ret[COL_POSITIVE * 3 + 0] = 0.8F;
1958     ret[COL_POSITIVE * 3 + 1] = 0.0F;
1959     ret[COL_POSITIVE * 3 + 2] = 0.0F;
1960
1961     ret[COL_NEUTRAL * 3 + 0] = 0.10F;
1962     ret[COL_NEUTRAL * 3 + 1] = 0.60F;
1963     ret[COL_NEUTRAL * 3 + 2] = 0.10F;
1964
1965     ret[COL_ERROR * 3 + 0] = 1.0F;
1966     ret[COL_ERROR * 3 + 1] = 0.0F;
1967     ret[COL_ERROR * 3 + 2] = 0.0F;
1968
1969     ret[COL_NOT * 3 + 0] = 0.2F;
1970     ret[COL_NOT * 3 + 1] = 0.2F;
1971     ret[COL_NOT * 3 + 2] = 1.0F;
1972
1973     *ncolours = NCOLOURS;
1974     return ret;
1975 }
1976
1977 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1978 {
1979     struct game_drawstate *ds = snew(struct game_drawstate);
1980
1981     ds->tilesize = ds->started = ds->solved = 0;
1982     ds->w = state->w;
1983     ds->h = state->h;
1984
1985     ds->what = snewn(state->wh, unsigned long);
1986     memset(ds->what, 0, state->wh*sizeof(unsigned long));
1987
1988     ds->colwhat = snewn(state->w*3, unsigned long);
1989     memset(ds->colwhat, 0, state->w*3*sizeof(unsigned long));
1990     ds->rowwhat = snewn(state->h*3, unsigned long);
1991     memset(ds->rowwhat, 0, state->h*3*sizeof(unsigned long));
1992
1993     return ds;
1994 }
1995
1996 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1997 {
1998     sfree(ds->colwhat);
1999     sfree(ds->rowwhat);
2000     sfree(ds->what);
2001     sfree(ds);
2002 }
2003
2004 static void draw_num(drawing *dr, game_drawstate *ds, int rowcol, int which,
2005                          int idx, int colbg, int col, int num)
2006 {
2007     char buf[32];
2008     int cx, cy, tsz;
2009
2010     if (num < 0) return;
2011
2012     sprintf(buf, "%d", num);
2013     tsz = (strlen(buf) == 1) ? (7*TILE_SIZE/10) : (9*TILE_SIZE/10)/strlen(buf);
2014
2015     if (rowcol == ROW) {
2016         cx = BORDER;
2017         if (which == NEGATIVE) cx += TILE_SIZE * (ds->w+1);
2018         cy = BORDER + TILE_SIZE * (idx+1);
2019     } else {
2020         cx = BORDER + TILE_SIZE * (idx+1);
2021         cy = BORDER;
2022         if (which == NEGATIVE) cy += TILE_SIZE * (ds->h+1);
2023     }
2024
2025     draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, colbg);
2026     draw_text(dr, cx + TILE_SIZE/2, cy + TILE_SIZE/2, FONT_VARIABLE, tsz,
2027               ALIGN_VCENTRE | ALIGN_HCENTRE, col, buf);
2028
2029     draw_update(dr, cx, cy, TILE_SIZE, TILE_SIZE);
2030 }
2031
2032 static void draw_sym(drawing *dr, game_drawstate *ds, int x, int y, int which, int col)
2033 {
2034     int cx = COORD(x), cy = COORD(y);
2035     int ccx = cx + TILE_SIZE/2, ccy = cy + TILE_SIZE/2;
2036     int roff = TILE_SIZE/4, rsz = 2*roff+1;
2037     int soff = TILE_SIZE/16, ssz = 2*soff+1;
2038
2039     if (which == POSITIVE || which == NEGATIVE) {
2040         draw_rect(dr, ccx - roff, ccy - soff, rsz, ssz, col);
2041         if (which == POSITIVE)
2042             draw_rect(dr, ccx - soff, ccy - roff, ssz, rsz, col);
2043     } else if (col == COL_NOT) {
2044         /* not-a-neutral is a blue question mark. */
2045         char qu[2] = { '?', 0 };
2046         draw_text(dr, ccx, ccy, FONT_VARIABLE, 7*TILE_SIZE/10,
2047                   ALIGN_VCENTRE | ALIGN_HCENTRE, col, qu);
2048     } else {
2049         draw_line(dr, ccx - roff, ccy - roff, ccx + roff, ccy + roff, col);
2050         draw_line(dr, ccx + roff, ccy - roff, ccx - roff, ccy + roff, col);
2051     }
2052 }
2053
2054 enum {
2055     TYPE_L,
2056     TYPE_R,
2057     TYPE_T,
2058     TYPE_B,
2059     TYPE_BLANK
2060 };
2061
2062 /* NOT responsible for redrawing background or updating. */
2063 static void draw_tile_col(drawing *dr, game_drawstate *ds, int *dominoes,
2064                           int x, int y, int which, int bg, int fg, int perc)
2065 {
2066     int cx = COORD(x), cy = COORD(y), i, other, type = TYPE_BLANK;
2067     int gutter, radius, coffset;
2068
2069     /* gutter is TSZ/16 for 100%, 8*TSZ/16 (TSZ/2) for 0% */
2070     gutter = (TILE_SIZE / 16) + ((100 - perc) * (7*TILE_SIZE / 16))/100;
2071     radius = (perc * (TILE_SIZE / 8)) / 100;
2072     coffset = gutter + radius;
2073
2074     i = y*ds->w + x;
2075     other = dominoes[i];
2076
2077     if (other == i) return;
2078     else if (other == i+1) type = TYPE_L;
2079     else if (other == i-1) type = TYPE_R;
2080     else if (other == i+ds->w) type = TYPE_T;
2081     else if (other == i-ds->w) type = TYPE_B;
2082     else assert(!"mad domino orientation");
2083
2084     /* domino drawing shamelessly stolen from dominosa.c. */
2085     if (type == TYPE_L || type == TYPE_T)
2086         draw_circle(dr, cx+coffset, cy+coffset,
2087                     radius, bg, bg);
2088     if (type == TYPE_R || type == TYPE_T)
2089         draw_circle(dr, cx+TILE_SIZE-1-coffset, cy+coffset,
2090                     radius, bg, bg);
2091     if (type == TYPE_L || type == TYPE_B)
2092         draw_circle(dr, cx+coffset, cy+TILE_SIZE-1-coffset,
2093                     radius, bg, bg);
2094     if (type == TYPE_R || type == TYPE_B)
2095         draw_circle(dr, cx+TILE_SIZE-1-coffset,
2096                     cy+TILE_SIZE-1-coffset,
2097                     radius, bg, bg);
2098
2099     for (i = 0; i < 2; i++) {
2100         int x1, y1, x2, y2;
2101
2102         x1 = cx + (i ? gutter : coffset);
2103         y1 = cy + (i ? coffset : gutter);
2104         x2 = cx + TILE_SIZE-1 - (i ? gutter : coffset);
2105         y2 = cy + TILE_SIZE-1 - (i ? coffset : gutter);
2106         if (type == TYPE_L)
2107             x2 = cx + TILE_SIZE;
2108         else if (type == TYPE_R)
2109             x1 = cx;
2110         else if (type == TYPE_T)
2111             y2 = cy + TILE_SIZE ;
2112         else if (type == TYPE_B)
2113             y1 = cy;
2114
2115         draw_rect(dr, x1, y1, x2-x1+1, y2-y1+1, bg);
2116     }
2117
2118     if (fg != -1) draw_sym(dr, ds, x, y, which, fg);
2119 }
2120
2121 static void draw_tile(drawing *dr, game_drawstate *ds, int *dominoes,
2122                       int x, int y, unsigned long flags)
2123 {
2124     int cx = COORD(x), cy = COORD(y), bg, fg, perc = 100;
2125     int which = flags & DS_WHICH_MASK;
2126
2127     flags &= ~DS_WHICH_MASK;
2128
2129     draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
2130
2131     if (flags & DS_CURSOR)
2132         bg = COL_CURSOR;        /* off-white white for cursor */
2133     else if (which == POSITIVE)
2134         bg = COL_POSITIVE;
2135     else if (which == NEGATIVE)
2136         bg = COL_NEGATIVE;
2137     else if (flags & DS_SET)
2138         bg = COL_NEUTRAL;       /* green inner for neutral cells */
2139     else
2140         bg = COL_LOWLIGHT;      /* light grey for empty cells. */
2141
2142     if (which == EMPTY && !(flags & DS_SET)) {
2143         int notwhich = -1;
2144         fg = -1; /* don't draw cross unless actually set as neutral. */
2145
2146         if (flags & DS_NOTPOS) notwhich = POSITIVE;
2147         if (flags & DS_NOTNEG) notwhich = NEGATIVE;
2148         if (flags & DS_NOTNEU) notwhich = NEUTRAL;
2149         if (notwhich != -1) {
2150             which = notwhich;
2151             fg = COL_NOT;
2152         }
2153     } else
2154         fg = (flags & DS_ERROR) ? COL_ERROR :
2155              (flags & DS_CURSOR) ? COL_TEXT : COL_BACKGROUND;
2156
2157     draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
2158
2159     if (flags & DS_FLASH) {
2160         int bordercol = COL_HIGHLIGHT;
2161         draw_tile_col(dr, ds, dominoes, x, y, which, bordercol, -1, perc);
2162         perc = 3*perc/4;
2163     }
2164     draw_tile_col(dr, ds, dominoes, x, y, which, bg, fg, perc);
2165
2166     draw_update(dr, cx, cy, TILE_SIZE, TILE_SIZE);
2167 }
2168
2169 static int get_count_color(const game_state *state, int rowcol, int which,
2170                            int index, int target)
2171 {
2172     int idx;
2173     int count = count_rowcol(state, index, rowcol, which);
2174
2175     if ((count > target) ||
2176         (count < target && !count_rowcol(state, index, rowcol, -1))) {
2177         return COL_ERROR;
2178     } else if (rowcol == COLUMN) {
2179         idx = clue_index(state, index, which == POSITIVE ? -1 : state->h);
2180     } else {
2181         idx = clue_index(state, which == POSITIVE ? -1 : state->w, index);
2182     }
2183
2184     if (state->counts_done[idx]) {
2185         return COL_DONE;
2186     }
2187
2188     return COL_TEXT;
2189 }
2190
2191 static void game_redraw(drawing *dr, game_drawstate *ds,
2192                         const game_state *oldstate, const game_state *state,
2193                         int dir, const game_ui *ui,
2194                         float animtime, float flashtime)
2195 {
2196     int x, y, w = state->w, h = state->h, which, i, j, flash;
2197
2198     flash = (int)(flashtime * 5 / FLASH_TIME) % 2;
2199
2200     if (!ds->started) {
2201         /* draw background, corner +-. */
2202         draw_rect(dr, 0, 0,
2203                   TILE_SIZE * (w+2) + 2 * BORDER,
2204                   TILE_SIZE * (h+2) + 2 * BORDER,
2205                   COL_BACKGROUND);
2206
2207         draw_sym(dr, ds, -1, -1, POSITIVE, COL_TEXT);
2208         draw_sym(dr, ds, state->w, state->h, NEGATIVE, COL_TEXT);
2209
2210         draw_update(dr, 0, 0,
2211                     TILE_SIZE * (ds->w+2) + 2 * BORDER,
2212                     TILE_SIZE * (ds->h+2) + 2 * BORDER);
2213     }
2214
2215     /* Draw grid */
2216     for (y = 0; y < h; y++) {
2217         for (x = 0; x < w; x++) {
2218             int idx = y*w+x;
2219             unsigned long c = state->grid[idx];
2220
2221             if (state->flags[idx] & GS_ERROR)
2222                 c |= DS_ERROR;
2223             if (state->flags[idx] & GS_SET)
2224                 c |= DS_SET;
2225
2226             if (x == ui->cur_x && y == ui->cur_y && ui->cur_visible)
2227                 c |= DS_CURSOR;
2228
2229             if (flash)
2230                 c |= DS_FLASH;
2231
2232             if (state->flags[idx] & GS_NOTPOSITIVE)
2233                 c |= DS_NOTPOS;
2234             if (state->flags[idx] & GS_NOTNEGATIVE)
2235                 c |= DS_NOTNEG;
2236             if (state->flags[idx] & GS_NOTNEUTRAL)
2237                 c |= DS_NOTNEU;
2238
2239             if (ds->what[idx] != c || !ds->started) {
2240                 draw_tile(dr, ds, state->common->dominoes, x, y, c);
2241                 ds->what[idx] = c;
2242             }
2243         }
2244     }
2245     /* Draw counts around side */
2246     for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
2247         for (i = 0; i < w; i++) {
2248             int index = i * 3 + which;
2249             int target = state->common->colcount[index];
2250             int color = get_count_color(state, COLUMN, which, i, target);
2251
2252             if (color != ds->colwhat[index] || !ds->started) {
2253                 draw_num(dr, ds, COLUMN, which, i, COL_BACKGROUND, color, target);
2254                 ds->colwhat[index] = color;
2255             }
2256         }
2257         for (i = 0; i < h; i++) {
2258             int index = i * 3 + which;
2259             int target = state->common->rowcount[index];
2260             int color = get_count_color(state, ROW, which, i, target);
2261
2262             if (color != ds->rowwhat[index] || !ds->started) {
2263                 draw_num(dr, ds, ROW, which, i, COL_BACKGROUND, color, target);
2264                 ds->rowwhat[index] = color;
2265             }
2266         }
2267     }
2268
2269     ds->started = 1;
2270 }
2271
2272 static float game_anim_length(const game_state *oldstate,
2273                               const game_state *newstate, int dir, game_ui *ui)
2274 {
2275     return 0.0F;
2276 }
2277
2278 static float game_flash_length(const game_state *oldstate,
2279                                const game_state *newstate, int dir, game_ui *ui)
2280 {
2281     if (!oldstate->completed && newstate->completed &&
2282         !oldstate->solved && !newstate->solved)
2283         return FLASH_TIME;
2284     return 0.0F;
2285 }
2286
2287 static int game_status(const game_state *state)
2288 {
2289     return state->completed ? +1 : 0;
2290 }
2291
2292 static int game_timing_state(const game_state *state, game_ui *ui)
2293 {
2294     return TRUE;
2295 }
2296
2297 static void game_print_size(const game_params *params, float *x, float *y)
2298 {
2299     int pw, ph;
2300
2301     /*
2302      * I'll use 6mm squares by default.
2303      */
2304     game_compute_size(params, 600, &pw, &ph);
2305     *x = pw / 100.0F;
2306     *y = ph / 100.0F;
2307 }
2308
2309 static void game_print(drawing *dr, const game_state *state, int tilesize)
2310 {
2311     int w = state->w, h = state->h;
2312     int ink = print_mono_colour(dr, 0);
2313     int paper = print_mono_colour(dr, 1);
2314     int x, y, which, i, j;
2315
2316     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2317     game_drawstate ads, *ds = &ads;
2318     game_set_size(dr, ds, NULL, tilesize);
2319     ds->w = w; ds->h = h;
2320
2321     /* Border. */
2322     print_line_width(dr, TILE_SIZE/12);
2323
2324     /* Numbers and +/- for corners. */
2325     draw_sym(dr, ds, -1, -1, POSITIVE, ink);
2326     draw_sym(dr, ds, state->w, state->h, NEGATIVE, ink);
2327     for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
2328         for (i = 0; i < w; i++) {
2329             draw_num(dr, ds, COLUMN, which, i, paper, ink,
2330                          state->common->colcount[i*3+which]);
2331         }
2332         for (i = 0; i < h; i++) {
2333             draw_num(dr, ds, ROW, which, i, paper, ink,
2334                          state->common->rowcount[i*3+which]);
2335         }
2336     }
2337
2338     /* Dominoes. */
2339     for (x = 0; x < w; x++) {
2340         for (y = 0; y < h; y++) {
2341             i = y*state->w + x;
2342             if (state->common->dominoes[i] == i+1 ||
2343                 state->common->dominoes[i] == i+w) {
2344                 int dx = state->common->dominoes[i] == i+1 ? 2 : 1;
2345                 int dy = 3 - dx;
2346                 int xx, yy;
2347                 int cx = COORD(x), cy = COORD(y);
2348
2349                 print_line_width(dr, 0);
2350
2351                 /* Ink the domino */
2352                 for (yy = 0; yy < 2; yy++)
2353                     for (xx = 0; xx < 2; xx++)
2354                         draw_circle(dr,
2355                                     cx+xx*dx*TILE_SIZE+(1-2*xx)*3*TILE_SIZE/16,
2356                                     cy+yy*dy*TILE_SIZE+(1-2*yy)*3*TILE_SIZE/16,
2357                                     TILE_SIZE/8, ink, ink);
2358                 draw_rect(dr, cx + TILE_SIZE/16, cy + 3*TILE_SIZE/16,
2359                           dx*TILE_SIZE - 2*(TILE_SIZE/16),
2360                           dy*TILE_SIZE - 6*(TILE_SIZE/16), ink);
2361                 draw_rect(dr, cx + 3*TILE_SIZE/16, cy + TILE_SIZE/16,
2362                           dx*TILE_SIZE - 6*(TILE_SIZE/16),
2363                           dy*TILE_SIZE - 2*(TILE_SIZE/16), ink);
2364
2365                 /* Un-ink the domino interior */
2366                 for (yy = 0; yy < 2; yy++)
2367                     for (xx = 0; xx < 2; xx++)
2368                         draw_circle(dr,
2369                                     cx+xx*dx*TILE_SIZE+(1-2*xx)*3*TILE_SIZE/16,
2370                                     cy+yy*dy*TILE_SIZE+(1-2*yy)*3*TILE_SIZE/16,
2371                                     3*TILE_SIZE/32, paper, paper);
2372                 draw_rect(dr, cx + 3*TILE_SIZE/32, cy + 3*TILE_SIZE/16,
2373                           dx*TILE_SIZE - 2*(3*TILE_SIZE/32),
2374                           dy*TILE_SIZE - 6*(TILE_SIZE/16), paper);
2375                 draw_rect(dr, cx + 3*TILE_SIZE/16, cy + 3*TILE_SIZE/32,
2376                           dx*TILE_SIZE - 6*(TILE_SIZE/16),
2377                           dy*TILE_SIZE - 2*(3*TILE_SIZE/32), paper);
2378             }
2379         }
2380     }
2381
2382     /* Grid symbols (solution). */
2383     for (x = 0; x < w; x++) {
2384         for (y = 0; y < h; y++) {
2385             i = y*state->w + x;
2386             if ((state->grid[i] != NEUTRAL) || (state->flags[i] & GS_SET))
2387                 draw_sym(dr, ds, x, y, state->grid[i], ink);
2388         }
2389     }
2390 }
2391
2392 #ifdef COMBINED
2393 #define thegame magnets
2394 #endif
2395
2396 const struct game thegame = {
2397     "Magnets", "games.magnets", "magnets",
2398     default_params,
2399     game_fetch_preset,
2400     decode_params,
2401     encode_params,
2402     free_params,
2403     dup_params,
2404     TRUE, game_configure, custom_params,
2405     validate_params,
2406     new_game_desc,
2407     validate_desc,
2408     new_game,
2409     dup_game,
2410     free_game,
2411     TRUE, solve_game,
2412     TRUE, game_can_format_as_text_now, game_text_format,
2413     new_ui,
2414     free_ui,
2415     encode_ui,
2416     decode_ui,
2417     game_changed_state,
2418     interpret_move,
2419     execute_move,
2420     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2421     game_colours,
2422     game_new_drawstate,
2423     game_free_drawstate,
2424     game_redraw,
2425     game_anim_length,
2426     game_flash_length,
2427     game_status,
2428     TRUE, FALSE, game_print_size, game_print,
2429     FALSE,                             /* wants_statusbar */
2430     FALSE, game_timing_state,
2431     REQUIRE_RBUTTON,                   /* flags */
2432 };
2433
2434 #ifdef STANDALONE_SOLVER
2435
2436 #include <time.h>
2437 #include <stdarg.h>
2438
2439 const char *quis = NULL;
2440 int csv = 0;
2441
2442 void usage(FILE *out) {
2443     fprintf(out, "usage: %s [-v] [--print] <params>|<game id>\n", quis);
2444 }
2445
2446 void doprint(game_state *state)
2447 {
2448     char *fmt = game_text_format(state);
2449     printf("%s", fmt);
2450     sfree(fmt);
2451 }
2452
2453 static void pnum(int n, int ntot, const char *desc)
2454 {
2455     printf("%2.1f%% (%d) %s", (double)n*100.0 / (double)ntot, n, desc);
2456 }
2457
2458 static void start_soak(game_params *p, random_state *rs)
2459 {
2460     time_t tt_start, tt_now, tt_last;
2461     char *aux;
2462     game_state *s, *s2;
2463     int n = 0, nsolved = 0, nimpossible = 0, ntricky = 0, ret, i;
2464     long nn, nn_total = 0, nn_solved = 0, nn_tricky = 0;
2465
2466     tt_start = tt_now = time(NULL);
2467
2468     if (csv)
2469         printf("time, w, h,  #generated, #solved, #tricky, #impossible,  "
2470                "#neutral, #neutral/solved, #neutral/tricky\n");
2471     else
2472         printf("Soak-testing a %dx%d grid.\n", p->w, p->h);
2473
2474     s = new_state(p->w, p->h);
2475     aux = snewn(s->wh+1, char);
2476
2477     while (1) {
2478         gen_game(s, rs);
2479
2480         nn = 0;
2481         for (i = 0; i < s->wh; i++) {
2482             if (s->grid[i] == NEUTRAL) nn++;
2483         }
2484
2485         generate_aux(s, aux);
2486         memset(s->grid, EMPTY, s->wh * sizeof(int));
2487         s2 = dup_game(s);
2488
2489         ret = solve_state(s, DIFFCOUNT);
2490
2491         n++;
2492         nn_total += nn;
2493         if (ret > 0) {
2494             nsolved++;
2495             nn_solved += nn;
2496             if (solve_state(s2, DIFF_EASY) <= 0) {
2497                 ntricky++;
2498                 nn_tricky += nn;
2499             }
2500         } else if (ret < 0) {
2501             char *desc = generate_desc(s);
2502             solve_from_aux(s, aux);
2503             printf("Game considered impossible:\n  %dx%d:%s\n",
2504                     p->w, p->h, desc);
2505             sfree(desc);
2506             doprint(s);
2507             nimpossible++;
2508         }
2509
2510         free_game(s2);
2511
2512         tt_last = time(NULL);
2513         if (tt_last > tt_now) {
2514             tt_now = tt_last;
2515             if (csv) {
2516                 printf("%d,%d,%d, %d,%d,%d,%d, %ld,%ld,%ld\n",
2517                        (int)(tt_now - tt_start), p->w, p->h,
2518                        n, nsolved, ntricky, nimpossible,
2519                        nn_total, nn_solved, nn_tricky);
2520             } else {
2521                 printf("%d total, %3.1f/s, ",
2522                        n, (double)n / ((double)tt_now - tt_start));
2523                 pnum(nsolved, n, "solved"); printf(", ");
2524                 pnum(ntricky, n, "tricky");
2525                 if (nimpossible > 0)
2526                     pnum(nimpossible, n, "impossible");
2527                 printf("\n");
2528
2529                 printf("  overall %3.1f%% neutral (%3.1f%% for solved, %3.1f%% for tricky)\n",
2530                        (double)(nn_total * 100) / (double)(p->w * p->h * n),
2531                        (double)(nn_solved * 100) / (double)(p->w * p->h * nsolved),
2532                        (double)(nn_tricky * 100) / (double)(p->w * p->h * ntricky));
2533             }
2534         }
2535     }
2536     free_game(s);
2537     sfree(aux);
2538 }
2539
2540 int main(int argc, const char *argv[])
2541 {
2542     int print = 0, soak = 0, solved = 0, ret;
2543     char *id = NULL, *desc, *desc_gen = NULL, *err, *aux = NULL;
2544     game_state *s = NULL;
2545     game_params *p = NULL;
2546     random_state *rs = NULL;
2547     time_t seed = time(NULL);
2548
2549     setvbuf(stdout, NULL, _IONBF, 0);
2550
2551     quis = argv[0];
2552     while (--argc > 0) {
2553         char *p = (char*)(*++argv);
2554         if (!strcmp(p, "-v") || !strcmp(p, "--verbose")) {
2555             verbose = 1;
2556         } else if (!strcmp(p, "--csv")) {
2557             csv = 1;
2558         } else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
2559             seed = atoi(*++argv);
2560             argc--;
2561         } else if (!strcmp(p, "-p") || !strcmp(p, "--print")) {
2562             print = 1;
2563         } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
2564             soak = 1;
2565         } else if (*p == '-') {
2566             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2567             usage(stderr);
2568             exit(1);
2569         } else {
2570             id = p;
2571         }
2572     }
2573
2574     rs = random_new((void*)&seed, sizeof(time_t));
2575
2576     if (!id) {
2577         fprintf(stderr, "usage: %s [-v] [--soak] <params> | <game_id>\n", argv[0]);
2578         goto done;
2579     }
2580     desc = strchr(id, ':');
2581     if (desc) *desc++ = '\0';
2582
2583     p = default_params();
2584     decode_params(p, id);
2585     err = validate_params(p, 1);
2586     if (err) {
2587         fprintf(stderr, "%s: %s", argv[0], err);
2588         goto done;
2589     }
2590
2591     if (soak) {
2592         if (desc) {
2593             fprintf(stderr, "%s: --soak needs parameters, not description.\n", quis);
2594             goto done;
2595         }
2596         start_soak(p, rs);
2597         goto done;
2598     }
2599
2600     if (!desc)
2601         desc = desc_gen = new_game_desc(p, rs, &aux, 0);
2602
2603     err = validate_desc(p, desc);
2604     if (err) {
2605         fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
2606         goto done;
2607     }
2608     s = new_game(NULL, p, desc);
2609     printf("%s:%s (seed %ld)\n", id, desc, (long)seed);
2610     if (aux) {
2611         /* We just generated this ourself. */
2612         if (verbose || print) {
2613             doprint(s);
2614             solve_from_aux(s, aux);
2615             solved = 1;
2616         }
2617     } else {
2618         doprint(s);
2619         verbose = 1;
2620         ret = solve_state(s, DIFFCOUNT);
2621         if (ret < 0) printf("Puzzle is impossible.\n");
2622         else if (ret == 0) printf("Puzzle is ambiguous.\n");
2623         else printf("Puzzle was solved.\n");
2624         verbose = 0;
2625         solved = 1;
2626     }
2627     if (solved) doprint(s);
2628
2629 done:
2630     if (desc_gen) sfree(desc_gen);
2631     if (p) free_params(p);
2632     if (s) free_game(s);
2633     if (rs) random_free(rs);
2634     if (aux) sfree(aux);
2635
2636     return 0;
2637 }
2638
2639 #endif
2640
2641 /* vim: set shiftwidth=4 tabstop=8: */