chiark / gitweb /
OS X seems particularly picky about possibly uninitialised
[sgt-puzzles.git] / inertia.c
1 /*
2  * inertia.c: Game involving navigating round a grid picking up
3  * gems.
4  * 
5  * Game rules and basic generator design by Ben Olmstead.
6  * This re-implementation was written by Simon Tatham.
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <math.h>
15
16 #include "puzzles.h"
17
18 /* Used in the game_state */
19 #define BLANK   'b'
20 #define GEM     'g'
21 #define MINE    'm'
22 #define STOP    's'
23 #define WALL    'w'
24
25 /* Used in the game IDs */
26 #define START   'S'
27
28 /* Used in the game generation */
29 #define POSSGEM 'G'
30
31 /* Used only in the game_drawstate*/
32 #define UNDRAWN '?'
33
34 #define DIRECTIONS 8
35 #define DX(dir) ( (dir) & 3 ? (((dir) & 7) > 4 ? -1 : +1) : 0 )
36 #define DY(dir) ( DX((dir)+6) )
37
38 /*
39  * Lvalue macro which expects x and y to be in range.
40  */
41 #define LV_AT(w, h, grid, x, y) ( (grid)[(y)*(w)+(x)] )
42
43 /*
44  * Rvalue macro which can cope with x and y being out of range.
45  */
46 #define AT(w, h, grid, x, y) ( (x)<0 || (x)>=(w) || (y)<0 || (y)>=(h) ? \
47                                WALL : LV_AT(w, h, grid, x, y) )
48
49 enum {
50     COL_BACKGROUND,
51     COL_OUTLINE,
52     COL_HIGHLIGHT,
53     COL_LOWLIGHT,
54     COL_PLAYER,
55     COL_DEAD_PLAYER,
56     COL_MINE,
57     COL_GEM,
58     COL_WALL,
59     NCOLOURS
60 };
61
62 struct game_params {
63     int w, h;
64 };
65
66 struct game_state {
67     game_params p;
68     int px, py;
69     int gems;
70     char *grid;
71     int distance_moved;
72     int dead;
73 };
74
75 static game_params *default_params(void)
76 {
77     game_params *ret = snew(game_params);
78
79     ret->w = 10;
80     ret->h = 8;
81
82     return ret;
83 }
84
85 static void free_params(game_params *params)
86 {
87     sfree(params);
88 }
89
90 static game_params *dup_params(game_params *params)
91 {
92     game_params *ret = snew(game_params);
93     *ret = *params;                    /* structure copy */
94     return ret;
95 }
96
97 static const struct game_params inertia_presets[] = {
98     { 10, 8 },
99     { 15, 12 },
100     { 20, 16 },
101 };
102
103 static int game_fetch_preset(int i, char **name, game_params **params)
104 {
105     game_params p, *ret;
106     char *retname;
107     char namebuf[80];
108
109     if (i < 0 || i >= lenof(inertia_presets))
110         return FALSE;
111
112     p = inertia_presets[i];
113     ret = dup_params(&p);
114     sprintf(namebuf, "%dx%d", ret->w, ret->h);
115     retname = dupstr(namebuf);
116
117     *params = ret;
118     *name = retname;
119     return TRUE;
120 }
121
122 static void decode_params(game_params *params, char const *string)
123 {
124     params->w = params->h = atoi(string);
125     while (*string && isdigit((unsigned char)*string)) string++;
126     if (*string == 'x') {
127         string++;
128         params->h = atoi(string);
129     }
130 }
131
132 static char *encode_params(game_params *params, int full)
133 {
134     char data[256];
135
136     sprintf(data, "%dx%d", params->w, params->h);
137
138     return dupstr(data);
139 }
140
141 static config_item *game_configure(game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(3, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].sval = dupstr(buf);
152     ret[0].ival = 0;
153
154     ret[1].name = "Height";
155     ret[1].type = C_STRING;
156     sprintf(buf, "%d", params->h);
157     ret[1].sval = dupstr(buf);
158     ret[1].ival = 0;
159
160     ret[2].name = NULL;
161     ret[2].type = C_END;
162     ret[2].sval = NULL;
163     ret[2].ival = 0;
164
165     return ret;
166 }
167
168 static game_params *custom_params(config_item *cfg)
169 {
170     game_params *ret = snew(game_params);
171
172     ret->w = atoi(cfg[0].sval);
173     ret->h = atoi(cfg[1].sval);
174
175     return ret;
176 }
177
178 static char *validate_params(game_params *params, int full)
179 {
180     /*
181      * Avoid completely degenerate cases which only have one
182      * row/column. We probably could generate completable puzzles
183      * of that shape, but they'd be forced to be extremely boring
184      * and at large sizes would take a while to happen upon at
185      * random as well.
186      */
187     if (params->w < 2 || params->h < 2)
188         return "Width and height must both be at least two";
189
190     /*
191      * The grid construction algorithm creates 1/5 as many gems as
192      * grid squares, and must create at least one gem to have an
193      * actual puzzle. However, an area-five grid is ruled out by
194      * the above constraint, so the practical minimum is six.
195      */
196     if (params->w * params->h < 6)
197         return "Grid area must be at least six squares";
198
199     return NULL;
200 }
201
202 /* ----------------------------------------------------------------------
203  * Solver used by grid generator.
204  */
205
206 struct solver_scratch {
207     unsigned char *reachable_from, *reachable_to;
208     int *positions;
209 };
210
211 static struct solver_scratch *new_scratch(int w, int h)
212 {
213     struct solver_scratch *sc = snew(struct solver_scratch);
214
215     sc->reachable_from = snewn(w * h * DIRECTIONS, unsigned char);
216     sc->reachable_to = snewn(w * h * DIRECTIONS, unsigned char);
217     sc->positions = snewn(w * h * DIRECTIONS, int);
218
219     return sc;
220 }
221
222 static void free_scratch(struct solver_scratch *sc)
223 {
224     sfree(sc);
225 }
226
227 static int can_go(int w, int h, char *grid,
228                   int x1, int y1, int dir1, int x2, int y2, int dir2)
229 {
230     /*
231      * Returns TRUE if we can transition directly from (x1,y1)
232      * going in direction dir1, to (x2,y2) going in direction dir2.
233      */
234
235     /*
236      * If we're actually in the middle of an unoccupyable square,
237      * we cannot make any move.
238      */
239     if (AT(w, h, grid, x1, y1) == WALL ||
240         AT(w, h, grid, x1, y1) == MINE)
241         return FALSE;
242
243     /*
244      * If a move is capable of stopping at x1,y1,dir1, and x2,y2 is
245      * the same coordinate as x1,y1, then we can make the
246      * transition (by stopping and changing direction).
247      * 
248      * For this to be the case, we have to either have a wall
249      * beyond x1,y1,dir1, or have a stop on x1,y1.
250      */
251     if (x2 == x1 && y2 == y1 &&
252         (AT(w, h, grid, x1, y1) == STOP ||
253          AT(w, h, grid, x1, y1) == START ||
254          AT(w, h, grid, x1+DX(dir1), y1+DY(dir1)) == WALL))
255         return TRUE;
256
257     /*
258      * If a move is capable of continuing here, then x1,y1,dir1 can
259      * move one space further on.
260      */
261     if (x2 == x1+DX(dir1) && y2 == y1+DY(dir1) && dir1 == dir2 &&
262         (AT(w, h, grid, x2, y2) == BLANK ||
263          AT(w, h, grid, x2, y2) == GEM ||
264          AT(w, h, grid, x2, y2) == STOP ||
265          AT(w, h, grid, x2, y2) == START))
266         return TRUE;
267
268     /*
269      * That's it.
270      */
271     return FALSE;
272 }
273
274 static int find_gem_candidates(int w, int h, char *grid,
275                                struct solver_scratch *sc)
276 {
277     int wh = w*h;
278     int head, tail;
279     int sx, sy, gx, gy, gd, pass, possgems;
280
281     /*
282      * This function finds all the candidate gem squares, which are
283      * precisely those squares which can be picked up on a loop
284      * from the starting point back to the starting point. Doing
285      * this may involve passing through such a square in the middle
286      * of a move; so simple breadth-first search over the _squares_
287      * of the grid isn't quite adequate, because it might be that
288      * we can only reach a gem from the start by moving over it in
289      * one direction, but can only return to the start if we were
290      * moving over it in another direction.
291      * 
292      * Instead, we BFS over a space which mentions each grid square
293      * eight times - once for each direction. We also BFS twice:
294      * once to find out what square+direction pairs we can reach
295      * _from_ the start point, and once to find out what pairs we
296      * can reach the start point from. Then a square is reachable
297      * if any of the eight directions for that square has both
298      * flags set.
299      */
300
301     memset(sc->reachable_from, 0, wh * DIRECTIONS);
302     memset(sc->reachable_to, 0, wh * DIRECTIONS);
303
304     /*
305      * Find the starting square.
306      */
307     sx = -1;                           /* placate optimiser */
308     for (sy = 0; sy < h; sy++) {
309         for (sx = 0; sx < w; sx++)
310             if (AT(w, h, grid, sx, sy) == START)
311                 break;
312         if (sx < w)
313             break;
314     }
315     assert(sy < h);
316
317     for (pass = 0; pass < 2; pass++) {
318         unsigned char *reachable = (pass == 0 ? sc->reachable_from :
319                                     sc->reachable_to);
320         int sign = (pass == 0 ? +1 : -1);
321         int dir;
322
323 #ifdef SOLVER_DIAGNOSTICS
324         printf("starting pass %d\n", pass);
325 #endif
326
327         /*
328          * `head' and `tail' are indices within sc->positions which
329          * track the list of board positions left to process.
330          */
331         head = tail = 0;
332         for (dir = 0; dir < DIRECTIONS; dir++) {
333             int index = (sy*w+sx)*DIRECTIONS+dir;
334             sc->positions[tail++] = index;
335             reachable[index] = TRUE;
336 #ifdef SOLVER_DIAGNOSTICS
337             printf("starting point %d,%d,%d\n", sx, sy, dir);
338 #endif
339         }
340
341         /*
342          * Now repeatedly pick an element off the list and process
343          * it.
344          */
345         while (head < tail) {
346             int index = sc->positions[head++];
347             int dir = index % DIRECTIONS;
348             int x = (index / DIRECTIONS) % w;
349             int y = index / (w * DIRECTIONS);
350             int n, x2, y2, d2, i2;
351
352 #ifdef SOLVER_DIAGNOSTICS
353             printf("processing point %d,%d,%d\n", x, y, dir);
354 #endif
355             /*
356              * The places we attempt to switch to here are:
357              *  - each possible direction change (all the other
358              *    directions in this square)
359              *  - one step further in the direction we're going (or
360              *    one step back, if we're in the reachable_to pass).
361              */
362             for (n = -1; n < DIRECTIONS; n++) {
363                 if (n < 0) {
364                     x2 = x + sign * DX(dir);
365                     y2 = y + sign * DY(dir);
366                     d2 = dir;
367                 } else {
368                     x2 = x;
369                     y2 = y;
370                     d2 = n;
371                 }
372                 i2 = (y2*w+x2)*DIRECTIONS+d2;
373                 if (!reachable[i2]) {
374                     int ok;
375 #ifdef SOLVER_DIAGNOSTICS
376                     printf("  trying point %d,%d,%d", x2, y2, d2);
377 #endif
378                     if (pass == 0)
379                         ok = can_go(w, h, grid, x, y, dir, x2, y2, d2);
380                     else
381                         ok = can_go(w, h, grid, x2, y2, d2, x, y, dir);
382 #ifdef SOLVER_DIAGNOSTICS
383                     printf(" - %sok\n", ok ? "" : "not ");
384 #endif
385                     if (ok) {
386                         sc->positions[tail++] = i2;
387                         reachable[i2] = TRUE;
388                     }
389                 }
390             }
391         }
392     }
393
394     /*
395      * And that should be it. Now all we have to do is find the
396      * squares for which there exists _some_ direction such that
397      * the square plus that direction form a tuple which is both
398      * reachable from the start and reachable to the start.
399      */
400     possgems = 0;
401     for (gy = 0; gy < h; gy++)
402         for (gx = 0; gx < w; gx++)
403             if (AT(w, h, grid, gx, gy) == BLANK) {
404                 for (gd = 0; gd < DIRECTIONS; gd++) {
405                     int index = (gy*w+gx)*DIRECTIONS+gd;
406                     if (sc->reachable_from[index] && sc->reachable_to[index]) {
407 #ifdef SOLVER_DIAGNOSTICS
408                         printf("space at %d,%d is reachable via"
409                                " direction %d\n", gx, gy, gd);
410 #endif
411                         LV_AT(w, h, grid, gx, gy) = POSSGEM;
412                         possgems++;
413                         break;
414                     }
415                 }
416             }
417
418     return possgems;
419 }
420
421 /* ----------------------------------------------------------------------
422  * Grid generation code.
423  */
424
425 static char *gengrid(int w, int h, random_state *rs)
426 {
427     int wh = w*h;
428     char *grid = snewn(wh+1, char);
429     struct solver_scratch *sc = new_scratch(w, h);
430     int maxdist_threshold, tries;
431
432     maxdist_threshold = 2;
433     tries = 0;
434
435     while (1) {
436         int i, j;
437         int possgems;
438         int *dist, *list, head, tail, maxdist;
439
440         /*
441          * We're going to fill the grid with the five basic piece
442          * types in about 1/5 proportion. For the moment, though,
443          * we leave out the gems, because we'll put those in
444          * _after_ we run the solver to tell us where the viable
445          * locations are.
446          */
447         i = 0;
448         for (j = 0; j < wh/5; j++)
449             grid[i++] = WALL;
450         for (j = 0; j < wh/5; j++)
451             grid[i++] = STOP;
452         for (j = 0; j < wh/5; j++)
453             grid[i++] = MINE;
454         assert(i < wh);
455         grid[i++] = START;
456         while (i < wh)
457             grid[i++] = BLANK;
458         shuffle(grid, wh, sizeof(*grid), rs);
459
460         /*
461          * Find the viable gem locations, and immediately give up
462          * and try again if there aren't enough of them.
463          */
464         possgems = find_gem_candidates(w, h, grid, sc);
465         if (possgems < wh/5)
466             continue;
467
468         /*
469          * We _could_ now select wh/5 of the POSSGEMs and set them
470          * to GEM, and have a viable level. However, there's a
471          * chance that a large chunk of the level will turn out to
472          * be unreachable, so first we test for that.
473          * 
474          * We do this by finding the largest distance from any
475          * square to the nearest POSSGEM, by breadth-first search.
476          * If this is above a critical threshold, we abort and try
477          * again.
478          * 
479          * (This search is purely geometric, without regard to
480          * walls and long ways round.)
481          */
482         dist = sc->positions;
483         list = sc->positions + wh;
484         for (i = 0; i < wh; i++)
485             dist[i] = -1;
486         head = tail = 0;
487         for (i = 0; i < wh; i++)
488             if (grid[i] == POSSGEM) {
489                 dist[i] = 0;
490                 list[tail++] = i;
491             }
492         maxdist = 0;
493         while (head < tail) {
494             int pos, x, y, d;
495
496             pos = list[head++];
497             if (maxdist < dist[pos])
498                 maxdist = dist[pos];
499
500             x = pos % w;
501             y = pos / w;
502
503             for (d = 0; d < DIRECTIONS; d++) {
504                 int x2, y2, p2;
505
506                 x2 = x + DX(d);
507                 y2 = y + DY(d);
508
509                 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) {
510                     p2 = y2*w+x2;
511                     if (dist[p2] < 0) {
512                         dist[p2] = dist[pos] + 1;
513                         list[tail++] = p2;
514                     }
515                 }
516             }
517         }
518         assert(head == wh && tail == wh);
519
520         /*
521          * Now abandon this grid and go round again if maxdist is
522          * above the required threshold.
523          * 
524          * We can safely start the threshold as low as 2. As we
525          * accumulate failed generation attempts, we gradually
526          * raise it as we get more desperate.
527          */
528         if (maxdist > maxdist_threshold) {
529             tries++;
530             if (tries == 50) {
531                 maxdist_threshold++;
532                 tries = 0;
533             }
534             continue;
535         }
536
537         /*
538          * Now our reachable squares are plausibly evenly
539          * distributed over the grid. I'm not actually going to
540          * _enforce_ that I place the gems in such a way as not to
541          * increase that maxdist value; I'm now just going to trust
542          * to the RNG to pick a sensible subset of the POSSGEMs.
543          */
544         j = 0;
545         for (i = 0; i < wh; i++)
546             if (grid[i] == POSSGEM)
547                 list[j++] = i;
548         shuffle(list, j, sizeof(*list), rs);
549         for (i = 0; i < j; i++)
550             grid[list[i]] = (i < wh/5 ? GEM : BLANK);
551         break;
552     }
553
554     free_scratch(sc);
555
556     grid[wh] = '\0';
557
558     return grid;
559 }
560
561 static char *new_game_desc(game_params *params, random_state *rs,
562                            char **aux, int interactive)
563 {
564     return gengrid(params->w, params->h, rs);
565 }
566
567 static char *validate_desc(game_params *params, char *desc)
568 {
569     int w = params->w, h = params->h, wh = w*h;
570     int starts = 0, gems = 0, i;
571
572     for (i = 0; i < wh; i++) {
573         if (!desc[i])
574             return "Not enough data to fill grid";
575         if (desc[i] != WALL && desc[i] != START && desc[i] != STOP &&
576             desc[i] != GEM && desc[i] != MINE && desc[i] != BLANK)
577             return "Unrecognised character in game description";
578         if (desc[i] == START)
579             starts++;
580         if (desc[i] == GEM)
581             gems++;
582     }
583     if (desc[i])
584         return "Too much data to fill grid";
585     if (starts < 1)
586         return "No starting square specified";
587     if (starts > 1)
588         return "More than one starting square specified";
589     if (gems < 1)
590         return "No gems specified";
591
592     return NULL;
593 }
594
595 static game_state *new_game(midend *me, game_params *params, char *desc)
596 {
597     int w = params->w, h = params->h, wh = w*h;
598     int i;
599     game_state *state = snew(game_state);
600
601     state->p = *params;                /* structure copy */
602
603     state->grid = snewn(wh, char);
604     assert(strlen(desc) == wh);
605     memcpy(state->grid, desc, wh);
606
607     state->px = state->py = -1;
608     state->gems = 0;
609     for (i = 0; i < wh; i++) {
610         if (state->grid[i] == START) {
611             state->grid[i] = STOP;
612             state->px = i % w;
613             state->py = i / w;
614         } else if (state->grid[i] == GEM) {
615             state->gems++;
616         }
617     }
618
619     assert(state->gems > 0);
620     assert(state->px >= 0 && state->py >= 0);
621
622     state->distance_moved = 0;
623     state->dead = FALSE;
624
625     return state;
626 }
627
628 static game_state *dup_game(game_state *state)
629 {
630     int w = state->p.w, h = state->p.h, wh = w*h;
631     game_state *ret = snew(game_state);
632
633     ret->p = state->p;
634     ret->px = state->px;
635     ret->py = state->py;
636     ret->gems = state->gems;
637     ret->grid = snewn(wh, char);
638     ret->distance_moved = state->distance_moved;
639     ret->dead = FALSE;
640     memcpy(ret->grid, state->grid, wh);
641
642     return ret;
643 }
644
645 static void free_game(game_state *state)
646 {
647     sfree(state->grid);
648     sfree(state);
649 }
650
651 static char *solve_game(game_state *state, game_state *currstate,
652                         char *aux, char **error)
653 {
654     return NULL;
655 }
656
657 static char *game_text_format(game_state *state)
658 {
659     return NULL;
660 }
661
662 struct game_ui {
663     float anim_length;
664     int flashtype;
665     int deaths;
666     int just_made_move;
667     int just_died;
668 };
669
670 static game_ui *new_ui(game_state *state)
671 {
672     game_ui *ui = snew(game_ui);
673     ui->anim_length = 0.0F;
674     ui->flashtype = 0;
675     ui->deaths = 0;
676     ui->just_made_move = FALSE;
677     ui->just_died = FALSE;
678     return ui;
679 }
680
681 static void free_ui(game_ui *ui)
682 {
683     sfree(ui);
684 }
685
686 static char *encode_ui(game_ui *ui)
687 {
688     char buf[80];
689     /*
690      * The deaths counter needs preserving across a serialisation.
691      */
692     sprintf(buf, "D%d", ui->deaths);
693     return dupstr(buf);
694 }
695
696 static void decode_ui(game_ui *ui, char *encoding)
697 {
698     int p = 0;
699     sscanf(encoding, "D%d%n", &ui->deaths, &p);
700 }
701
702 static void game_changed_state(game_ui *ui, game_state *oldstate,
703                                game_state *newstate)
704 {
705     /*
706      * Increment the deaths counter. We only do this if
707      * ui->just_made_move is set (redoing a suicide move doesn't
708      * kill you _again_), and also we only do it if the game isn't
709      * completed (once you're finished, you can play).
710      */
711     if (!oldstate->dead && newstate->dead && ui->just_made_move &&
712         newstate->gems) {
713         ui->deaths++;
714         ui->just_died = TRUE;
715     } else {
716         ui->just_died = FALSE;
717     }
718     ui->just_made_move = FALSE;
719 }
720
721 struct game_drawstate {
722     game_params p;
723     int tilesize;
724     int started;
725     unsigned short *grid;
726     blitter *player_background;
727     int player_bg_saved, pbgx, pbgy;
728 };
729
730 #define PREFERRED_TILESIZE 32
731 #define TILESIZE (ds->tilesize)
732 #define BORDER    (TILESIZE)
733 #define HIGHLIGHT_WIDTH (TILESIZE / 10)
734 #define COORD(x)  ( (x) * TILESIZE + BORDER )
735 #define FROMCOORD(x)  ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
736
737 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
738                             int x, int y, int button)
739 {
740     int w = state->p.w, h = state->p.h /*, wh = w*h */;
741     int dir;
742     char buf[80];
743
744     dir = -1;
745
746     if (button == LEFT_BUTTON) {
747         /*
748          * Mouse-clicking near the target point (or, more
749          * accurately, in the appropriate octant) is an alternative
750          * way to input moves.
751          */
752
753         if (FROMCOORD(x) != state->px || FROMCOORD(y) != state->py) {
754             int dx, dy;
755             float angle;
756
757             dx = FROMCOORD(x) - state->px;
758             dy = FROMCOORD(y) - state->py;
759             /* I pass dx,dy rather than dy,dx so that the octants
760              * end up the right way round. */
761             angle = atan2(dx, -dy);
762
763             angle = (angle + (PI/8)) / (PI/4);
764             assert(angle > -16.0F);
765             dir = (int)(angle + 16.0F) & 7;
766         }
767     } else if (button == CURSOR_UP || button == (MOD_NUM_KEYPAD | '8'))
768         dir = 0;
769     else if (button == CURSOR_DOWN || button == (MOD_NUM_KEYPAD | '2'))
770         dir = 4;
771     else if (button == CURSOR_LEFT || button == (MOD_NUM_KEYPAD | '4'))
772         dir = 6;
773     else if (button == CURSOR_RIGHT || button == (MOD_NUM_KEYPAD | '6'))
774         dir = 2;
775     else if (button == (MOD_NUM_KEYPAD | '7'))
776         dir = 7;
777     else if (button == (MOD_NUM_KEYPAD | '1'))
778         dir = 5;
779     else if (button == (MOD_NUM_KEYPAD | '9'))
780         dir = 1;
781     else if (button == (MOD_NUM_KEYPAD | '3'))
782         dir = 3;
783
784     if (dir < 0)
785         return NULL;
786
787     /*
788      * Reject the move if we can't make it at all due to a wall
789      * being in the way.
790      */
791     if (AT(w, h, state->grid, state->px+DX(dir), state->py+DY(dir)) == WALL)
792         return NULL;
793
794     /*
795      * Reject the move if we're dead!
796      */
797     if (state->dead)
798         return NULL;
799
800     /*
801      * Otherwise, we can make the move. All we need to specify is
802      * the direction.
803      */
804     ui->just_made_move = TRUE;
805     sprintf(buf, "%d", dir);
806     return dupstr(buf);
807 }
808
809 static game_state *execute_move(game_state *state, char *move)
810 {
811     int w = state->p.w, h = state->p.h /*, wh = w*h */;
812     int dir = atoi(move);
813     game_state *ret;
814
815     if (dir < 0 || dir >= DIRECTIONS)
816         return NULL;                   /* huh? */
817
818     if (state->dead)
819         return NULL;
820
821     if (AT(w, h, state->grid, state->px+DX(dir), state->py+DY(dir)) == WALL)
822         return NULL;                   /* wall in the way! */
823
824     /*
825      * Now make the move.
826      */
827     ret = dup_game(state);
828     ret->distance_moved = 0;
829     while (1) {
830         ret->px += DX(dir);
831         ret->py += DY(dir);
832         ret->distance_moved++;
833
834         if (AT(w, h, ret->grid, ret->px, ret->py) == GEM) {
835             LV_AT(w, h, ret->grid, ret->px, ret->py) = BLANK;
836             ret->gems--;
837         }
838
839         if (AT(w, h, ret->grid, ret->px, ret->py) == MINE) {
840             ret->dead = TRUE;
841             break;
842         }
843
844         if (AT(w, h, ret->grid, ret->px, ret->py) == STOP ||
845             AT(w, h, ret->grid, ret->px+DX(dir),
846                ret->py+DY(dir)) == WALL)
847             break;
848     }
849
850     return ret;
851 }
852
853 /* ----------------------------------------------------------------------
854  * Drawing routines.
855  */
856
857 static void game_compute_size(game_params *params, int tilesize,
858                               int *x, int *y)
859 {
860     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
861     struct { int tilesize; } ads, *ds = &ads;
862     ads.tilesize = tilesize;
863
864     *x = 2 * BORDER + 1 + params->w * TILESIZE;
865     *y = 2 * BORDER + 1 + params->h * TILESIZE;
866 }
867
868 static void game_set_size(drawing *dr, game_drawstate *ds,
869                           game_params *params, int tilesize)
870 {
871     ds->tilesize = tilesize;
872
873     assert(!ds->player_bg_saved);
874
875     if (ds->player_background)
876         blitter_free(dr, ds->player_background);
877     ds->player_background = blitter_new(dr, TILESIZE, TILESIZE);
878 }
879
880 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
881 {
882     float *ret = snewn(3 * NCOLOURS, float);
883     int i;
884
885     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
886
887     ret[COL_OUTLINE * 3 + 0] = 0.0F;
888     ret[COL_OUTLINE * 3 + 1] = 0.0F;
889     ret[COL_OUTLINE * 3 + 2] = 0.0F;
890
891     ret[COL_PLAYER * 3 + 0] = 0.0F;
892     ret[COL_PLAYER * 3 + 1] = 1.0F;
893     ret[COL_PLAYER * 3 + 2] = 0.0F;
894
895     ret[COL_DEAD_PLAYER * 3 + 0] = 1.0F;
896     ret[COL_DEAD_PLAYER * 3 + 1] = 0.0F;
897     ret[COL_DEAD_PLAYER * 3 + 2] = 0.0F;
898
899     ret[COL_MINE * 3 + 0] = 0.0F;
900     ret[COL_MINE * 3 + 1] = 0.0F;
901     ret[COL_MINE * 3 + 2] = 0.0F;
902
903     ret[COL_GEM * 3 + 0] = 0.6F;
904     ret[COL_GEM * 3 + 1] = 1.0F;
905     ret[COL_GEM * 3 + 2] = 1.0F;
906
907     for (i = 0; i < 3; i++) {
908         ret[COL_WALL * 3 + i] = (3 * ret[COL_BACKGROUND * 3 + i] +
909                                  1 * ret[COL_HIGHLIGHT * 3 + i]) / 4;
910     }
911
912     *ncolours = NCOLOURS;
913     return ret;
914 }
915
916 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
917 {
918     int w = state->p.w, h = state->p.h, wh = w*h;
919     struct game_drawstate *ds = snew(struct game_drawstate);
920     int i;
921
922     ds->tilesize = 0;
923
924     /* We can't allocate the blitter rectangle for the player background
925      * until we know what size to make it. */
926     ds->player_background = NULL;
927     ds->player_bg_saved = FALSE;
928     ds->pbgx = ds->pbgy = -1;
929
930     ds->p = state->p;                  /* structure copy */
931     ds->started = FALSE;
932     ds->grid = snewn(wh, unsigned short);
933     for (i = 0; i < wh; i++)
934         ds->grid[i] = UNDRAWN;
935
936     return ds;
937 }
938
939 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
940 {
941     sfree(ds->grid);
942     sfree(ds);
943 }
944
945 static void draw_player(drawing *dr, game_drawstate *ds, int x, int y,
946                         int dead)
947 {
948     if (dead) {
949         int coords[DIRECTIONS*4];
950         int d;
951
952         for (d = 0; d < DIRECTIONS; d++) {
953             float x1, y1, x2, y2, x3, y3, len;
954
955             x1 = DX(d);
956             y1 = DY(d);
957             len = sqrt(x1*x1+y1*y1); x1 /= len; y1 /= len;
958
959             x3 = DX(d+1);
960             y3 = DY(d+1);
961             len = sqrt(x3*x3+y3*y3); x3 /= len; y3 /= len;
962
963             x2 = (x1+x3) / 4;
964             y2 = (y1+y3) / 4;
965
966             coords[d*4+0] = x + TILESIZE/2 + (int)((TILESIZE*3/7) * x1);
967             coords[d*4+1] = y + TILESIZE/2 + (int)((TILESIZE*3/7) * y1);
968             coords[d*4+2] = x + TILESIZE/2 + (int)((TILESIZE*3/7) * x2);
969             coords[d*4+3] = y + TILESIZE/2 + (int)((TILESIZE*3/7) * y2);
970         }
971         draw_polygon(dr, coords, DIRECTIONS*2, COL_DEAD_PLAYER, COL_OUTLINE);
972     } else {
973         draw_circle(dr, x + TILESIZE/2, y + TILESIZE/2,
974                     TILESIZE/3, COL_PLAYER, COL_OUTLINE);
975     }
976     draw_update(dr, x, y, TILESIZE, TILESIZE);
977 }
978
979 #define FLASH_DEAD 0x100
980 #define FLASH_WIN  0x200
981 #define FLASH_MASK 0x300
982
983 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, int v)
984 {
985     int tx = COORD(x), ty = COORD(y);
986     int bg = (v & FLASH_DEAD ? COL_DEAD_PLAYER :
987               v & FLASH_WIN ? COL_HIGHLIGHT : COL_BACKGROUND);
988
989     v &= ~FLASH_MASK;
990
991     clip(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1);
992     draw_rect(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1, bg);
993
994     if (v == WALL) {
995         int coords[6];
996
997         coords[0] = tx + TILESIZE;
998         coords[1] = ty + TILESIZE;
999         coords[2] = tx + TILESIZE;
1000         coords[3] = ty + 1;
1001         coords[4] = tx + 1;
1002         coords[5] = ty + TILESIZE;
1003         draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
1004
1005         coords[0] = tx + 1;
1006         coords[1] = ty + 1;
1007         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1008
1009         draw_rect(dr, tx + 1 + HIGHLIGHT_WIDTH, ty + 1 + HIGHLIGHT_WIDTH,
1010                   TILESIZE - 2*HIGHLIGHT_WIDTH,
1011                   TILESIZE - 2*HIGHLIGHT_WIDTH, COL_WALL);
1012     } else if (v == MINE) {
1013         int cx = tx + TILESIZE / 2;
1014         int cy = ty + TILESIZE / 2;
1015         int r = TILESIZE / 2 - 3;
1016         int coords[4*5*2];
1017         int xdx = 1, xdy = 0, ydx = 0, ydy = 1;
1018         int tdx, tdy, i;
1019
1020         for (i = 0; i < 4*5*2; i += 5*2) {
1021             coords[i+2*0+0] = cx - r/6*xdx + r*4/5*ydx;
1022             coords[i+2*0+1] = cy - r/6*xdy + r*4/5*ydy;
1023             coords[i+2*1+0] = cx - r/6*xdx + r*ydx;
1024             coords[i+2*1+1] = cy - r/6*xdy + r*ydy;
1025             coords[i+2*2+0] = cx + r/6*xdx + r*ydx;
1026             coords[i+2*2+1] = cy + r/6*xdy + r*ydy;
1027             coords[i+2*3+0] = cx + r/6*xdx + r*4/5*ydx;
1028             coords[i+2*3+1] = cy + r/6*xdy + r*4/5*ydy;
1029             coords[i+2*4+0] = cx + r*3/5*xdx + r*3/5*ydx;
1030             coords[i+2*4+1] = cy + r*3/5*xdy + r*3/5*ydy;
1031
1032             tdx = ydx;
1033             tdy = ydy;
1034             ydx = xdx;
1035             ydy = xdy;
1036             xdx = -tdx;
1037             xdy = -tdy;
1038         }
1039
1040         draw_polygon(dr, coords, 5*4, COL_MINE, COL_MINE);
1041
1042         draw_rect(dr, cx-r/3, cy-r/3, r/3, r/4, COL_HIGHLIGHT);
1043     } else if (v == STOP) {
1044         draw_circle(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1045                     TILESIZE*3/7, -1, COL_OUTLINE);
1046         draw_rect(dr, tx + TILESIZE*3/7, ty+1,
1047                   TILESIZE - 2*(TILESIZE*3/7) + 1, TILESIZE-1, bg);
1048         draw_rect(dr, tx+1, ty + TILESIZE*3/7,
1049                   TILESIZE-1, TILESIZE - 2*(TILESIZE*3/7) + 1, bg);
1050     } else if (v == GEM) {
1051         int coords[8];
1052
1053         coords[0] = tx+TILESIZE/2;
1054         coords[1] = ty+TILESIZE*1/7;
1055         coords[2] = tx+TILESIZE*1/7;
1056         coords[3] = ty+TILESIZE/2;
1057         coords[4] = tx+TILESIZE/2;
1058         coords[5] = ty+TILESIZE-TILESIZE*1/7;
1059         coords[6] = tx+TILESIZE-TILESIZE*1/7;
1060         coords[7] = ty+TILESIZE/2;
1061
1062         draw_polygon(dr, coords, 4, COL_GEM, COL_OUTLINE);
1063     }
1064
1065     unclip(dr);
1066     draw_update(dr, tx, ty, TILESIZE, TILESIZE);
1067 }
1068
1069 #define BASE_ANIM_LENGTH 0.1F
1070 #define FLASH_LENGTH 0.3F
1071
1072 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1073                         game_state *state, int dir, game_ui *ui,
1074                         float animtime, float flashtime)
1075 {
1076     int w = state->p.w, h = state->p.h /*, wh = w*h */;
1077     int x, y;
1078     float ap;
1079     int player_dist;
1080     int flashtype;
1081     int gems, deaths;
1082     char status[256];
1083
1084     if (flashtime &&
1085         !((int)(flashtime * 3 / FLASH_LENGTH) % 2))
1086         flashtype = ui->flashtype;
1087     else
1088         flashtype = 0;
1089
1090     /*
1091      * Erase the player sprite.
1092      */
1093     if (ds->player_bg_saved) {
1094         assert(ds->player_background);
1095         blitter_load(dr, ds->player_background, ds->pbgx, ds->pbgy);
1096         draw_update(dr, ds->pbgx, ds->pbgy, TILESIZE, TILESIZE);
1097         ds->player_bg_saved = FALSE;
1098     }
1099
1100     /*
1101      * Initialise a fresh drawstate.
1102      */
1103     if (!ds->started) {
1104         int wid, ht;
1105
1106         /*
1107          * Blank out the window initially.
1108          */
1109         game_compute_size(&ds->p, TILESIZE, &wid, &ht);
1110         draw_rect(dr, 0, 0, wid, ht, COL_BACKGROUND);
1111         draw_update(dr, 0, 0, wid, ht);
1112
1113         /*
1114          * Draw the grid lines.
1115          */
1116         for (y = 0; y <= h; y++)
1117             draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y),
1118                       COL_LOWLIGHT);
1119         for (x = 0; x <= w; x++)
1120             draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h),
1121                       COL_LOWLIGHT);
1122
1123         ds->started = TRUE;
1124     }
1125
1126     /*
1127      * If we're in the process of animating a move, let's start by
1128      * working out how far the player has moved from their _older_
1129      * state.
1130      */
1131     if (oldstate) {
1132         ap = animtime / ui->anim_length;
1133         player_dist = ap * (dir > 0 ? state : oldstate)->distance_moved;
1134     } else {
1135         player_dist = 0;
1136         ap = 0.0F;
1137     }
1138
1139     /*
1140      * Draw the grid contents.
1141      * 
1142      * We count the gems as we go round this loop, for the purposes
1143      * of the status bar. Of course we have a gems counter in the
1144      * game_state already, but if we do the counting in this loop
1145      * then it tracks gems being picked up in a sliding move, and
1146      * updates one by one.
1147      */
1148     gems = 0;
1149     for (y = 0; y < h; y++)
1150         for (x = 0; x < w; x++) {
1151             unsigned short v = (unsigned char)state->grid[y*w+x];
1152
1153             /*
1154              * Special case: if the player is in the process of
1155              * moving over a gem, we draw the gem iff they haven't
1156              * gone past it yet.
1157              */
1158             if (oldstate && oldstate->grid[y*w+x] != state->grid[y*w+x]) {
1159                 /*
1160                  * Compute the distance from this square to the
1161                  * original player position.
1162                  */
1163                 int dist = max(abs(x - oldstate->px), abs(y - oldstate->py));
1164
1165                 /*
1166                  * If the player has reached here, use the new grid
1167                  * element. Otherwise use the old one.
1168                  */
1169                 if (player_dist < dist)
1170                     v = oldstate->grid[y*w+x];
1171                 else
1172                     v = state->grid[y*w+x];
1173             }
1174
1175             /*
1176              * Special case: erase the mine the dead player is
1177              * sitting on. Only at the end of the move.
1178              */
1179             if (v == MINE && !oldstate && state->dead &&
1180                 x == state->px && y == state->py)
1181                 v = BLANK;
1182
1183             if (v == GEM)
1184                 gems++;
1185
1186             v |= flashtype;
1187
1188             if (ds->grid[y*w+x] != v) {
1189                 draw_tile(dr, ds, x, y, v);
1190                 ds->grid[y*w+x] = v;
1191             }
1192         }
1193
1194     /*
1195      * Gem counter in the status bar. We replace it with
1196      * `COMPLETED!' when it reaches zero ... or rather, when the
1197      * _current state_'s gem counter is zero. (Thus, `Gems: 0' is
1198      * shown between the collection of the last gem and the
1199      * completion of the move animation that did it.)
1200      */
1201     if (state->dead && (!oldstate || oldstate->dead))
1202         sprintf(status, "DEAD!");
1203     else if (state->gems || (oldstate && oldstate->gems))
1204         sprintf(status, "Gems: %d", gems);
1205     else
1206         sprintf(status, "COMPLETED!");
1207     /* We subtract one from the visible death counter if we're still
1208      * animating the move at the end of which the death took place. */
1209     deaths = ui->deaths;
1210     if (oldstate && ui->just_died) {
1211         assert(deaths > 0);
1212         deaths--;
1213     }
1214     if (deaths)
1215         sprintf(status + strlen(status), "   Deaths: %d", deaths);
1216     status_bar(dr, status);
1217
1218     /*
1219      * Draw the player sprite.
1220      */
1221     assert(!ds->player_bg_saved);
1222     assert(ds->player_background);
1223     {
1224         int ox, oy, nx, ny;
1225         nx = COORD(state->px);
1226         ny = COORD(state->py);
1227         if (oldstate) {
1228             ox = COORD(oldstate->px);
1229             oy = COORD(oldstate->py);
1230         } else {
1231             ox = nx;
1232             oy = ny;
1233         }
1234         ds->pbgx = ox + ap * (nx - ox);
1235         ds->pbgy = oy + ap * (ny - oy);
1236     }
1237     blitter_save(dr, ds->player_background, ds->pbgx, ds->pbgy);
1238     draw_player(dr, ds, ds->pbgx, ds->pbgy, (state->dead && !oldstate));
1239     ds->player_bg_saved = TRUE;
1240 }
1241
1242 static float game_anim_length(game_state *oldstate, game_state *newstate,
1243                               int dir, game_ui *ui)
1244 {
1245     int dist;
1246     if (dir > 0)
1247         dist = newstate->distance_moved;
1248     else
1249         dist = oldstate->distance_moved;
1250     ui->anim_length = sqrt(dist) * BASE_ANIM_LENGTH;
1251     return ui->anim_length;
1252 }
1253
1254 static float game_flash_length(game_state *oldstate, game_state *newstate,
1255                                int dir, game_ui *ui)
1256 {
1257     if (!oldstate->dead && newstate->dead) {
1258         ui->flashtype = FLASH_DEAD;
1259         return FLASH_LENGTH;
1260     } else if (oldstate->gems && !newstate->gems) {
1261         ui->flashtype = FLASH_WIN;
1262         return FLASH_LENGTH;
1263     }
1264     return 0.0F;
1265 }
1266
1267 static int game_wants_statusbar(void)
1268 {
1269     return TRUE;
1270 }
1271
1272 static int game_timing_state(game_state *state, game_ui *ui)
1273 {
1274     return TRUE;
1275 }
1276
1277 static void game_print_size(game_params *params, float *x, float *y)
1278 {
1279 }
1280
1281 static void game_print(drawing *dr, game_state *state, int tilesize)
1282 {
1283 }
1284
1285 #ifdef COMBINED
1286 #define thegame inertia
1287 #endif
1288
1289 const struct game thegame = {
1290     "Inertia", "games.inertia",
1291     default_params,
1292     game_fetch_preset,
1293     decode_params,
1294     encode_params,
1295     free_params,
1296     dup_params,
1297     TRUE, game_configure, custom_params,
1298     validate_params,
1299     new_game_desc,
1300     validate_desc,
1301     new_game,
1302     dup_game,
1303     free_game,
1304     FALSE, solve_game,
1305     FALSE, game_text_format,
1306     new_ui,
1307     free_ui,
1308     encode_ui,
1309     decode_ui,
1310     game_changed_state,
1311     interpret_move,
1312     execute_move,
1313     PREFERRED_TILESIZE, game_compute_size, game_set_size,
1314     game_colours,
1315     game_new_drawstate,
1316     game_free_drawstate,
1317     game_redraw,
1318     game_anim_length,
1319     game_flash_length,
1320     FALSE, FALSE, game_print_size, game_print,
1321     game_wants_statusbar,
1322     FALSE, game_timing_state,
1323     0,                                 /* mouse_priorities */
1324 };