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