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