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