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