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