chiark / gitweb /
Merge branch 'master' of https://git.tartarus.org/simon/puzzles into widelines
[sgt-puzzles.git] / towers.c
1 /*
2  * towers.c: the puzzle also known as 'Skyscrapers'.
3  *
4  * Possible future work:
5  *
6  *  - Relax the upper bound on grid size at 9?
7  *     + I'd need TOCHAR and FROMCHAR macros a bit like group's, to
8  *       be used wherever this code has +'0' or -'0'
9  *     + the pencil marks in the drawstate would need a separate
10  *       word to live in
11  *     + the clues outside the grid would have to cope with being
12  *       multi-digit, meaning in particular that the text formatting
13  *       would become more unpleasant
14  *     + most importantly, though, the solver just isn't fast
15  *       enough. Even at size 9 it can't really do the solver_hard
16  *       factorial-time enumeration at a sensible rate. Easy puzzles
17  *       higher than that would be possible, but more latin-squarey
18  *       than skyscrapery, as it were.
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #include <math.h>
27
28 #include "puzzles.h"
29 #include "latin.h"
30
31 /*
32  * Difficulty levels. I do some macro ickery here to ensure that my
33  * enum and the various forms of my name list always match up.
34  */
35 #define DIFFLIST(A) \
36     A(EASY,Easy,solver_easy,e) \
37     A(HARD,Hard,solver_hard,h) \
38     A(EXTREME,Extreme,NULL,x) \
39     A(UNREASONABLE,Unreasonable,NULL,u)
40 #define ENUM(upper,title,func,lower) DIFF_ ## upper,
41 #define TITLE(upper,title,func,lower) #title,
42 #define ENCODE(upper,title,func,lower) #lower
43 #define CONFIG(upper,title,func,lower) ":" #title
44 enum { DIFFLIST(ENUM) DIFFCOUNT };
45 static char const *const towers_diffnames[] = { DIFFLIST(TITLE) };
46 static char const towers_diffchars[] = DIFFLIST(ENCODE);
47 #define DIFFCONFIG DIFFLIST(CONFIG)
48
49 enum {
50     COL_BACKGROUND,
51     COL_GRID,
52     COL_USER,
53     COL_HIGHLIGHT,
54     COL_ERROR,
55     COL_PENCIL,
56     COL_DONE,
57     NCOLOURS
58 };
59
60 struct game_params {
61     int w, diff;
62 };
63
64 struct clues {
65     int refcount;
66     int w;
67     /*
68      * An array of 4w integers, of which:
69      *  - the first w run across the top
70      *  - the next w across the bottom
71      *  - the third w down the left
72      *  - the last w down the right.
73      */
74     int *clues;
75
76     /*
77      * An array of w*w digits.
78      */
79     digit *immutable;
80 };
81
82 /*
83  * Macros to compute clue indices and coordinates.
84  */
85 #define STARTSTEP(start, step, index, w) do { \
86     if (index < w) \
87         start = index, step = w; \
88     else if (index < 2*w) \
89         start = (w-1)*w+(index-w), step = -w; \
90     else if (index < 3*w) \
91         start = w*(index-2*w), step = 1; \
92     else \
93         start = w*(index-3*w)+(w-1), step = -1; \
94 } while (0)
95 #define CSTARTSTEP(start, step, index, w) \
96     STARTSTEP(start, step, (((index)+2*w)%(4*w)), w)
97 #define CLUEPOS(x, y, index, w) do { \
98     if (index < w) \
99         x = index, y = -1; \
100     else if (index < 2*w) \
101         x = index-w, y = w; \
102     else if (index < 3*w) \
103         x = -1, y = index-2*w; \
104     else \
105         x = w, y = index-3*w; \
106 } while (0)
107
108 #ifdef STANDALONE_SOLVER
109 static const char *const cluepos[] = {
110     "above column", "below column", "left of row", "right of row"
111 };
112 #endif
113
114 struct game_state {
115     game_params par;
116     struct clues *clues;
117     unsigned char *clues_done;
118     digit *grid;
119     int *pencil;                       /* bitmaps using bits 1<<1..1<<n */
120     int completed, cheated;
121 };
122
123 static game_params *default_params(void)
124 {
125     game_params *ret = snew(game_params);
126
127     ret->w = 5;
128     ret->diff = DIFF_EASY;
129
130     return ret;
131 }
132
133 const static struct game_params towers_presets[] = {
134     {  4, DIFF_EASY         },
135     {  5, DIFF_EASY         },
136     {  5, DIFF_HARD         },
137     {  6, DIFF_EASY         },
138     {  6, DIFF_HARD         },
139     {  6, DIFF_EXTREME      },
140     {  6, DIFF_UNREASONABLE },
141 };
142
143 static int game_fetch_preset(int i, char **name, game_params **params)
144 {
145     game_params *ret;
146     char buf[80];
147
148     if (i < 0 || i >= lenof(towers_presets))
149         return FALSE;
150
151     ret = snew(game_params);
152     *ret = towers_presets[i]; /* structure copy */
153
154     sprintf(buf, "%dx%d %s", ret->w, ret->w, towers_diffnames[ret->diff]);
155
156     *name = dupstr(buf);
157     *params = ret;
158     return TRUE;
159 }
160
161 static void free_params(game_params *params)
162 {
163     sfree(params);
164 }
165
166 static game_params *dup_params(const game_params *params)
167 {
168     game_params *ret = snew(game_params);
169     *ret = *params;                    /* structure copy */
170     return ret;
171 }
172
173 static void decode_params(game_params *params, char const *string)
174 {
175     char const *p = string;
176
177     params->w = atoi(p);
178     while (*p && isdigit((unsigned char)*p)) p++;
179
180     if (*p == 'd') {
181         int i;
182         p++;
183         params->diff = DIFFCOUNT+1; /* ...which is invalid */
184         if (*p) {
185             for (i = 0; i < DIFFCOUNT; i++) {
186                 if (*p == towers_diffchars[i])
187                     params->diff = i;
188             }
189             p++;
190         }
191     }
192 }
193
194 static char *encode_params(const game_params *params, int full)
195 {
196     char ret[80];
197
198     sprintf(ret, "%d", params->w);
199     if (full)
200         sprintf(ret + strlen(ret), "d%c", towers_diffchars[params->diff]);
201
202     return dupstr(ret);
203 }
204
205 static config_item *game_configure(const game_params *params)
206 {
207     config_item *ret;
208     char buf[80];
209
210     ret = snewn(3, config_item);
211
212     ret[0].name = "Grid size";
213     ret[0].type = C_STRING;
214     sprintf(buf, "%d", params->w);
215     ret[0].u.string.sval = dupstr(buf);
216
217     ret[1].name = "Difficulty";
218     ret[1].type = C_CHOICES;
219     ret[1].u.choices.choicenames = DIFFCONFIG;
220     ret[1].u.choices.selected = params->diff;
221
222     ret[2].name = NULL;
223     ret[2].type = C_END;
224
225     return ret;
226 }
227
228 static game_params *custom_params(const config_item *cfg)
229 {
230     game_params *ret = snew(game_params);
231
232     ret->w = atoi(cfg[0].u.string.sval);
233     ret->diff = cfg[1].u.choices.selected;
234
235     return ret;
236 }
237
238 static const char *validate_params(const game_params *params, int full)
239 {
240     if (params->w < 3 || params->w > 9)
241         return "Grid size must be between 3 and 9";
242     if (params->diff >= DIFFCOUNT)
243         return "Unknown difficulty rating";
244     return NULL;
245 }
246
247 /* ----------------------------------------------------------------------
248  * Solver.
249  */
250
251 struct solver_ctx {
252     int w, diff;
253     int started;
254     int *clues;
255     long *iscratch;
256     int *dscratch;
257 };
258
259 static int solver_easy(struct latin_solver *solver, void *vctx)
260 {
261     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
262     int w = ctx->w;
263     int c, i, j, n, m, furthest;
264     int start, step, cstart, cstep, clue, pos, cpos;
265     int ret = 0;
266 #ifdef STANDALONE_SOLVER
267     char prefix[256];
268 #endif
269
270     if (!ctx->started) {
271         ctx->started = TRUE;
272         /*
273          * One-off loop to help get started: when a pair of facing
274          * clues sum to w+1, it must mean that the row consists of
275          * two increasing sequences back to back, so we can
276          * immediately place the highest digit by knowing the
277          * lengths of those two sequences.
278          */
279         for (c = 0; c < 3*w; c = (c == w-1 ? 2*w : c+1)) {
280             int c2 = c + w;
281
282             if (ctx->clues[c] && ctx->clues[c2] &&
283                 ctx->clues[c] + ctx->clues[c2] == w+1) {
284                 STARTSTEP(start, step, c, w);
285                 CSTARTSTEP(cstart, cstep, c, w);
286                 pos = start + (ctx->clues[c]-1)*step;
287                 cpos = cstart + (ctx->clues[c]-1)*cstep;
288                 if (solver->cube[cpos*w+w-1]) {
289 #ifdef STANDALONE_SOLVER
290                     if (solver_show_working) {
291                         printf("%*sfacing clues on %s %d are maximal:\n",
292                                solver_recurse_depth*4, "",
293                                c>=2*w ? "row" : "column", c % w + 1);
294                         printf("%*s  placing %d at (%d,%d)\n",
295                                solver_recurse_depth*4, "",
296                                w, pos%w+1, pos/w+1);
297                     }
298 #endif
299                     latin_solver_place(solver, pos%w, pos/w, w);
300                     ret = 1;
301                 } else {
302                     ret = -1;
303                 }
304             }
305         }
306
307         if (ret)
308             return ret;
309     }
310
311     /*
312      * Go over every clue doing reasonably simple heuristic
313      * deductions.
314      */
315     for (c = 0; c < 4*w; c++) {
316         clue = ctx->clues[c];
317         if (!clue)
318             continue;
319         STARTSTEP(start, step, c, w);
320         CSTARTSTEP(cstart, cstep, c, w);
321
322         /* Find the location of each number in the row. */
323         for (i = 0; i < w; i++)
324             ctx->dscratch[i] = w;
325         for (i = 0; i < w; i++)
326             if (solver->grid[start+i*step])
327                 ctx->dscratch[solver->grid[start+i*step]-1] = i;
328
329         n = m = 0;
330         furthest = w;
331         for (i = w; i >= 1; i--) {
332             if (ctx->dscratch[i-1] == w) {
333                 break;
334             } else if (ctx->dscratch[i-1] < furthest) {
335                 furthest = ctx->dscratch[i-1];
336                 m = i;
337                 n++;
338             }
339         }
340         if (clue == n+1 && furthest > 1) {
341 #ifdef STANDALONE_SOLVER
342             if (solver_show_working)
343                 sprintf(prefix, "%*sclue %s %d is nearly filled:\n",
344                         solver_recurse_depth*4, "",
345                         cluepos[c/w], c%w+1);
346             else
347                 prefix[0] = '\0';              /* placate optimiser */
348 #endif
349             /*
350              * We can already see an increasing sequence of the very
351              * highest numbers, of length one less than that
352              * specified in the clue. All of those numbers _must_ be
353              * part of the clue sequence, so the number right next
354              * to the clue must be the final one - i.e. it must be
355              * bigger than any of the numbers between it and m. This
356              * allows us to rule out small numbers in that square.
357              *
358              * (This is a generalisation of the obvious deduction
359              * that when you see a clue saying 1, it must be right
360              * next to the largest possible number; and similarly,
361              * when you see a clue saying 2 opposite that, it must
362              * be right next to the second-largest.)
363              */
364             j = furthest-1;  /* number of small numbers we can rule out */
365             for (i = 1; i <= w && j > 0; i++) {
366                 if (ctx->dscratch[i-1] < w && ctx->dscratch[i-1] >= furthest)
367                     continue;          /* skip this number, it's elsewhere */
368                 j--;
369                 if (solver->cube[cstart*w+i-1]) {
370 #ifdef STANDALONE_SOLVER
371                     if (solver_show_working) {
372                         printf("%s%*s  ruling out %d at (%d,%d)\n",
373                                prefix, solver_recurse_depth*4, "",
374                                i, start%w+1, start/w+1);
375                         prefix[0] = '\0';
376                     }
377 #endif
378                     solver->cube[cstart*w+i-1] = 0;
379                     ret = 1;
380                 }
381             }
382         }
383
384         if (ret)
385             return ret;
386
387 #ifdef STANDALONE_SOLVER
388         if (solver_show_working)
389             sprintf(prefix, "%*slower bounds for clue %s %d:\n",
390                     solver_recurse_depth*4, "",
391                     cluepos[c/w], c%w+1);
392         else
393             prefix[0] = '\0';          /* placate optimiser */
394 #endif
395
396         i = 0;
397         for (n = w; n > 0; n--) {
398             /*
399              * The largest number cannot occur in the first (clue-1)
400              * squares of the row, or else there wouldn't be space
401              * for a sufficiently long increasing sequence which it
402              * terminated. The second-largest number (not counting
403              * any that are known to be on the far side of a larger
404              * number and hence excluded from this sequence) cannot
405              * occur in the first (clue-2) squares, similarly, and
406              * so on.
407              */
408
409             if (ctx->dscratch[n-1] < w) {
410                 for (m = n+1; m < w; m++)
411                     if (ctx->dscratch[m] < ctx->dscratch[n-1])
412                         break;
413                 if (m < w)
414                     continue;          /* this number doesn't count */
415             }
416
417             for (j = 0; j < clue - i - 1; j++)
418                 if (solver->cube[(cstart + j*cstep)*w+n-1]) {
419 #ifdef STANDALONE_SOLVER
420                     if (solver_show_working) {
421                         int pos = start+j*step;
422                         printf("%s%*s  ruling out %d at (%d,%d)\n",
423                                prefix, solver_recurse_depth*4, "",
424                                n, pos%w+1, pos/w+1);
425                         prefix[0] = '\0';
426                     }
427 #endif
428                     solver->cube[(cstart + j*cstep)*w+n-1] = 0;
429                     ret = 1;
430                 }
431             i++;
432         }
433     }
434
435     if (ret)
436         return ret;
437
438     return 0;
439 }
440
441 static int solver_hard(struct latin_solver *solver, void *vctx)
442 {
443     struct solver_ctx *ctx = (struct solver_ctx *)vctx;
444     int w = ctx->w;
445     int c, i, j, n, best, clue, start, step, ret;
446     long bitmap;
447 #ifdef STANDALONE_SOLVER
448     char prefix[256];
449 #endif
450
451     /*
452      * Go over every clue analysing all possibilities.
453      */
454     for (c = 0; c < 4*w; c++) {
455         clue = ctx->clues[c];
456         if (!clue)
457             continue;
458         CSTARTSTEP(start, step, c, w);
459
460         for (i = 0; i < w; i++)
461             ctx->iscratch[i] = 0;
462
463         /*
464          * Instead of a tedious physical recursion, I iterate in the
465          * scratch array through all possibilities. At any given
466          * moment, i indexes the element of the box that will next
467          * be incremented.
468          */
469         i = 0;
470         ctx->dscratch[i] = 0;
471         best = n = 0;
472         bitmap = 0;
473
474         while (1) {
475             if (i < w) {
476                 /*
477                  * Find the next valid value for cell i.
478                  */
479                 int limit = (n == clue ? best : w);
480                 int pos = start + step * i;
481                 for (j = ctx->dscratch[i] + 1; j <= limit; j++) {
482                     if (bitmap & (1L << j))
483                         continue;      /* used this one already */
484                     if (!solver->cube[pos*w+j-1])
485                         continue;      /* ruled out already */
486
487                     /* Found one. */
488                     break;
489                 }
490
491                 if (j > limit) {
492                     /* No valid values left; drop back. */
493                     i--;
494                     if (i < 0)
495                         break;         /* overall iteration is finished */
496                     bitmap &= ~(1L << ctx->dscratch[i]);
497                     if (ctx->dscratch[i] == best) {
498                         n--;
499                         best = 0;
500                         for (j = 0; j < i; j++)
501                             if (best < ctx->dscratch[j])
502                                 best = ctx->dscratch[j];
503                     }
504                 } else {
505                     /* Got a valid value; store it and move on. */
506                     bitmap |= 1L << j;
507                     ctx->dscratch[i++] = j;
508                     if (j > best) {
509                         best = j;
510                         n++;
511                     }
512                     ctx->dscratch[i] = 0;
513                 }
514             } else {
515                 if (n == clue) {
516                     for (j = 0; j < w; j++)
517                         ctx->iscratch[j] |= 1L << ctx->dscratch[j];
518                 }
519                 i--;
520                 bitmap &= ~(1L << ctx->dscratch[i]);
521                 if (ctx->dscratch[i] == best) {
522                     n--;
523                     best = 0;
524                     for (j = 0; j < i; j++)
525                         if (best < ctx->dscratch[j])
526                             best = ctx->dscratch[j];
527                 }
528             }
529         }
530
531 #ifdef STANDALONE_SOLVER
532         if (solver_show_working)
533             sprintf(prefix, "%*sexhaustive analysis of clue %s %d:\n",
534                     solver_recurse_depth*4, "",
535                     cluepos[c/w], c%w+1);
536         else
537             prefix[0] = '\0';          /* placate optimiser */
538 #endif
539
540         ret = 0;
541
542         for (i = 0; i < w; i++) {
543             int pos = start + step * i;
544             for (j = 1; j <= w; j++) {
545                 if (solver->cube[pos*w+j-1] &&
546                     !(ctx->iscratch[i] & (1L << j))) {
547 #ifdef STANDALONE_SOLVER
548                     if (solver_show_working) {
549                         printf("%s%*s  ruling out %d at (%d,%d)\n",
550                                prefix, solver_recurse_depth*4, "",
551                                j, pos/w+1, pos%w+1);
552                         prefix[0] = '\0';
553                     }
554 #endif
555                     solver->cube[pos*w+j-1] = 0;
556                     ret = 1;
557                 }
558             }
559
560             /*
561              * Once we find one clue we can do something with in
562              * this way, revert to trying easier deductions, so as
563              * not to generate solver diagnostics that make the
564              * problem look harder than it is.
565              */
566             if (ret)
567                 return ret;
568         }
569     }
570
571     return 0;
572 }
573
574 #define SOLVER(upper,title,func,lower) func,
575 static usersolver_t const towers_solvers[] = { DIFFLIST(SOLVER) };
576
577 static int solver(int w, int *clues, digit *soln, int maxdiff)
578 {
579     int ret;
580     struct solver_ctx ctx;
581
582     ctx.w = w;
583     ctx.diff = maxdiff;
584     ctx.clues = clues;
585     ctx.started = FALSE;
586     ctx.iscratch = snewn(w, long);
587     ctx.dscratch = snewn(w+1, int);
588
589     ret = latin_solver(soln, w, maxdiff,
590                        DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
591                        DIFF_EXTREME, DIFF_UNREASONABLE,
592                        towers_solvers, &ctx, NULL, NULL);
593
594     sfree(ctx.iscratch);
595     sfree(ctx.dscratch);
596
597     return ret;
598 }
599
600 /* ----------------------------------------------------------------------
601  * Grid generation.
602  */
603
604 static char *new_game_desc(const game_params *params, random_state *rs,
605                            char **aux, int interactive)
606 {
607     int w = params->w, a = w*w;
608     digit *grid, *soln, *soln2;
609     int *clues, *order;
610     int i, ret;
611     int diff = params->diff;
612     char *desc, *p;
613
614     /*
615      * Difficulty exceptions: some combinations of size and
616      * difficulty cannot be satisfied, because all puzzles of at
617      * most that difficulty are actually even easier.
618      *
619      * Remember to re-test this whenever a change is made to the
620      * solver logic!
621      *
622      * I tested it using the following shell command:
623
624 for d in e h x u; do
625   for i in {3..9}; do
626     echo -n "./towers --generate 1 ${i}d${d}: "
627     perl -e 'alarm 30; exec @ARGV' ./towers --generate 1 ${i}d${d} >/dev/null \
628       && echo ok
629   done
630 done
631
632      * Of course, it's better to do that after taking the exceptions
633      * _out_, so as to detect exceptions that should be removed as
634      * well as those which should be added.
635      */
636     if (diff > DIFF_HARD && w <= 3)
637         diff = DIFF_HARD;
638
639     grid = NULL;
640     clues = snewn(4*w, int);
641     soln = snewn(a, digit);
642     soln2 = snewn(a, digit);
643     order = snewn(max(4*w,a), int);
644
645     while (1) {
646         /*
647          * Construct a latin square to be the solution.
648          */
649         sfree(grid);
650         grid = latin_generate(w, rs);
651
652         /*
653          * Fill in the clues.
654          */
655         for (i = 0; i < 4*w; i++) {
656             int start, step, j, k, best;
657             STARTSTEP(start, step, i, w);
658             k = best = 0;
659             for (j = 0; j < w; j++) {
660                 if (grid[start+j*step] > best) {
661                     best = grid[start+j*step];
662                     k++;
663                 }
664             }
665             clues[i] = k;
666         }
667
668         /*
669          * Remove the grid numbers and then the clues, one by one,
670          * for as long as the game remains soluble at the given
671          * difficulty.
672          */
673         memcpy(soln, grid, a);
674
675         if (diff == DIFF_EASY && w <= 5) {
676             /*
677              * Special case: for Easy-mode grids that are small
678              * enough, it's nice to be able to find completely empty
679              * grids.
680              */
681             memset(soln2, 0, a);
682             ret = solver(w, clues, soln2, diff);
683             if (ret > diff)
684                 continue;
685         }
686
687         for (i = 0; i < a; i++)
688             order[i] = i;
689         shuffle(order, a, sizeof(*order), rs);
690         for (i = 0; i < a; i++) {
691             int j = order[i];
692
693             memcpy(soln2, grid, a);
694             soln2[j] = 0;
695             ret = solver(w, clues, soln2, diff);
696             if (ret <= diff)
697                 grid[j] = 0;
698         }
699
700         if (diff > DIFF_EASY) {        /* leave all clues on Easy mode */
701             for (i = 0; i < 4*w; i++)
702                 order[i] = i;
703             shuffle(order, 4*w, sizeof(*order), rs);
704             for (i = 0; i < 4*w; i++) {
705                 int j = order[i];
706                 int clue = clues[j];
707
708                 memcpy(soln2, grid, a);
709                 clues[j] = 0;
710                 ret = solver(w, clues, soln2, diff);
711                 if (ret > diff)
712                     clues[j] = clue;
713             }
714         }
715
716         /*
717          * See if the game can be solved at the specified difficulty
718          * level, but not at the one below.
719          */
720         memcpy(soln2, grid, a);
721         ret = solver(w, clues, soln2, diff);
722         if (ret != diff)
723             continue;                  /* go round again */
724
725         /*
726          * We've got a usable puzzle!
727          */
728         break;
729     }
730
731     /*
732      * Encode the puzzle description.
733      */
734     desc = snewn(40*a, char);
735     p = desc;
736     for (i = 0; i < 4*w; i++) {
737         if (i)
738             *p++ = '/';
739         if (clues[i])
740             p += sprintf(p, "%d", clues[i]);
741     }
742     for (i = 0; i < a; i++)
743         if (grid[i])
744             break;
745     if (i < a) {
746         int run = 0;
747
748         *p++ = ',';
749
750         for (i = 0; i <= a; i++) {
751             int n = (i < a ? grid[i] : -1);
752
753             if (!n)
754                 run++;
755             else {
756                 if (run) {
757                     while (run > 0) {
758                         int thisrun = min(run, 26);
759                         *p++ = thisrun - 1 + 'a';
760                         run -= thisrun;
761                     }
762                 } else {
763                     /*
764                      * If there's a number in the very top left or
765                      * bottom right, there's no point putting an
766                      * unnecessary _ before or after it.
767                      */
768                     if (i > 0 && n > 0)
769                         *p++ = '_';
770                 }
771                 if (n > 0)
772                     p += sprintf(p, "%d", n);
773                 run = 0;
774             }
775         }
776     }
777     *p++ = '\0';
778     desc = sresize(desc, p - desc, char);
779
780     /*
781      * Encode the solution.
782      */
783     *aux = snewn(a+2, char);
784     (*aux)[0] = 'S';
785     for (i = 0; i < a; i++)
786         (*aux)[i+1] = '0' + soln[i];
787     (*aux)[a+1] = '\0';
788
789     sfree(grid);
790     sfree(clues);
791     sfree(soln);
792     sfree(soln2);
793     sfree(order);
794
795     return desc;
796 }
797
798 /* ----------------------------------------------------------------------
799  * Gameplay.
800  */
801
802 static const char *validate_desc(const game_params *params, const char *desc)
803 {
804     int w = params->w, a = w*w;
805     const char *p = desc;
806     int i, clue;
807
808     /*
809      * Verify that the right number of clues are given, and that
810      * they're in range.
811      */
812     for (i = 0; i < 4*w; i++) {
813         if (!*p)
814             return "Too few clues for grid size";
815
816         if (i > 0) {
817             if (*p != '/')
818                 return "Expected commas between clues";
819             p++;
820         }
821
822         if (isdigit((unsigned char)*p)) {
823             clue = atoi(p);
824             while (*p && isdigit((unsigned char)*p)) p++;
825
826             if (clue <= 0 || clue > w)
827                 return "Clue number out of range";
828         }
829     }
830     if (*p == '/')
831         return "Too many clues for grid size";
832
833     if (*p == ',') {
834         /*
835          * Verify that the right amount of grid data is given, and
836          * that any grid elements provided are in range.
837          */
838         int squares = 0;
839
840         p++;
841         while (*p) {
842             int c = *p++;
843             if (c >= 'a' && c <= 'z') {
844                 squares += c - 'a' + 1;
845             } else if (c == '_') {
846                 /* do nothing */;
847             } else if (c > '0' && c <= '9') {
848                 int val = atoi(p-1);
849                 if (val < 1 || val > w)
850                     return "Out-of-range number in grid description";
851                 squares++;
852                 while (*p && isdigit((unsigned char)*p)) p++;
853             } else
854                 return "Invalid character in game description";
855         }
856
857         if (squares < a)
858             return "Not enough data to fill grid";
859
860         if (squares > a)
861             return "Too much data to fit in grid";
862     }
863
864     return NULL;
865 }
866
867 static game_state *new_game(midend *me, const game_params *params,
868                             const char *desc)
869 {
870     int w = params->w, a = w*w;
871     game_state *state = snew(game_state);
872     const char *p = desc;
873     int i;
874
875     state->par = *params;              /* structure copy */
876     state->clues = snew(struct clues);
877     state->clues->refcount = 1;
878     state->clues->w = w;
879     state->clues->clues = snewn(4*w, int);
880     state->clues->immutable = snewn(a, digit);
881     state->grid = snewn(a, digit);
882     state->clues_done = snewn(4*w, unsigned char);
883     state->pencil = snewn(a, int);
884
885     for (i = 0; i < a; i++) {
886         state->grid[i] = 0;
887         state->pencil[i] = 0;
888     }
889
890     memset(state->clues->immutable, 0, a);
891     memset(state->clues_done, 0, 4*w*sizeof(unsigned char));
892
893     for (i = 0; i < 4*w; i++) {
894         if (i > 0) {
895             assert(*p == '/');
896             p++;
897         }
898         if (*p && isdigit((unsigned char)*p)) {
899             state->clues->clues[i] = atoi(p);
900             while (*p && isdigit((unsigned char)*p)) p++;
901         } else
902             state->clues->clues[i] = 0;
903     }
904
905     if (*p == ',') {
906         int pos = 0;
907         p++;
908         while (*p) {
909             int c = *p++;
910             if (c >= 'a' && c <= 'z') {
911                 pos += c - 'a' + 1;
912             } else if (c == '_') {
913                 /* do nothing */;
914             } else if (c > '0' && c <= '9') {
915                 int val = atoi(p-1);
916                 assert(val >= 1 && val <= w);
917                 assert(pos < a);
918                 state->grid[pos] = state->clues->immutable[pos] = val;
919                 pos++;
920                 while (*p && isdigit((unsigned char)*p)) p++;
921             } else
922                 assert(!"Corrupt game description");
923         }
924         assert(pos == a);
925     }
926     assert(!*p);
927
928     state->completed = state->cheated = FALSE;
929
930     return state;
931 }
932
933 static game_state *dup_game(const game_state *state)
934 {
935     int w = state->par.w, a = w*w;
936     game_state *ret = snew(game_state);
937
938     ret->par = state->par;             /* structure copy */
939
940     ret->clues = state->clues;
941     ret->clues->refcount++;
942
943     ret->grid = snewn(a, digit);
944     ret->pencil = snewn(a, int);
945     ret->clues_done = snewn(4*w, unsigned char);
946     memcpy(ret->grid, state->grid, a*sizeof(digit));
947     memcpy(ret->pencil, state->pencil, a*sizeof(int));
948     memcpy(ret->clues_done, state->clues_done, 4*w*sizeof(unsigned char));
949
950     ret->completed = state->completed;
951     ret->cheated = state->cheated;
952
953     return ret;
954 }
955
956 static void free_game(game_state *state)
957 {
958     sfree(state->grid);
959     sfree(state->pencil);
960     sfree(state->clues_done);
961     if (--state->clues->refcount <= 0) {
962         sfree(state->clues->immutable);
963         sfree(state->clues->clues);
964         sfree(state->clues);
965     }
966     sfree(state);
967 }
968
969 static char *solve_game(const game_state *state, const game_state *currstate,
970                         const char *aux, const char **error)
971 {
972     int w = state->par.w, a = w*w;
973     int i, ret;
974     digit *soln;
975     char *out;
976
977     if (aux)
978         return dupstr(aux);
979
980     soln = snewn(a, digit);
981     memcpy(soln, state->clues->immutable, a);
982
983     ret = solver(w, state->clues->clues, soln, DIFFCOUNT-1);
984
985     if (ret == diff_impossible) {
986         *error = "No solution exists for this puzzle";
987         out = NULL;
988     } else if (ret == diff_ambiguous) {
989         *error = "Multiple solutions exist for this puzzle";
990         out = NULL;
991     } else {
992         out = snewn(a+2, char);
993         out[0] = 'S';
994         for (i = 0; i < a; i++)
995             out[i+1] = '0' + soln[i];
996         out[a+1] = '\0';
997     }
998
999     sfree(soln);
1000     return out;
1001 }
1002
1003 static int game_can_format_as_text_now(const game_params *params)
1004 {
1005     return TRUE;
1006 }
1007
1008 static char *game_text_format(const game_state *state)
1009 {
1010     int w = state->par.w /* , a = w*w */;
1011     char *ret;
1012     char *p;
1013     int x, y;
1014     int total;
1015
1016     /*
1017      * We have:
1018      *  - a top clue row, consisting of three spaces, then w clue
1019      *    digits with spaces between (total 2*w+3 chars including
1020      *    newline)
1021      *  - a blank line (one newline)
1022      *  - w main rows, consisting of a left clue digit, two spaces,
1023      *    w grid digits with spaces between, two spaces and a right
1024      *    clue digit (total 2*w+6 chars each including newline)
1025      *  - a blank line (one newline)
1026      *  - a bottom clue row (same as top clue row)
1027      *  - terminating NUL.
1028      *
1029      * Total size is therefore 2*(2*w+3) + 2 + w*(2*w+6) + 1
1030      * = 2w^2+10w+9.
1031      */
1032     total = 2*w*w + 10*w + 9;
1033     ret = snewn(total, char);
1034     p = ret;
1035
1036     /* Top clue row. */
1037     *p++ = ' '; *p++ = ' ';
1038     for (x = 0; x < w; x++) {
1039         *p++ = ' ';
1040         *p++ = (state->clues->clues[x] ? '0' + state->clues->clues[x] : ' ');
1041     }
1042     *p++ = '\n';
1043
1044     /* Blank line. */
1045     *p++ = '\n';
1046
1047     /* Main grid. */
1048     for (y = 0; y < w; y++) {
1049         *p++ = (state->clues->clues[y+2*w] ? '0' + state->clues->clues[y+2*w] :
1050                 ' ');
1051         *p++ = ' ';
1052         for (x = 0; x < w; x++) {
1053             *p++ = ' ';
1054             *p++ = (state->grid[y*w+x] ? '0' + state->grid[y*w+x] : ' ');
1055         }
1056         *p++ = ' '; *p++ = ' ';
1057         *p++ = (state->clues->clues[y+3*w] ? '0' + state->clues->clues[y+3*w] :
1058                 ' ');
1059         *p++ = '\n';
1060     }
1061
1062     /* Blank line. */
1063     *p++ = '\n';
1064
1065     /* Bottom clue row. */
1066     *p++ = ' '; *p++ = ' ';
1067     for (x = 0; x < w; x++) {
1068         *p++ = ' ';
1069         *p++ = (state->clues->clues[x+w] ? '0' + state->clues->clues[x+w] :
1070                 ' ');
1071     }
1072     *p++ = '\n';
1073
1074     *p++ = '\0';
1075     assert(p == ret + total);
1076
1077     return ret;
1078 }
1079
1080 struct game_ui {
1081     /*
1082      * These are the coordinates of the currently highlighted
1083      * square on the grid, if hshow = 1.
1084      */
1085     int hx, hy;
1086     /*
1087      * This indicates whether the current highlight is a
1088      * pencil-mark one or a real one.
1089      */
1090     int hpencil;
1091     /*
1092      * This indicates whether or not we're showing the highlight
1093      * (used to be hx = hy = -1); important so that when we're
1094      * using the cursor keys it doesn't keep coming back at a
1095      * fixed position. When hshow = 1, pressing a valid number
1096      * or letter key or Space will enter that number or letter in the grid.
1097      */
1098     int hshow;
1099     /*
1100      * This indicates whether we're using the highlight as a cursor;
1101      * it means that it doesn't vanish on a keypress, and that it is
1102      * allowed on immutable squares.
1103      */
1104     int hcursor;
1105 };
1106
1107 static game_ui *new_ui(const game_state *state)
1108 {
1109     game_ui *ui = snew(game_ui);
1110
1111     ui->hx = ui->hy = 0;
1112     ui->hpencil = ui->hshow = ui->hcursor = 0;
1113
1114     return ui;
1115 }
1116
1117 static void free_ui(game_ui *ui)
1118 {
1119     sfree(ui);
1120 }
1121
1122 static char *encode_ui(const game_ui *ui)
1123 {
1124     return NULL;
1125 }
1126
1127 static void decode_ui(game_ui *ui, const char *encoding)
1128 {
1129 }
1130
1131 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1132                                const game_state *newstate)
1133 {
1134     int w = newstate->par.w;
1135     /*
1136      * We prevent pencil-mode highlighting of a filled square, unless
1137      * we're using the cursor keys. So if the user has just filled in
1138      * a square which we had a pencil-mode highlight in (by Undo, or
1139      * by Redo, or by Solve), then we cancel the highlight.
1140      */
1141     if (ui->hshow && ui->hpencil && !ui->hcursor &&
1142         newstate->grid[ui->hy * w + ui->hx] != 0) {
1143         ui->hshow = 0;
1144     }
1145 }
1146
1147 #define PREFERRED_TILESIZE 48
1148 #define TILESIZE (ds->tilesize)
1149 #define BORDER (TILESIZE * 9 / 8)
1150 #define COORD(x) ((x)*TILESIZE + BORDER)
1151 #define FROMCOORD(x) (((x)+(TILESIZE-BORDER)) / TILESIZE - 1)
1152
1153 /* These always return positive values, though y offsets are actually -ve */
1154 #define X_3D_DISP(height, w) ((height) * TILESIZE / (8 * (w)))
1155 #define Y_3D_DISP(height, w) ((height) * TILESIZE / (4 * (w)))
1156
1157 #define FLASH_TIME 0.4F
1158
1159 #define DF_PENCIL_SHIFT 16
1160 #define DF_CLUE_DONE 0x10000
1161 #define DF_ERROR 0x8000
1162 #define DF_HIGHLIGHT 0x4000
1163 #define DF_HIGHLIGHT_PENCIL 0x2000
1164 #define DF_IMMUTABLE 0x1000
1165 #define DF_PLAYAREA 0x0800
1166 #define DF_DIGIT_MASK 0x00FF
1167
1168 struct game_drawstate {
1169     int tilesize;
1170     int three_d;                /* default 3D graphics are user-disableable */
1171     int started;
1172     long *tiles;                       /* (w+2)*(w+2) temp space */
1173     long *drawn;                       /* (w+2)*(w+2)*4: current drawn data */
1174     int *errtmp;
1175 };
1176
1177 static int check_errors(const game_state *state, int *errors)
1178 {
1179     int w = state->par.w /*, a = w*w */;
1180     int W = w+2, A = W*W;              /* the errors array is (w+2) square */
1181     int *clues = state->clues->clues;
1182     digit *grid = state->grid;
1183     int i, x, y, errs = FALSE;
1184     int tmp[32];
1185
1186     assert(w < lenof(tmp));
1187
1188     if (errors)
1189         for (i = 0; i < A; i++)
1190             errors[i] = 0;
1191
1192     for (y = 0; y < w; y++) {
1193         unsigned long mask = 0, errmask = 0;
1194         for (x = 0; x < w; x++) {
1195             unsigned long bit = 1UL << grid[y*w+x];
1196             errmask |= (mask & bit);
1197             mask |= bit;
1198         }
1199
1200         if (mask != (1L << (w+1)) - (1L << 1)) {
1201             errs = TRUE;
1202             errmask &= ~1UL;
1203             if (errors) {
1204                 for (x = 0; x < w; x++)
1205                     if (errmask & (1UL << grid[y*w+x]))
1206                         errors[(y+1)*W+(x+1)] = TRUE;
1207             }
1208         }
1209     }
1210
1211     for (x = 0; x < w; x++) {
1212         unsigned long mask = 0, errmask = 0;
1213         for (y = 0; y < w; y++) {
1214             unsigned long bit = 1UL << grid[y*w+x];
1215             errmask |= (mask & bit);
1216             mask |= bit;
1217         }
1218
1219         if (mask != (1 << (w+1)) - (1 << 1)) {
1220             errs = TRUE;
1221             errmask &= ~1UL;
1222             if (errors) {
1223                 for (y = 0; y < w; y++)
1224                     if (errmask & (1UL << grid[y*w+x]))
1225                         errors[(y+1)*W+(x+1)] = TRUE;
1226             }
1227         }
1228     }
1229
1230     for (i = 0; i < 4*w; i++) {
1231         int start, step, j, n, best;
1232         STARTSTEP(start, step, i, w);
1233
1234         if (!clues[i])
1235             continue;
1236
1237         best = n = 0;
1238         for (j = 0; j < w; j++) {
1239             int number = grid[start+j*step];
1240             if (!number)
1241                 break;                 /* can't tell what happens next */
1242             if (number > best) {
1243                 best = number;
1244                 n++;
1245             }
1246         }
1247
1248         if (n > clues[i] || (best == w && n < clues[i]) ||
1249             (best < w && n == clues[i])) {
1250             if (errors) {
1251                 int x, y;
1252                 CLUEPOS(x, y, i, w);
1253                 errors[(y+1)*W+(x+1)] = TRUE;
1254             }
1255             errs = TRUE;
1256         }
1257     }
1258
1259     return errs;
1260 }
1261
1262 static int clue_index(const game_state *state, int x, int y)
1263 {
1264     int w = state->par.w;
1265
1266     if (x == -1 || x == w)
1267         return w * (x == -1 ? 2 : 3) + y;
1268     else if (y == -1 || y == w)
1269         return (y == -1 ? 0 : w) + x;
1270
1271     return -1;
1272 }
1273
1274 static int is_clue(const game_state *state, int x, int y)
1275 {
1276     int w = state->par.w;
1277
1278     if (((x == -1 || x == w) && y >= 0 && y < w) ||
1279         ((y == -1 || y == w) && x >= 0 && x < w))
1280     {
1281         if (state->clues->clues[clue_index(state, x, y)] & DF_DIGIT_MASK)
1282             return TRUE;
1283     }
1284
1285     return FALSE;
1286 }
1287
1288 static char *interpret_move(const game_state *state, game_ui *ui,
1289                             const game_drawstate *ds,
1290                             int x, int y, int button)
1291 {
1292     int w = state->par.w;
1293     int shift_or_control = button & (MOD_SHFT | MOD_CTRL);
1294     int tx, ty;
1295     char buf[80];
1296
1297     button &= ~MOD_MASK;
1298
1299     tx = FROMCOORD(x);
1300     ty = FROMCOORD(y);
1301
1302     if (ds->three_d) {
1303         /*
1304          * In 3D mode, just locating the mouse click in the natural
1305          * square grid may not be sufficient to tell which tower the
1306          * user clicked on. Investigate the _tops_ of the nearby
1307          * towers to see if a click on one grid square was actually
1308          * a click on a tower protruding into that region from
1309          * another.
1310          */
1311         int dx, dy;
1312         for (dy = 0; dy <= 1; dy++)
1313             for (dx = 0; dx >= -1; dx--) {
1314                 int cx = tx + dx, cy = ty + dy;
1315                 if (cx >= 0 && cx < w && cy >= 0 && cy < w) {
1316                     int height = state->grid[cy*w+cx];
1317                     int bx = COORD(cx), by = COORD(cy);
1318                     int ox = bx + X_3D_DISP(height, w);
1319                     int oy = by - Y_3D_DISP(height, w);
1320                     if (/* on top face? */
1321                         (x - ox >= 0 && x - ox < TILESIZE &&
1322                          y - oy >= 0 && y - oy < TILESIZE) ||
1323                         /* in triangle between top-left corners? */
1324                         (ox > bx && x >= bx && x <= ox && y <= by &&
1325                          (by-y) * (ox-bx) <= (by-oy) * (x-bx)) ||
1326                         /* in triangle between bottom-right corners? */
1327                         (ox > bx && x >= bx+TILESIZE && x <= ox+TILESIZE &&
1328                          y >= oy+TILESIZE &&
1329                          (by-y+TILESIZE)*(ox-bx) >= (by-oy)*(x-bx-TILESIZE))) {
1330                         tx = cx;
1331                         ty = cy;
1332                     }
1333                 }
1334             }
1335     }
1336
1337     if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
1338         if (button == LEFT_BUTTON) {
1339             if (tx == ui->hx && ty == ui->hy &&
1340                 ui->hshow && ui->hpencil == 0) {
1341                 ui->hshow = 0;
1342             } else {
1343                 ui->hx = tx;
1344                 ui->hy = ty;
1345                 ui->hshow = !state->clues->immutable[ty*w+tx];
1346                 ui->hpencil = 0;
1347             }
1348             ui->hcursor = 0;
1349             return UI_UPDATE;
1350         }
1351         if (button == RIGHT_BUTTON) {
1352             /*
1353              * Pencil-mode highlighting for non filled squares.
1354              */
1355             if (state->grid[ty*w+tx] == 0) {
1356                 if (tx == ui->hx && ty == ui->hy &&
1357                     ui->hshow && ui->hpencil) {
1358                     ui->hshow = 0;
1359                 } else {
1360                     ui->hpencil = 1;
1361                     ui->hx = tx;
1362                     ui->hy = ty;
1363                     ui->hshow = 1;
1364                 }
1365             } else {
1366                 ui->hshow = 0;
1367             }
1368             ui->hcursor = 0;
1369             return UI_UPDATE;
1370         }
1371     } else if (button == LEFT_BUTTON) {
1372         if (is_clue(state, tx, ty)) {
1373             sprintf(buf, "%c%d,%d", 'D', tx, ty);
1374             return dupstr(buf);
1375         }
1376     }
1377     if (IS_CURSOR_MOVE(button)) {
1378         if (shift_or_control) {
1379             int x = ui->hx, y = ui->hy;
1380             switch (button) {
1381             case CURSOR_LEFT:   x = -1; break;
1382             case CURSOR_RIGHT:  x =  w; break;
1383             case CURSOR_UP:     y = -1; break;
1384             case CURSOR_DOWN:   y =  w; break;
1385             }
1386             if (is_clue(state, x, y)) {
1387                 sprintf(buf, "%c%d,%d", 'D', x, y);
1388                 return dupstr(buf);
1389             }
1390             return NULL;
1391         }
1392         move_cursor(button, &ui->hx, &ui->hy, w, w, 0);
1393         ui->hshow = ui->hcursor = 1;
1394         return UI_UPDATE;
1395     }
1396     if (ui->hshow &&
1397         (button == CURSOR_SELECT)) {
1398         ui->hpencil = 1 - ui->hpencil;
1399         ui->hcursor = 1;
1400         return UI_UPDATE;
1401     }
1402
1403     if (ui->hshow &&
1404         ((button >= '0' && button <= '9' && button - '0' <= w) ||
1405          button == CURSOR_SELECT2 || button == '\b')) {
1406         int n = button - '0';
1407         if (button == CURSOR_SELECT2 || button == '\b')
1408             n = 0;
1409
1410         /*
1411          * Can't make pencil marks in a filled square. This can only
1412          * become highlighted if we're using cursor keys.
1413          */
1414         if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
1415             return NULL;
1416
1417         /*
1418          * Can't do anything to an immutable square.
1419          */
1420         if (state->clues->immutable[ui->hy*w+ui->hx])
1421             return NULL;
1422
1423         sprintf(buf, "%c%d,%d,%d",
1424                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
1425
1426         if (!ui->hcursor) ui->hshow = 0;
1427
1428         return dupstr(buf);
1429     }
1430
1431     if (button == 'M' || button == 'm')
1432         return dupstr("M");
1433
1434     return NULL;
1435 }
1436
1437 static game_state *execute_move(const game_state *from, const char *move)
1438 {
1439     int w = from->par.w, a = w*w;
1440     game_state *ret = dup_game(from);
1441     int x, y, i, n;
1442
1443     if (move[0] == 'S') {
1444         ret->completed = ret->cheated = TRUE;
1445
1446         for (i = 0; i < a; i++) {
1447             if (move[i+1] < '1' || move[i+1] > '0'+w)
1448                 goto badmove;
1449             ret->grid[i] = move[i+1] - '0';
1450             ret->pencil[i] = 0;
1451         }
1452
1453         if (move[a+1] != '\0')
1454             goto badmove;
1455
1456         return ret;
1457     } else if ((move[0] == 'P' || move[0] == 'R') &&
1458         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
1459         x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
1460         if (from->clues->immutable[y*w+x])
1461             goto badmove;
1462
1463         if (move[0] == 'P' && n > 0) {
1464             ret->pencil[y*w+x] ^= 1L << n;
1465         } else {
1466             ret->grid[y*w+x] = n;
1467             ret->pencil[y*w+x] = 0;
1468
1469             if (!ret->completed && !check_errors(ret, NULL))
1470                 ret->completed = TRUE;
1471         }
1472         return ret;
1473     } else if (move[0] == 'M') {
1474         /*
1475          * Fill in absolutely all pencil marks everywhere. (I
1476          * wouldn't use this for actual play, but it's a handy
1477          * starting point when following through a set of
1478          * diagnostics output by the standalone solver.)
1479          */
1480         for (i = 0; i < a; i++) {
1481             if (!ret->grid[i])
1482                 ret->pencil[i] = (1L << (w+1)) - (1L << 1);
1483         }
1484         return ret;
1485     } else if (move[0] == 'D' && sscanf(move+1, "%d,%d", &x, &y) == 2 &&
1486                is_clue(from, x, y)) {
1487         int index = clue_index(from, x, y);
1488         ret->clues_done[index] = !ret->clues_done[index];
1489         return ret;
1490     }
1491
1492   badmove:
1493     /* couldn't parse move string */
1494     free_game(ret);
1495     return NULL;
1496 }
1497
1498 /* ----------------------------------------------------------------------
1499  * Drawing routines.
1500  */
1501
1502 #define SIZE(w) ((w) * TILESIZE + 2*BORDER)
1503
1504 static void game_compute_size(const game_params *params, int tilesize,
1505                               int *x, int *y)
1506 {
1507     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1508     struct { int tilesize; } ads, *ds = &ads;
1509     ads.tilesize = tilesize;
1510
1511     *x = *y = SIZE(params->w);
1512 }
1513
1514 static void game_set_size(drawing *dr, game_drawstate *ds,
1515                           const game_params *params, int tilesize)
1516 {
1517     ds->tilesize = tilesize;
1518 }
1519
1520 static float *game_colours(frontend *fe, int *ncolours)
1521 {
1522     float *ret = snewn(3 * NCOLOURS, float);
1523
1524     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1525
1526     ret[COL_GRID * 3 + 0] = 0.0F;
1527     ret[COL_GRID * 3 + 1] = 0.0F;
1528     ret[COL_GRID * 3 + 2] = 0.0F;
1529
1530     ret[COL_USER * 3 + 0] = 0.0F;
1531     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1532     ret[COL_USER * 3 + 2] = 0.0F;
1533
1534     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
1535     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
1536     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
1537
1538     ret[COL_ERROR * 3 + 0] = 1.0F;
1539     ret[COL_ERROR * 3 + 1] = 0.0F;
1540     ret[COL_ERROR * 3 + 2] = 0.0F;
1541
1542     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1543     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1544     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
1545
1546     ret[COL_DONE * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] / 1.5F;
1547     ret[COL_DONE * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] / 1.5F;
1548     ret[COL_DONE * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] / 1.5F;
1549
1550     *ncolours = NCOLOURS;
1551     return ret;
1552 }
1553
1554 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1555 {
1556     int w = state->par.w /*, a = w*w */;
1557     struct game_drawstate *ds = snew(struct game_drawstate);
1558     int i;
1559
1560     ds->tilesize = 0;
1561     ds->three_d = !getenv("TOWERS_2D");
1562     ds->started = FALSE;
1563     ds->tiles = snewn((w+2)*(w+2), long);
1564     ds->drawn = snewn((w+2)*(w+2)*4, long);
1565     for (i = 0; i < (w+2)*(w+2)*4; i++)
1566         ds->drawn[i] = -1;
1567     ds->errtmp = snewn((w+2)*(w+2), int);
1568
1569     return ds;
1570 }
1571
1572 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1573 {
1574     sfree(ds->errtmp);
1575     sfree(ds->tiles);
1576     sfree(ds->drawn);
1577     sfree(ds);
1578 }
1579
1580 static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
1581                       int x, int y, long tile)
1582 {
1583     int w = clues->w /* , a = w*w */;
1584     int tx, ty, bg;
1585     char str[64];
1586
1587     tx = COORD(x);
1588     ty = COORD(y);
1589
1590     bg = (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND;
1591
1592     /* draw tower */
1593     if (ds->three_d && (tile & DF_PLAYAREA) && (tile & DF_DIGIT_MASK)) {
1594         int coords[8];
1595         int xoff = X_3D_DISP(tile & DF_DIGIT_MASK, w);
1596         int yoff = Y_3D_DISP(tile & DF_DIGIT_MASK, w);
1597
1598         /* left face of tower */
1599         coords[0] = tx;
1600         coords[1] = ty - 1;
1601         coords[2] = tx;
1602         coords[3] = ty + TILESIZE - 1;
1603         coords[4] = coords[2] + xoff;
1604         coords[5] = coords[3] - yoff;
1605         coords[6] = coords[0] + xoff;
1606         coords[7] = coords[1] - yoff;
1607         draw_polygon(dr, coords, 4, bg, COL_GRID);
1608
1609         /* bottom face of tower */
1610         coords[0] = tx + TILESIZE;
1611         coords[1] = ty + TILESIZE - 1;
1612         coords[2] = tx;
1613         coords[3] = ty + TILESIZE - 1;
1614         coords[4] = coords[2] + xoff;
1615         coords[5] = coords[3] - yoff;
1616         coords[6] = coords[0] + xoff;
1617         coords[7] = coords[1] - yoff;
1618         draw_polygon(dr, coords, 4, bg, COL_GRID);
1619
1620         /* now offset all subsequent drawing to the top of the tower */
1621         tx += xoff;
1622         ty -= yoff;
1623     }
1624
1625     /* erase background */
1626     draw_rect(dr, tx, ty, TILESIZE, TILESIZE, bg);
1627
1628     /* pencil-mode highlight */
1629     if (tile & DF_HIGHLIGHT_PENCIL) {
1630         int coords[6];
1631         coords[0] = tx;
1632         coords[1] = ty;
1633         coords[2] = tx+TILESIZE/2;
1634         coords[3] = ty;
1635         coords[4] = tx;
1636         coords[5] = ty+TILESIZE/2;
1637         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1638     }
1639
1640     /* draw box outline */
1641     if (tile & DF_PLAYAREA) {
1642         int coords[8];
1643         coords[0] = tx;
1644         coords[1] = ty - 1;
1645         coords[2] = tx + TILESIZE;
1646         coords[3] = ty - 1;
1647         coords[4] = tx + TILESIZE;
1648         coords[5] = ty + TILESIZE - 1;
1649         coords[6] = tx;
1650         coords[7] = ty + TILESIZE - 1;
1651         draw_polygon(dr, coords, 4, -1, COL_GRID);
1652     }
1653
1654     /* new number needs drawing? */
1655     if (tile & DF_DIGIT_MASK) {
1656         int color;
1657
1658         str[1] = '\0';
1659         str[0] = (tile & DF_DIGIT_MASK) + '0';
1660
1661         if (tile & DF_ERROR)
1662             color = COL_ERROR;
1663         else if (tile & DF_CLUE_DONE)
1664             color = COL_DONE;
1665         else if (x < 0 || y < 0 || x >= w || y >= w)
1666             color = COL_GRID;
1667         else if (tile & DF_IMMUTABLE)
1668             color = COL_GRID;
1669         else
1670             color = COL_USER;
1671
1672         draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2, FONT_VARIABLE,
1673                   (tile & DF_PLAYAREA ? TILESIZE/2 : TILESIZE*2/5),
1674                   ALIGN_VCENTRE | ALIGN_HCENTRE, color, str);
1675     } else {
1676         int i, j, npencil;
1677         int pl, pr, pt, pb;
1678         float bestsize;
1679         int pw, ph, minph, pbest, fontsize;
1680
1681         /* Count the pencil marks required. */
1682         for (i = 1, npencil = 0; i <= w; i++)
1683             if (tile & (1L << (i + DF_PENCIL_SHIFT)))
1684                 npencil++;
1685         if (npencil) {
1686
1687             minph = 2;
1688
1689             /*
1690              * Determine the bounding rectangle within which we're going
1691              * to put the pencil marks.
1692              */
1693             /* Start with the whole square, minus space for impinging towers */
1694             pl = tx + (ds->three_d ? X_3D_DISP(w,w) : 0);
1695             pr = tx + TILESIZE;
1696             pt = ty;
1697             pb = ty + TILESIZE - (ds->three_d ? Y_3D_DISP(w,w) : 0);
1698
1699             /*
1700              * We arrange our pencil marks in a grid layout, with
1701              * the number of rows and columns adjusted to allow the
1702              * maximum font size.
1703              *
1704              * So now we work out what the grid size ought to be.
1705              */
1706             bestsize = 0.0;
1707             pbest = 0;
1708             /* Minimum */
1709             for (pw = 3; pw < max(npencil,4); pw++) {
1710                 float fw, fh, fs;
1711
1712                 ph = (npencil + pw - 1) / pw;
1713                 ph = max(ph, minph);
1714                 fw = (pr - pl) / (float)pw;
1715                 fh = (pb - pt) / (float)ph;
1716                 fs = min(fw, fh);
1717                 if (fs > bestsize) {
1718                     bestsize = fs;
1719                     pbest = pw;
1720                 }
1721             }
1722             assert(pbest > 0);
1723             pw = pbest;
1724             ph = (npencil + pw - 1) / pw;
1725             ph = max(ph, minph);
1726
1727             /*
1728              * Now we've got our grid dimensions, work out the pixel
1729              * size of a grid element, and round it to the nearest
1730              * pixel. (We don't want rounding errors to make the
1731              * grid look uneven at low pixel sizes.)
1732              */
1733             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
1734
1735             /*
1736              * Centre the resulting figure in the square.
1737              */
1738             pl = pl + (pr - pl - fontsize * pw) / 2;
1739             pt = pt + (pb - pt - fontsize * ph) / 2;
1740
1741             /*
1742              * Now actually draw the pencil marks.
1743              */
1744             for (i = 1, j = 0; i <= w; i++)
1745                 if (tile & (1L << (i + DF_PENCIL_SHIFT))) {
1746                     int dx = j % pw, dy = j / pw;
1747
1748                     str[1] = '\0';
1749                     str[0] = i + '0';
1750                     draw_text(dr, pl + fontsize * (2*dx+1) / 2,
1751                               pt + fontsize * (2*dy+1) / 2,
1752                               FONT_VARIABLE, fontsize,
1753                               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
1754                     j++;
1755                 }
1756         }
1757     }
1758 }
1759
1760 static void game_redraw(drawing *dr, game_drawstate *ds,
1761                         const game_state *oldstate, const game_state *state,
1762                         int dir, const game_ui *ui,
1763                         float animtime, float flashtime)
1764 {
1765     int w = state->par.w /*, a = w*w */;
1766     int i, x, y;
1767
1768     if (!ds->started) {
1769         /*
1770          * The initial contents of the window are not guaranteed and
1771          * can vary with front ends. To be on the safe side, all
1772          * games should start by drawing a big background-colour
1773          * rectangle covering the whole window.
1774          */
1775         draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);
1776
1777         draw_update(dr, 0, 0, SIZE(w), SIZE(w));
1778
1779         ds->started = TRUE;
1780     }
1781
1782     check_errors(state, ds->errtmp);
1783
1784     /*
1785      * Work out what data each tile should contain.
1786      */
1787     for (i = 0; i < (w+2)*(w+2); i++)
1788         ds->tiles[i] = 0;              /* completely blank square */
1789     /* The clue squares... */
1790     for (i = 0; i < 4*w; i++) {
1791         long tile = state->clues->clues[i];
1792
1793         CLUEPOS(x, y, i, w);
1794
1795         if (ds->errtmp[(y+1)*(w+2)+(x+1)])
1796             tile |= DF_ERROR;
1797         else if (state->clues_done[i])
1798             tile |= DF_CLUE_DONE;
1799
1800         ds->tiles[(y+1)*(w+2)+(x+1)] = tile;
1801     }
1802     /* ... and the main grid. */
1803     for (y = 0; y < w; y++) {
1804         for (x = 0; x < w; x++) {
1805             long tile = DF_PLAYAREA;
1806
1807             if (state->grid[y*w+x])
1808                 tile |= state->grid[y*w+x];
1809             else
1810                 tile |= (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;
1811
1812             if (ui->hshow && ui->hx == x && ui->hy == y)
1813                 tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);
1814
1815             if (state->clues->immutable[y*w+x])
1816                 tile |= DF_IMMUTABLE;
1817
1818             if (flashtime > 0 &&
1819                 (flashtime <= FLASH_TIME/3 ||
1820                  flashtime >= FLASH_TIME*2/3))
1821                 tile |= DF_HIGHLIGHT;  /* completion flash */
1822
1823             if (ds->errtmp[(y+1)*(w+2)+(x+1)])
1824                 tile |= DF_ERROR;
1825
1826             ds->tiles[(y+1)*(w+2)+(x+1)] = tile;
1827         }
1828     }
1829
1830     /*
1831      * Now actually draw anything that needs to be changed.
1832      */
1833     for (y = 0; y < w+2; y++) {
1834         for (x = 0; x < w+2; x++) {
1835             long tl, tr, bl, br;
1836             int i = y*(w+2)+x;
1837
1838             tr = ds->tiles[y*(w+2)+x];
1839             tl = (x == 0 ? 0 : ds->tiles[y*(w+2)+(x-1)]);
1840             br = (y == w+1 ? 0 : ds->tiles[(y+1)*(w+2)+x]);
1841             bl = (x == 0 || y == w+1 ? 0 : ds->tiles[(y+1)*(w+2)+(x-1)]);
1842
1843             if (ds->drawn[i*4] != tl || ds->drawn[i*4+1] != tr ||
1844                 ds->drawn[i*4+2] != bl || ds->drawn[i*4+3] != br) {
1845                 clip(dr, COORD(x-1), COORD(y-1), TILESIZE, TILESIZE);
1846
1847                 draw_tile(dr, ds, state->clues, x-1, y-1, tr);
1848                 if (x > 0)
1849                     draw_tile(dr, ds, state->clues, x-2, y-1, tl);
1850                 if (y <= w)
1851                     draw_tile(dr, ds, state->clues, x-1, y, br);
1852                 if (x > 0 && y <= w)
1853                     draw_tile(dr, ds, state->clues, x-2, y, bl);
1854
1855                 unclip(dr);
1856                 draw_update(dr, COORD(x-1), COORD(y-1), TILESIZE, TILESIZE);
1857
1858                 ds->drawn[i*4] = tl;
1859                 ds->drawn[i*4+1] = tr;
1860                 ds->drawn[i*4+2] = bl;
1861                 ds->drawn[i*4+3] = br;
1862             }
1863         }
1864     }
1865 }
1866
1867 static float game_anim_length(const game_state *oldstate,
1868                               const game_state *newstate, int dir, game_ui *ui)
1869 {
1870     return 0.0F;
1871 }
1872
1873 static float game_flash_length(const game_state *oldstate,
1874                                const game_state *newstate, int dir, game_ui *ui)
1875 {
1876     if (!oldstate->completed && newstate->completed &&
1877         !oldstate->cheated && !newstate->cheated)
1878         return FLASH_TIME;
1879     return 0.0F;
1880 }
1881
1882 static int game_status(const game_state *state)
1883 {
1884     return state->completed ? +1 : 0;
1885 }
1886
1887 static int game_timing_state(const game_state *state, game_ui *ui)
1888 {
1889     if (state->completed)
1890         return FALSE;
1891     return TRUE;
1892 }
1893
1894 static void game_print_size(const game_params *params, float *x, float *y)
1895 {
1896     int pw, ph;
1897
1898     /*
1899      * We use 9mm squares by default, like Solo.
1900      */
1901     game_compute_size(params, 900, &pw, &ph);
1902     *x = pw / 100.0F;
1903     *y = ph / 100.0F;
1904 }
1905
1906 static void game_print(drawing *dr, const game_state *state, int tilesize)
1907 {
1908     int w = state->par.w;
1909     int ink = print_mono_colour(dr, 0);
1910     int i, x, y;
1911
1912     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1913     game_drawstate ads, *ds = &ads;
1914     game_set_size(dr, ds, NULL, tilesize);
1915
1916     /*
1917      * Border.
1918      */
1919     print_line_width(dr, 3 * TILESIZE / 40);
1920     draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);
1921
1922     /*
1923      * Main grid.
1924      */
1925     for (x = 1; x < w; x++) {
1926         print_line_width(dr, TILESIZE / 40);
1927         draw_line(dr, BORDER+x*TILESIZE, BORDER,
1928                   BORDER+x*TILESIZE, BORDER+w*TILESIZE, ink);
1929     }
1930     for (y = 1; y < w; y++) {
1931         print_line_width(dr, TILESIZE / 40);
1932         draw_line(dr, BORDER, BORDER+y*TILESIZE,
1933                   BORDER+w*TILESIZE, BORDER+y*TILESIZE, ink);
1934     }
1935
1936     /*
1937      * Clues.
1938      */
1939     for (i = 0; i < 4*w; i++) {
1940         char str[128];
1941
1942         if (!state->clues->clues[i])
1943             continue;
1944
1945         CLUEPOS(x, y, i, w);
1946
1947         sprintf (str, "%d", state->clues->clues[i]);
1948
1949         draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
1950                   BORDER + y*TILESIZE + TILESIZE/2,
1951                   FONT_VARIABLE, TILESIZE/2,
1952                   ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1953     }
1954
1955     /*
1956      * Numbers for the solution, if any.
1957      */
1958     for (y = 0; y < w; y++)
1959         for (x = 0; x < w; x++)
1960             if (state->grid[y*w+x]) {
1961                 char str[2];
1962                 str[1] = '\0';
1963                 str[0] = state->grid[y*w+x] + '0';
1964                 draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
1965                           BORDER + y*TILESIZE + TILESIZE/2,
1966                           FONT_VARIABLE, TILESIZE/2,
1967                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
1968             }
1969 }
1970
1971 #ifdef COMBINED
1972 #define thegame towers
1973 #endif
1974
1975 const struct game thegame = {
1976     "Towers", "games.towers", "towers",
1977     default_params,
1978     game_fetch_preset, NULL,
1979     decode_params,
1980     encode_params,
1981     free_params,
1982     dup_params,
1983     TRUE, game_configure, custom_params,
1984     validate_params,
1985     new_game_desc,
1986     validate_desc,
1987     new_game,
1988     dup_game,
1989     free_game,
1990     TRUE, solve_game,
1991     TRUE, game_can_format_as_text_now, game_text_format,
1992     new_ui,
1993     free_ui,
1994     encode_ui,
1995     decode_ui,
1996     game_changed_state,
1997     interpret_move,
1998     execute_move,
1999     PREFERRED_TILESIZE, game_compute_size, game_set_size,
2000     game_colours,
2001     game_new_drawstate,
2002     game_free_drawstate,
2003     game_redraw,
2004     game_anim_length,
2005     game_flash_length,
2006     game_status,
2007     TRUE, FALSE, game_print_size, game_print,
2008     FALSE,                             /* wants_statusbar */
2009     FALSE, game_timing_state,
2010     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
2011 };
2012
2013 #ifdef STANDALONE_SOLVER
2014
2015 #include <stdarg.h>
2016
2017 int main(int argc, char **argv)
2018 {
2019     game_params *p;
2020     game_state *s;
2021     char *id = NULL, *desc;
2022     const char *err;
2023     int grade = FALSE;
2024     int ret, diff, really_show_working = FALSE;
2025
2026     while (--argc > 0) {
2027         char *p = *++argv;
2028         if (!strcmp(p, "-v")) {
2029             really_show_working = TRUE;
2030         } else if (!strcmp(p, "-g")) {
2031             grade = TRUE;
2032         } else if (*p == '-') {
2033             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2034             return 1;
2035         } else {
2036             id = p;
2037         }
2038     }
2039
2040     if (!id) {
2041         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2042         return 1;
2043     }
2044
2045     desc = strchr(id, ':');
2046     if (!desc) {
2047         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2048         return 1;
2049     }
2050     *desc++ = '\0';
2051
2052     p = default_params();
2053     decode_params(p, id);
2054     err = validate_desc(p, desc);
2055     if (err) {
2056         fprintf(stderr, "%s: %s\n", argv[0], err);
2057         return 1;
2058     }
2059     s = new_game(NULL, p, desc);
2060
2061     /*
2062      * When solving an Easy puzzle, we don't want to bother the
2063      * user with Hard-level deductions. For this reason, we grade
2064      * the puzzle internally before doing anything else.
2065      */
2066     ret = -1;                          /* placate optimiser */
2067     solver_show_working = FALSE;
2068     for (diff = 0; diff < DIFFCOUNT; diff++) {
2069         memcpy(s->grid, s->clues->immutable, p->w * p->w);
2070         ret = solver(p->w, s->clues->clues, s->grid, diff);
2071         if (ret <= diff)
2072             break;
2073     }
2074
2075     if (diff == DIFFCOUNT) {
2076         if (grade)
2077             printf("Difficulty rating: ambiguous\n");
2078         else
2079             printf("Unable to find a unique solution\n");
2080     } else {
2081         if (grade) {
2082             if (ret == diff_impossible)
2083                 printf("Difficulty rating: impossible (no solution exists)\n");
2084             else
2085                 printf("Difficulty rating: %s\n", towers_diffnames[ret]);
2086         } else {
2087             solver_show_working = really_show_working;
2088             memcpy(s->grid, s->clues->immutable, p->w * p->w);
2089             ret = solver(p->w, s->clues->clues, s->grid, diff);
2090             if (ret != diff)
2091                 printf("Puzzle is inconsistent\n");
2092             else
2093                 fputs(game_text_format(s), stdout);
2094         }
2095     }
2096
2097     return 0;
2098 }
2099
2100 #endif
2101
2102 /* vim: set shiftwidth=4 tabstop=8: */