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