2 * mines.c: Minesweeper clone with sophisticated grid generation.
6 * - think about configurably supporting question marks. Once,
7 * that is, we've thought about configurability in general!
21 COL_BACKGROUND, COL_BACKGROUND2,
22 COL_1, COL_2, COL_3, COL_4, COL_5, COL_6, COL_7, COL_8,
23 COL_MINE, COL_BANG, COL_CROSS, COL_FLAG, COL_FLAGBASE, COL_QUERY,
24 COL_HIGHLIGHT, COL_LOWLIGHT,
29 #define BORDER (TILE_SIZE * 3 / 2)
30 #define HIGHLIGHT_WIDTH 2
31 #define OUTER_HIGHLIGHT_WIDTH 3
32 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
33 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
35 #define FLASH_FRAME 0.13F
44 * This structure is shared between all the game_states for a
45 * given instance of the puzzle, so we reference-count it.
50 * If we haven't yet actually generated the mine layout, here's
51 * all the data we will need to do so.
55 midend_data *me; /* to give back the new game desc */
59 int w, h, n, dead, won;
60 int used_solve, just_used_solve;
61 struct mine_layout *layout; /* real mine positions */
62 signed char *grid; /* player knowledge */
64 * Each item in the `grid' array is one of the following values:
66 * - 0 to 8 mean the square is open and has a surrounding mine
69 * - -1 means the square is marked as a mine.
71 * - -2 means the square is unknown.
73 * - -3 means the square is marked with a question mark
74 * (FIXME: do we even want to bother with this?).
76 * - 64 means the square has had a mine revealed when the game
79 * - 65 means the square had a mine revealed and this was the
80 * one the player hits.
82 * - 66 means the square has a crossed-out mine because the
83 * player had incorrectly marked it.
87 static game_params *default_params(void)
89 game_params *ret = snew(game_params);
98 static const struct game_params mines_presets[] = {
104 static int game_fetch_preset(int i, char **name, game_params **params)
109 if (i < 0 || i >= lenof(mines_presets))
112 ret = snew(game_params);
113 *ret = mines_presets[i];
115 sprintf(str, "%dx%d, %d mines", ret->w, ret->h, ret->n);
122 static void free_params(game_params *params)
127 static game_params *dup_params(game_params *params)
129 game_params *ret = snew(game_params);
130 *ret = *params; /* structure copy */
134 static void decode_params(game_params *params, char const *string)
136 char const *p = string;
139 while (*p && isdigit((unsigned char)*p)) p++;
143 while (*p && isdigit((unsigned char)*p)) p++;
145 params->h = params->w;
150 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
152 params->n = params->w * params->h / 10;
158 params->unique = FALSE;
160 p++; /* skip any other gunk */
164 static char *encode_params(game_params *params, int full)
169 len = sprintf(ret, "%dx%d", params->w, params->h);
171 * Mine count is a generation-time parameter, since it can be
172 * deduced from the mine bitmap!
175 len += sprintf(ret+len, "n%d", params->n);
176 if (full && !params->unique)
178 assert(len < lenof(ret));
184 static config_item *game_configure(game_params *params)
189 ret = snewn(5, config_item);
191 ret[0].name = "Width";
192 ret[0].type = C_STRING;
193 sprintf(buf, "%d", params->w);
194 ret[0].sval = dupstr(buf);
197 ret[1].name = "Height";
198 ret[1].type = C_STRING;
199 sprintf(buf, "%d", params->h);
200 ret[1].sval = dupstr(buf);
203 ret[2].name = "Mines";
204 ret[2].type = C_STRING;
205 sprintf(buf, "%d", params->n);
206 ret[2].sval = dupstr(buf);
209 ret[3].name = "Ensure solubility";
210 ret[3].type = C_BOOLEAN;
212 ret[3].ival = params->unique;
222 static game_params *custom_params(config_item *cfg)
224 game_params *ret = snew(game_params);
226 ret->w = atoi(cfg[0].sval);
227 ret->h = atoi(cfg[1].sval);
228 ret->n = atoi(cfg[2].sval);
229 if (strchr(cfg[2].sval, '%'))
230 ret->n = ret->n * (ret->w * ret->h) / 100;
231 ret->unique = cfg[3].ival;
236 static char *validate_params(game_params *params)
239 * Lower limit on grid size: each dimension must be at least 3.
240 * 1 is theoretically workable if rather boring, but 2 is a
241 * real problem: there is often _no_ way to generate a uniquely
242 * solvable 2xn Mines grid. You either run into two mines
243 * blocking the way and no idea what's behind them, or one mine
244 * and no way to know which of the two rows it's in. If the
245 * mine count is even you can create a soluble grid by packing
246 * all the mines at one end (so what when you hit a two-mine
247 * wall there are only as many covered squares left as there
248 * are mines); but if it's odd, you are doomed, because you
249 * _have_ to have a gap somewhere which you can't determine the
252 if (params->w <= 2 || params->h <= 2)
253 return "Width and height must both be greater than two";
254 if (params->n > params->w * params->h - 9)
255 return "Too many mines for grid size";
258 * FIXME: Need more constraints here. Not sure what the
259 * sensible limits for Minesweeper actually are. The limits
260 * probably ought to change, however, depending on uniqueness.
266 /* ----------------------------------------------------------------------
267 * Minesweeper solver, used to ensure the generated grids are
268 * solvable without having to take risks.
272 * Count the bits in a word. Only needs to cope with 16 bits.
274 static int bitcount16(int word)
276 word = ((word & 0xAAAA) >> 1) + (word & 0x5555);
277 word = ((word & 0xCCCC) >> 2) + (word & 0x3333);
278 word = ((word & 0xF0F0) >> 4) + (word & 0x0F0F);
279 word = ((word & 0xFF00) >> 8) + (word & 0x00FF);
285 * We use a tree234 to store a large number of small localised
286 * sets, each with a mine count. We also keep some of those sets
287 * linked together into a to-do list.
290 short x, y, mask, mines;
292 struct set *prev, *next;
295 static int setcmp(void *av, void *bv)
297 struct set *a = (struct set *)av;
298 struct set *b = (struct set *)bv;
302 else if (a->y > b->y)
304 else if (a->x < b->x)
306 else if (a->x > b->x)
308 else if (a->mask < b->mask)
310 else if (a->mask > b->mask)
318 struct set *todo_head, *todo_tail;
321 static struct setstore *ss_new(void)
323 struct setstore *ss = snew(struct setstore);
324 ss->sets = newtree234(setcmp);
325 ss->todo_head = ss->todo_tail = NULL;
330 * Take two input sets, in the form (x,y,mask). Munge the first by
331 * taking either its intersection with the second or its difference
332 * with the second. Return the new mask part of the first set.
334 static int setmunge(int x1, int y1, int mask1, int x2, int y2, int mask2,
338 * Adjust the second set so that it has the same x,y
339 * coordinates as the first.
341 if (abs(x2-x1) >= 3 || abs(y2-y1) >= 3) {
345 mask2 &= ~(4|32|256);
355 mask2 &= ~(64|128|256);
367 * Invert the second set if `diff' is set (we're after A &~ B
368 * rather than A & B).
374 * Now all that's left is a logical AND.
376 return mask1 & mask2;
379 static void ss_add_todo(struct setstore *ss, struct set *s)
382 return; /* already on it */
384 #ifdef SOLVER_DIAGNOSTICS
385 printf("adding set on todo list: %d,%d %03x %d\n",
386 s->x, s->y, s->mask, s->mines);
389 s->prev = ss->todo_tail;
399 static void ss_add(struct setstore *ss, int x, int y, int mask, int mines)
406 * Normalise so that x and y are genuinely the bounding
409 while (!(mask & (1|8|64)))
411 while (!(mask & (1|2|4)))
415 * Create a set structure and add it to the tree.
417 s = snew(struct set);
423 if (add234(ss->sets, s) != s) {
425 * This set already existed! Free it and return.
432 * We've added a new set to the tree, so put it on the todo
438 static void ss_remove(struct setstore *ss, struct set *s)
440 struct set *next = s->next, *prev = s->prev;
442 #ifdef SOLVER_DIAGNOSTICS
443 printf("removing set %d,%d %03x\n", s->x, s->y, s->mask);
446 * Remove s from the todo list.
450 else if (s == ss->todo_head)
451 ss->todo_head = next;
455 else if (s == ss->todo_tail)
456 ss->todo_tail = prev;
461 * Remove s from the tree.
466 * Destroy the actual set structure.
472 * Return a dynamically allocated list of all the sets which
473 * overlap a provided input set.
475 static struct set **ss_overlap(struct setstore *ss, int x, int y, int mask)
477 struct set **ret = NULL;
478 int nret = 0, retsize = 0;
481 for (xx = x-3; xx < x+3; xx++)
482 for (yy = y-3; yy < y+3; yy++) {
487 * Find the first set with these top left coordinates.
493 if (findrelpos234(ss->sets, &stmp, NULL, REL234_GE, &pos)) {
494 while ((s = index234(ss->sets, pos)) != NULL &&
495 s->x == xx && s->y == yy) {
497 * This set potentially overlaps the input one.
498 * Compute the intersection to see if they
499 * really overlap, and add it to the list if
502 if (setmunge(x, y, mask, s->x, s->y, s->mask, FALSE)) {
504 * There's an overlap.
506 if (nret >= retsize) {
508 ret = sresize(ret, retsize, struct set *);
518 ret = sresize(ret, nret+1, struct set *);
525 * Get an element from the head of the set todo list.
527 static struct set *ss_todo(struct setstore *ss)
530 struct set *ret = ss->todo_head;
531 ss->todo_head = ret->next;
533 ss->todo_head->prev = NULL;
535 ss->todo_tail = NULL;
536 ret->next = ret->prev = NULL;
549 static void std_add(struct squaretodo *std, int i)
552 std->next[std->tail] = i;
559 typedef int (*open_cb)(void *, int, int);
561 static void known_squares(int w, int h, struct squaretodo *std,
563 open_cb open, void *openctx,
564 int x, int y, int mask, int mine)
570 for (yy = 0; yy < 3; yy++)
571 for (xx = 0; xx < 3; xx++) {
573 int i = (y + yy) * w + (x + xx);
576 * It's possible that this square is _already_
577 * known, in which case we don't try to add it to
583 grid[i] = -1; /* and don't open it! */
585 grid[i] = open(openctx, x + xx, y + yy);
586 assert(grid[i] != -1); /* *bang* */
597 * This is data returned from the `perturb' function. It details
598 * which squares have become mines and which have become clear. The
599 * solver is (of course) expected to honourably not use that
600 * knowledge directly, but to efficently adjust its internal data
601 * structures and proceed based on only the information it
604 struct perturbation {
606 int delta; /* +1 == become a mine; -1 == cleared */
608 struct perturbations {
610 struct perturbation *changes;
614 * Main solver entry point. You give it a grid of existing
615 * knowledge (-1 for a square known to be a mine, 0-8 for empty
616 * squares with a given number of neighbours, -2 for completely
617 * unknown), plus a function which you can call to open new squares
618 * once you're confident of them. It fills in as much more of the
623 * - -1 means deduction stalled and nothing could be done
624 * - 0 means deduction succeeded fully
625 * - >0 means deduction succeeded but some number of perturbation
626 * steps were required; the exact return value is the number of
630 typedef struct perturbations *(*perturb_cb) (void *, signed char *, int, int, int);
632 static int minesolve(int w, int h, int n, signed char *grid,
635 void *ctx, random_state *rs)
637 struct setstore *ss = ss_new();
639 struct squaretodo astd, *std = &astd;
644 * Set up a linked list of squares with known contents, so that
645 * we can process them one by one.
647 std->next = snewn(w*h, int);
648 std->head = std->tail = -1;
651 * Initialise that list with all known squares in the input
654 for (y = 0; y < h; y++) {
655 for (x = 0; x < w; x++) {
663 * Main deductive loop.
666 int done_something = FALSE;
670 * If there are any known squares on the todo list, process
671 * them and construct a set for each.
673 while (std->head != -1) {
675 #ifdef SOLVER_DIAGNOSTICS
676 printf("known square at %d,%d [%d]\n", i%w, i/w, grid[i]);
678 std->head = std->next[i];
686 int dx, dy, mines, bit, val;
687 #ifdef SOLVER_DIAGNOSTICS
688 printf("creating set around this square\n");
691 * Empty square. Construct the set of non-known squares
692 * around this one, and determine its mine count.
697 for (dy = -1; dy <= +1; dy++) {
698 for (dx = -1; dx <= +1; dx++) {
699 #ifdef SOLVER_DIAGNOSTICS
700 printf("grid %d,%d = %d\n", x+dx, y+dy, grid[i+dy*w+dx]);
702 if (x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= h)
703 /* ignore this one */;
704 else if (grid[i+dy*w+dx] == -1)
706 else if (grid[i+dy*w+dx] == -2)
712 ss_add(ss, x-1, y-1, val, mines);
716 * Now, whether the square is empty or full, we must
717 * find any set which contains it and replace it with
718 * one which does not.
721 #ifdef SOLVER_DIAGNOSTICS
722 printf("finding sets containing known square %d,%d\n", x, y);
724 list = ss_overlap(ss, x, y, 1);
726 for (j = 0; list[j]; j++) {
727 int newmask, newmines;
732 * Compute the mask for this set minus the
733 * newly known square.
735 newmask = setmunge(s->x, s->y, s->mask, x, y, 1, TRUE);
738 * Compute the new mine count.
740 newmines = s->mines - (grid[i] == -1);
743 * Insert the new set into the collection,
744 * unless it's been whittled right down to
748 ss_add(ss, s->x, s->y, newmask, newmines);
751 * Destroy the old one; it is actually obsolete.
760 * Marking a fresh square as known certainly counts as
763 done_something = TRUE;
767 * Now pick a set off the to-do list and attempt deductions
770 if ((s = ss_todo(ss)) != NULL) {
772 #ifdef SOLVER_DIAGNOSTICS
773 printf("set to do: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
776 * Firstly, see if this set has a mine count of zero or
777 * of its own cardinality.
779 if (s->mines == 0 || s->mines == bitcount16(s->mask)) {
781 * If so, we can immediately mark all the squares
782 * in the set as known.
784 #ifdef SOLVER_DIAGNOSTICS
787 known_squares(w, h, std, grid, open, ctx,
788 s->x, s->y, s->mask, (s->mines != 0));
791 * Having done that, we need do nothing further
792 * with this set; marking all the squares in it as
793 * known will eventually eliminate it, and will
794 * also permit further deductions about anything
801 * Failing that, we now search through all the sets
802 * which overlap this one.
804 list = ss_overlap(ss, s->x, s->y, s->mask);
806 for (j = 0; list[j]; j++) {
807 struct set *s2 = list[j];
808 int swing, s2wing, swc, s2wc;
811 * Find the non-overlapping parts s2-s and s-s2,
812 * and their cardinalities.
814 * I'm going to refer to these parts as `wings'
815 * surrounding the central part common to both
816 * sets. The `s wing' is s-s2; the `s2 wing' is
819 swing = setmunge(s->x, s->y, s->mask, s2->x, s2->y, s2->mask,
821 s2wing = setmunge(s2->x, s2->y, s2->mask, s->x, s->y, s->mask,
823 swc = bitcount16(swing);
824 s2wc = bitcount16(s2wing);
827 * If one set has more mines than the other, and
828 * the number of extra mines is equal to the
829 * cardinality of that set's wing, then we can mark
830 * every square in the wing as a known mine, and
831 * every square in the other wing as known clear.
833 if (swc == s->mines - s2->mines ||
834 s2wc == s2->mines - s->mines) {
835 known_squares(w, h, std, grid, open, ctx,
837 (swc == s->mines - s2->mines));
838 known_squares(w, h, std, grid, open, ctx,
839 s2->x, s2->y, s2wing,
840 (s2wc == s2->mines - s->mines));
845 * Failing that, see if one set is a subset of the
846 * other. If so, we can divide up the mine count of
847 * the larger set between the smaller set and its
848 * complement, even if neither smaller set ends up
849 * being immediately clearable.
851 if (swc == 0 && s2wc != 0) {
852 /* s is a subset of s2. */
853 assert(s2->mines > s->mines);
854 ss_add(ss, s2->x, s2->y, s2wing, s2->mines - s->mines);
855 } else if (s2wc == 0 && swc != 0) {
856 /* s2 is a subset of s. */
857 assert(s->mines > s2->mines);
858 ss_add(ss, s->x, s->y, swing, s->mines - s2->mines);
865 * In this situation we have definitely done
866 * _something_, even if it's only reducing the size of
869 done_something = TRUE;
872 * We have nothing left on our todo list, which means
873 * all localised deductions have failed. Our next step
874 * is to resort to global deduction based on the total
875 * mine count. This is computationally expensive
876 * compared to any of the above deductions, which is
877 * why we only ever do it when all else fails, so that
878 * hopefully it won't have to happen too often.
880 * If you pass n<0 into this solver, that informs it
881 * that you do not know the total mine count, so it
882 * won't even attempt these deductions.
885 int minesleft, squaresleft;
886 int nsets, setused[10], cursor;
889 * Start by scanning the current grid state to work out
890 * how many unknown squares we still have, and how many
891 * mines are to be placed in them.
895 for (i = 0; i < w*h; i++) {
898 else if (grid[i] == -2)
902 #ifdef SOLVER_DIAGNOSTICS
903 printf("global deduction time: squaresleft=%d minesleft=%d\n",
904 squaresleft, minesleft);
905 for (y = 0; y < h; y++) {
906 for (x = 0; x < w; x++) {
922 * If there _are_ no unknown squares, we have actually
925 if (squaresleft == 0) {
926 assert(minesleft == 0);
931 * First really simple case: if there are no more mines
932 * left, or if there are exactly as many mines left as
933 * squares to play them in, then it's all easy.
935 if (minesleft == 0 || minesleft == squaresleft) {
936 for (i = 0; i < w*h; i++)
938 known_squares(w, h, std, grid, open, ctx,
939 i % w, i / w, 1, minesleft != 0);
940 continue; /* now go back to main deductive loop */
944 * Failing that, we have to do some _real_ work.
945 * Ideally what we do here is to try every single
946 * combination of the currently available sets, in an
947 * attempt to find a disjoint union (i.e. a set of
948 * squares with a known mine count between them) such
949 * that the remaining unknown squares _not_ contained
950 * in that union either contain no mines or are all
953 * Actually enumerating all 2^n possibilities will get
954 * a bit slow for large n, so I artificially cap this
955 * recursion at n=10 to avoid too much pain.
957 nsets = count234(ss->sets);
958 if (nsets <= lenof(setused)) {
960 * Doing this with actual recursive function calls
961 * would get fiddly because a load of local
962 * variables from this function would have to be
963 * passed down through the recursion. So instead
964 * I'm going to use a virtual recursion within this
965 * function. The way this works is:
967 * - we have an array `setused', such that
968 * setused[n] is 0 or 1 depending on whether set
969 * n is currently in the union we are
972 * - we have a value `cursor' which indicates how
973 * much of `setused' we have so far filled in.
974 * It's conceptually the recursion depth.
976 * We begin by setting `cursor' to zero. Then:
978 * - if cursor can advance, we advance it by one.
979 * We set the value in `setused' that it went
980 * past to 1 if that set is disjoint from
981 * anything else currently in `setused', or to 0
984 * - If cursor cannot advance because it has
985 * reached the end of the setused list, then we
986 * have a maximal disjoint union. Check to see
987 * whether its mine count has any useful
988 * properties. If so, mark all the squares not
989 * in the union as known and terminate.
991 * - If cursor has reached the end of setused and
992 * the algorithm _hasn't_ terminated, back
993 * cursor up to the nearest 1, turn it into a 0
994 * and advance cursor just past it.
996 * - If we attempt to back up to the nearest 1 and
997 * there isn't one at all, then we have gone
998 * through all disjoint unions of sets in the
999 * list and none of them has been helpful, so we
1002 struct set *sets[lenof(setused)];
1003 for (i = 0; i < nsets; i++)
1004 sets[i] = index234(ss->sets, i);
1009 if (cursor < nsets) {
1012 /* See if any existing set overlaps this one. */
1013 for (i = 0; i < cursor; i++)
1015 setmunge(sets[cursor]->x,
1018 sets[i]->x, sets[i]->y, sets[i]->mask,
1026 * We're adding this set to our union,
1027 * so adjust minesleft and squaresleft
1030 minesleft -= sets[cursor]->mines;
1031 squaresleft -= bitcount16(sets[cursor]->mask);
1034 setused[cursor++] = ok;
1036 #ifdef SOLVER_DIAGNOSTICS
1037 printf("trying a set combination with %d %d\n",
1038 squaresleft, minesleft);
1039 #endif /* SOLVER_DIAGNOSTICS */
1042 * We've reached the end. See if we've got
1043 * anything interesting.
1045 if (squaresleft > 0 &&
1046 (minesleft == 0 || minesleft == squaresleft)) {
1048 * We have! There is at least one
1049 * square not contained within the set
1050 * union we've just found, and we can
1051 * deduce that either all such squares
1052 * are mines or all are not (depending
1053 * on whether minesleft==0). So now all
1054 * we have to do is actually go through
1055 * the grid, find those squares, and
1058 for (i = 0; i < w*h; i++)
1059 if (grid[i] == -2) {
1063 for (j = 0; j < nsets; j++)
1065 setmunge(sets[j]->x, sets[j]->y,
1066 sets[j]->mask, x, y, 1,
1072 known_squares(w, h, std, grid,
1074 x, y, 1, minesleft != 0);
1077 done_something = TRUE;
1078 break; /* return to main deductive loop */
1082 * If we reach here, then this union hasn't
1083 * done us any good, so move on to the
1084 * next. Backtrack cursor to the nearest 1,
1085 * change it to a 0 and continue.
1087 while (--cursor >= 0 && !setused[cursor]);
1089 assert(setused[cursor]);
1092 * We're removing this set from our
1093 * union, so re-increment minesleft and
1096 minesleft += sets[cursor]->mines;
1097 squaresleft += bitcount16(sets[cursor]->mask);
1099 setused[cursor++] = 0;
1102 * We've backtracked all the way to the
1103 * start without finding a single 1,
1104 * which means that our virtual
1105 * recursion is complete and nothing
1120 #ifdef SOLVER_DIAGNOSTICS
1122 * Dump the current known state of the grid.
1124 printf("solver ran out of steam, ret=%d, grid:\n", nperturbs);
1125 for (y = 0; y < h; y++) {
1126 for (x = 0; x < w; x++) {
1127 int v = grid[y*w+x];
1143 for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1144 printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1149 * Now we really are at our wits' end as far as solving
1150 * this grid goes. Our only remaining option is to call
1151 * a perturb function and ask it to modify the grid to
1155 struct perturbations *ret;
1161 * Choose a set at random from the current selection,
1162 * and ask the perturb function to either fill or empty
1165 * If we have no sets at all, we must give up.
1167 if (count234(ss->sets) == 0) {
1168 #ifdef SOLVER_DIAGNOSTICS
1169 printf("perturbing on entire unknown set\n");
1171 ret = perturb(ctx, grid, 0, 0, 0);
1173 s = index234(ss->sets, random_upto(rs, count234(ss->sets)));
1174 #ifdef SOLVER_DIAGNOSTICS
1175 printf("perturbing on set %d,%d %03x\n", s->x, s->y, s->mask);
1177 ret = perturb(ctx, grid, s->x, s->y, s->mask);
1181 assert(ret->n > 0); /* otherwise should have been NULL */
1184 * A number of squares have been fiddled with, and
1185 * the returned structure tells us which. Adjust
1186 * the mine count in any set which overlaps one of
1187 * those squares, and put them back on the to-do
1188 * list. Also, if the square itself is marked as a
1189 * known non-mine, put it back on the squares-to-do
1192 for (i = 0; i < ret->n; i++) {
1193 #ifdef SOLVER_DIAGNOSTICS
1194 printf("perturbation %s mine at %d,%d\n",
1195 ret->changes[i].delta > 0 ? "added" : "removed",
1196 ret->changes[i].x, ret->changes[i].y);
1199 if (ret->changes[i].delta < 0 &&
1200 grid[ret->changes[i].y*w+ret->changes[i].x] != -2) {
1201 std_add(std, ret->changes[i].y*w+ret->changes[i].x);
1204 list = ss_overlap(ss,
1205 ret->changes[i].x, ret->changes[i].y, 1);
1207 for (j = 0; list[j]; j++) {
1208 list[j]->mines += ret->changes[i].delta;
1209 ss_add_todo(ss, list[j]);
1216 * Now free the returned data.
1218 sfree(ret->changes);
1221 #ifdef SOLVER_DIAGNOSTICS
1223 * Dump the current known state of the grid.
1225 printf("state after perturbation:\n");
1226 for (y = 0; y < h; y++) {
1227 for (x = 0; x < w; x++) {
1228 int v = grid[y*w+x];
1244 for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1245 printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1250 * And now we can go back round the deductive loop.
1257 * If we get here, even that didn't work (either we didn't
1258 * have a perturb function or it returned failure), so we
1265 * See if we've got any unknown squares left.
1267 for (y = 0; y < h; y++)
1268 for (x = 0; x < w; x++)
1269 if (grid[y*w+x] == -2) {
1270 nperturbs = -1; /* failed to complete */
1275 * Free the set list and square-todo list.
1279 while ((s = delpos234(ss->sets, 0)) != NULL)
1281 freetree234(ss->sets);
1289 /* ----------------------------------------------------------------------
1290 * Grid generator which uses the above solver.
1297 int allow_big_perturbs;
1301 static int mineopen(void *vctx, int x, int y)
1303 struct minectx *ctx = (struct minectx *)vctx;
1306 assert(x >= 0 && x < ctx->w && y >= 0 && y < ctx->h);
1307 if (ctx->grid[y * ctx->w + x])
1308 return -1; /* *bang* */
1311 for (i = -1; i <= +1; i++) {
1312 if (x + i < 0 || x + i >= ctx->w)
1314 for (j = -1; j <= +1; j++) {
1315 if (y + j < 0 || y + j >= ctx->h)
1317 if (i == 0 && j == 0)
1319 if (ctx->grid[(y+j) * ctx->w + (x+i)])
1327 /* Structure used internally to mineperturb(). */
1329 int x, y, type, random;
1331 static int squarecmp(const void *av, const void *bv)
1333 const struct square *a = (const struct square *)av;
1334 const struct square *b = (const struct square *)bv;
1335 if (a->type < b->type)
1337 else if (a->type > b->type)
1339 else if (a->random < b->random)
1341 else if (a->random > b->random)
1343 else if (a->y < b->y)
1345 else if (a->y > b->y)
1347 else if (a->x < b->x)
1349 else if (a->x > b->x)
1355 * Normally this function is passed an (x,y,mask) set description.
1356 * On occasions, though, there is no _localised_ set being used,
1357 * and the set being perturbed is supposed to be the entirety of
1358 * the unreachable area. This is signified by the special case
1359 * mask==0: in this case, anything labelled -2 in the grid is part
1362 * Allowing perturbation in this special case appears to make it
1363 * guaranteeably possible to generate a workable grid for any mine
1364 * density, but they tend to be a bit boring, with mines packed
1365 * densely into far corners of the grid and the remainder being
1366 * less dense than one might like. Therefore, to improve overall
1367 * grid quality I disable this feature for the first few attempts,
1368 * and fall back to it after no useful grid has been generated.
1370 static struct perturbations *mineperturb(void *vctx, signed char *grid,
1371 int setx, int sety, int mask)
1373 struct minectx *ctx = (struct minectx *)vctx;
1374 struct square *sqlist;
1375 int x, y, dx, dy, i, n, nfull, nempty;
1376 struct square **tofill, **toempty, **todo;
1377 int ntofill, ntoempty, ntodo, dtodo, dset;
1378 struct perturbations *ret;
1381 if (!mask && !ctx->allow_big_perturbs)
1385 * Make a list of all the squares in the grid which we can
1386 * possibly use. This list should be in preference order, which
1389 * - first, unknown squares on the boundary of known space
1390 * - next, unknown squares beyond that boundary
1391 * - as a very last resort, known squares, but not within one
1392 * square of the starting position.
1394 * Each of these sections needs to be shuffled independently.
1395 * We do this by preparing list of all squares and then sorting
1396 * it with a random secondary key.
1398 sqlist = snewn(ctx->w * ctx->h, struct square);
1400 for (y = 0; y < ctx->h; y++)
1401 for (x = 0; x < ctx->w; x++) {
1403 * If this square is too near the starting position,
1404 * don't put it on the list at all.
1406 if (abs(y - ctx->sy) <= 1 && abs(x - ctx->sx) <= 1)
1410 * If this square is in the input set, also don't put
1413 if ((mask == 0 && grid[y*ctx->w+x] == -2) ||
1414 (x >= setx && x < setx + 3 &&
1415 y >= sety && y < sety + 3 &&
1416 mask & (1 << ((y-sety)*3+(x-setx)))))
1422 if (grid[y*ctx->w+x] != -2) {
1423 sqlist[n].type = 3; /* known square */
1426 * Unknown square. Examine everything around it and
1427 * see if it borders on any known squares. If it
1428 * does, it's class 1, otherwise it's 2.
1433 for (dy = -1; dy <= +1; dy++)
1434 for (dx = -1; dx <= +1; dx++)
1435 if (x+dx >= 0 && x+dx < ctx->w &&
1436 y+dy >= 0 && y+dy < ctx->h &&
1437 grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1444 * Finally, a random number to cause qsort to
1445 * shuffle within each group.
1447 sqlist[n].random = random_bits(ctx->rs, 31);
1452 qsort(sqlist, n, sizeof(struct square), squarecmp);
1455 * Now count up the number of full and empty squares in the set
1456 * we've been provided.
1460 for (dy = 0; dy < 3; dy++)
1461 for (dx = 0; dx < 3; dx++)
1462 if (mask & (1 << (dy*3+dx))) {
1463 assert(setx+dx <= ctx->w);
1464 assert(sety+dy <= ctx->h);
1465 if (ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1471 for (y = 0; y < ctx->h; y++)
1472 for (x = 0; x < ctx->w; x++)
1473 if (grid[y*ctx->w+x] == -2) {
1474 if (ctx->grid[y*ctx->w+x])
1482 * Now go through our sorted list until we find either `nfull'
1483 * empty squares, or `nempty' full squares; these will be
1484 * swapped with the appropriate squares in the set to either
1485 * fill or empty the set while keeping the same number of mines
1488 ntofill = ntoempty = 0;
1490 tofill = snewn(9, struct square *);
1491 toempty = snewn(9, struct square *);
1493 tofill = snewn(ctx->w * ctx->h, struct square *);
1494 toempty = snewn(ctx->w * ctx->h, struct square *);
1496 for (i = 0; i < n; i++) {
1497 struct square *sq = &sqlist[i];
1498 if (ctx->grid[sq->y * ctx->w + sq->x])
1499 toempty[ntoempty++] = sq;
1501 tofill[ntofill++] = sq;
1502 if (ntofill == nfull || ntoempty == nempty)
1507 * If we haven't found enough empty squares outside the set to
1508 * empty it into _or_ enough full squares outside it to fill it
1509 * up with, we'll have to settle for doing only a partial job.
1510 * In this case we choose to always _fill_ the set (because
1511 * this case will tend to crop up when we're working with very
1512 * high mine densities and the only way to get a solvable grid
1513 * is going to be to pack most of the mines solidly around the
1514 * edges). So now our job is to make a list of the empty
1515 * squares in the set, and shuffle that list so that we fill a
1516 * random selection of them.
1518 if (ntofill != nfull && ntoempty != nempty) {
1521 assert(ntoempty != 0);
1523 setlist = snewn(ctx->w * ctx->h, int);
1526 for (dy = 0; dy < 3; dy++)
1527 for (dx = 0; dx < 3; dx++)
1528 if (mask & (1 << (dy*3+dx))) {
1529 assert(setx+dx <= ctx->w);
1530 assert(sety+dy <= ctx->h);
1531 if (!ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1532 setlist[i++] = (sety+dy)*ctx->w+(setx+dx);
1535 for (y = 0; y < ctx->h; y++)
1536 for (x = 0; x < ctx->w; x++)
1537 if (grid[y*ctx->w+x] == -2) {
1538 if (!ctx->grid[y*ctx->w+x])
1539 setlist[i++] = y*ctx->w+x;
1542 assert(i > ntoempty);
1544 * Now pick `ntoempty' items at random from the list.
1546 for (k = 0; k < ntoempty; k++) {
1547 int index = k + random_upto(ctx->rs, i - k);
1551 setlist[k] = setlist[index];
1552 setlist[index] = tmp;
1558 * Now we're pretty much there. We need to either
1559 * (a) put a mine in each of the empty squares in the set, and
1560 * take one out of each square in `toempty'
1561 * (b) take a mine out of each of the full squares in the set,
1562 * and put one in each square in `tofill'
1563 * depending on which one we've found enough squares to do.
1565 * So we start by constructing our list of changes to return to
1566 * the solver, so that it can update its data structures
1567 * efficiently rather than having to rescan the whole grid.
1569 ret = snew(struct perturbations);
1570 if (ntofill == nfull) {
1578 * (We also fall into this case if we've constructed a
1588 ret->changes = snewn(ret->n, struct perturbation);
1589 for (i = 0; i < ntodo; i++) {
1590 ret->changes[i].x = todo[i]->x;
1591 ret->changes[i].y = todo[i]->y;
1592 ret->changes[i].delta = dtodo;
1594 /* now i == ntodo */
1597 assert(todo == toempty);
1598 for (j = 0; j < ntoempty; j++) {
1599 ret->changes[i].x = setlist[j] % ctx->w;
1600 ret->changes[i].y = setlist[j] / ctx->w;
1601 ret->changes[i].delta = dset;
1606 for (dy = 0; dy < 3; dy++)
1607 for (dx = 0; dx < 3; dx++)
1608 if (mask & (1 << (dy*3+dx))) {
1609 int currval = (ctx->grid[(sety+dy)*ctx->w+(setx+dx)] ? +1 : -1);
1610 if (dset == -currval) {
1611 ret->changes[i].x = setx + dx;
1612 ret->changes[i].y = sety + dy;
1613 ret->changes[i].delta = dset;
1618 for (y = 0; y < ctx->h; y++)
1619 for (x = 0; x < ctx->w; x++)
1620 if (grid[y*ctx->w+x] == -2) {
1621 int currval = (ctx->grid[y*ctx->w+x] ? +1 : -1);
1622 if (dset == -currval) {
1623 ret->changes[i].x = x;
1624 ret->changes[i].y = y;
1625 ret->changes[i].delta = dset;
1630 assert(i == ret->n);
1636 * Having set up the precise list of changes we're going to
1637 * make, we now simply make them and return.
1639 for (i = 0; i < ret->n; i++) {
1642 x = ret->changes[i].x;
1643 y = ret->changes[i].y;
1644 delta = ret->changes[i].delta;
1647 * Check we're not trying to add an existing mine or remove
1650 assert((delta < 0) ^ (ctx->grid[y*ctx->w+x] == 0));
1653 * Actually make the change.
1655 ctx->grid[y*ctx->w+x] = (delta > 0);
1658 * Update any numbers already present in the grid.
1660 for (dy = -1; dy <= +1; dy++)
1661 for (dx = -1; dx <= +1; dx++)
1662 if (x+dx >= 0 && x+dx < ctx->w &&
1663 y+dy >= 0 && y+dy < ctx->h &&
1664 grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1665 if (dx == 0 && dy == 0) {
1667 * The square itself is marked as known in
1668 * the grid. Mark it as a mine if it's a
1669 * mine, or else work out its number.
1672 grid[y*ctx->w+x] = -1;
1674 int dx2, dy2, minecount = 0;
1675 for (dy2 = -1; dy2 <= +1; dy2++)
1676 for (dx2 = -1; dx2 <= +1; dx2++)
1677 if (x+dx2 >= 0 && x+dx2 < ctx->w &&
1678 y+dy2 >= 0 && y+dy2 < ctx->h &&
1679 ctx->grid[(y+dy2)*ctx->w+(x+dx2)])
1681 grid[y*ctx->w+x] = minecount;
1684 if (grid[(y+dy)*ctx->w+(x+dx)] >= 0)
1685 grid[(y+dy)*ctx->w+(x+dx)] += delta;
1690 #ifdef GENERATION_DIAGNOSTICS
1693 printf("grid after perturbing:\n");
1694 for (yy = 0; yy < ctx->h; yy++) {
1695 for (xx = 0; xx < ctx->w; xx++) {
1696 int v = ctx->grid[yy*ctx->w+xx];
1697 if (yy == ctx->sy && xx == ctx->sx) {
1715 static char *minegen(int w, int h, int n, int x, int y, int unique,
1718 char *ret = snewn(w*h, char);
1726 memset(ret, 0, w*h);
1729 * Start by placing n mines, none of which is at x,y or within
1733 int *tmp = snewn(w*h, int);
1737 * Write down the list of possible mine locations.
1740 for (i = 0; i < h; i++)
1741 for (j = 0; j < w; j++)
1742 if (abs(i - y) > 1 || abs(j - x) > 1)
1746 * Now pick n off the list at random.
1750 i = random_upto(rs, k);
1758 #ifdef GENERATION_DIAGNOSTICS
1761 printf("grid after initial generation:\n");
1762 for (yy = 0; yy < h; yy++) {
1763 for (xx = 0; xx < w; xx++) {
1764 int v = ret[yy*w+xx];
1765 if (yy == y && xx == x) {
1781 * Now set up a results grid to run the solver in, and a
1782 * context for the solver to open squares. Then run the solver
1783 * repeatedly; if the number of perturb steps ever goes up or
1784 * it ever returns -1, give up completely.
1786 * We bypass this bit if we're not after a unique grid.
1789 signed char *solvegrid = snewn(w*h, char);
1790 struct minectx actx, *ctx = &actx;
1791 int solveret, prevret = -2;
1799 ctx->allow_big_perturbs = (ntries > 100);
1802 memset(solvegrid, -2, w*h);
1803 solvegrid[y*w+x] = mineopen(ctx, x, y);
1804 assert(solvegrid[y*w+x] == 0); /* by deliberate arrangement */
1807 minesolve(w, h, n, solvegrid, mineopen, mineperturb, ctx, rs);
1808 if (solveret < 0 || (prevret >= 0 && solveret >= prevret)) {
1811 } else if (solveret == 0) {
1828 * The Mines game descriptions contain the location of every mine,
1829 * and can therefore be used to cheat.
1831 * It would be pointless to attempt to _prevent_ this form of
1832 * cheating by encrypting the description, since Mines is
1833 * open-source so anyone can find out the encryption key. However,
1834 * I think it is worth doing a bit of gentle obfuscation to prevent
1835 * _accidental_ spoilers: if you happened to note that the game ID
1836 * starts with an F, for example, you might be unable to put the
1837 * knowledge of those mines out of your mind while playing. So,
1838 * just as discussions of film endings are rot13ed to avoid
1839 * spoiling it for people who don't want to be told, we apply a
1840 * keyless, reversible, but visually completely obfuscatory masking
1841 * function to the mine bitmap.
1843 static void obfuscate_bitmap(unsigned char *bmp, int bits, int decode)
1845 int bytes, firsthalf, secondhalf;
1847 unsigned char *seedstart;
1849 unsigned char *targetstart;
1855 * My obfuscation algorithm is similar in concept to the OAEP
1856 * encoding used in some forms of RSA. Here's a specification
1859 * + We have a `masking function' which constructs a stream of
1860 * pseudorandom bytes from a seed of some number of input
1863 * + We pad out our input bit stream to a whole number of
1864 * bytes by adding up to 7 zero bits on the end. (In fact
1865 * the bitmap passed as input to this function will already
1866 * have had this done in practice.)
1868 * + We divide the _byte_ stream exactly in half, rounding the
1869 * half-way position _down_. So an 81-bit input string, for
1870 * example, rounds up to 88 bits or 11 bytes, and then
1871 * dividing by two gives 5 bytes in the first half and 6 in
1874 * + We generate a mask from the second half of the bytes, and
1875 * XOR it over the first half.
1877 * + We generate a mask from the (encoded) first half of the
1878 * bytes, and XOR it over the second half. Any null bits at
1879 * the end which were added as padding are cleared back to
1880 * zero even if this operation would have made them nonzero.
1882 * To de-obfuscate, the steps are precisely the same except
1883 * that the final two are reversed.
1885 * Finally, our masking function. Given an input seed string of
1886 * bytes, the output mask consists of concatenating the SHA-1
1887 * hashes of the seed string and successive decimal integers,
1891 bytes = (bits + 7) / 8;
1892 firsthalf = bytes / 2;
1893 secondhalf = bytes - firsthalf;
1895 steps[decode ? 1 : 0].seedstart = bmp + firsthalf;
1896 steps[decode ? 1 : 0].seedlen = secondhalf;
1897 steps[decode ? 1 : 0].targetstart = bmp;
1898 steps[decode ? 1 : 0].targetlen = firsthalf;
1900 steps[decode ? 0 : 1].seedstart = bmp;
1901 steps[decode ? 0 : 1].seedlen = firsthalf;
1902 steps[decode ? 0 : 1].targetstart = bmp + firsthalf;
1903 steps[decode ? 0 : 1].targetlen = secondhalf;
1905 for (i = 0; i < 2; i++) {
1906 SHA_State base, final;
1907 unsigned char digest[20];
1909 int digestpos = 20, counter = 0;
1912 SHA_Bytes(&base, steps[i].seedstart, steps[i].seedlen);
1914 for (j = 0; j < steps[i].targetlen; j++) {
1915 if (digestpos >= 20) {
1916 sprintf(numberbuf, "%d", counter++);
1918 SHA_Bytes(&final, numberbuf, strlen(numberbuf));
1919 SHA_Final(&final, digest);
1922 steps[i].targetstart[j] ^= digest[digestpos++];
1926 * Mask off the pad bits in the final byte after both steps.
1929 bmp[bits / 8] &= 0xFF & (0xFF00 >> (bits % 8));
1933 static char *new_mine_layout(int w, int h, int n, int x, int y, int unique,
1934 random_state *rs, char **game_desc)
1936 signed char *grid, *ret, *p;
1940 #ifdef TEST_OBFUSCATION
1941 static int tested_obfuscation = FALSE;
1942 if (!tested_obfuscation) {
1944 * A few simple test vectors for the obfuscator.
1946 * First test: the 28-bit stream 1234567. This divides up
1947 * into 1234 and 567[0]. The SHA of 56 70 30 (appending
1948 * "0") is 15ce8ab946640340bbb99f3f48fd2c45d1a31d30. Thus,
1949 * we XOR the 16-bit string 15CE into the input 1234 to get
1950 * 07FA. Next, we SHA that with "0": the SHA of 07 FA 30 is
1951 * 3370135c5e3da4fed937adc004a79533962b6391. So we XOR the
1952 * 12-bit string 337 into the input 567 to get 650. Thus
1953 * our output is 07FA650.
1956 unsigned char bmp1[] = "\x12\x34\x56\x70";
1957 obfuscate_bitmap(bmp1, 28, FALSE);
1958 printf("test 1 encode: %s\n",
1959 memcmp(bmp1, "\x07\xfa\x65\x00", 4) ? "failed" : "passed");
1960 obfuscate_bitmap(bmp1, 28, TRUE);
1961 printf("test 1 decode: %s\n",
1962 memcmp(bmp1, "\x12\x34\x56\x70", 4) ? "failed" : "passed");
1965 * Second test: a long string to make sure we switch from
1966 * one SHA to the next correctly. My input string this time
1967 * is simply fifty bytes of zeroes.
1970 unsigned char bmp2[50];
1971 unsigned char bmp2a[50];
1972 memset(bmp2, 0, 50);
1973 memset(bmp2a, 0, 50);
1974 obfuscate_bitmap(bmp2, 50 * 8, FALSE);
1976 * SHA of twenty-five zero bytes plus "0" is
1977 * b202c07b990c01f6ff2d544707f60e506019b671. SHA of
1978 * twenty-five zero bytes plus "1" is
1979 * fcb1d8b5a2f6b592fe6780b36aa9d65dd7aa6db9. Thus our
1980 * first half becomes
1981 * b202c07b990c01f6ff2d544707f60e506019b671fcb1d8b5a2.
1983 * SHA of that lot plus "0" is
1984 * 10b0af913db85d37ca27f52a9f78bba3a80030db. SHA of the
1985 * same string plus "1" is
1986 * 3d01d8df78e76d382b8106f480135a1bc751d725. So the
1987 * second half becomes
1988 * 10b0af913db85d37ca27f52a9f78bba3a80030db3d01d8df78.
1990 printf("test 2 encode: %s\n",
1991 memcmp(bmp2, "\xb2\x02\xc0\x7b\x99\x0c\x01\xf6\xff\x2d\x54"
1992 "\x47\x07\xf6\x0e\x50\x60\x19\xb6\x71\xfc\xb1\xd8"
1993 "\xb5\xa2\x10\xb0\xaf\x91\x3d\xb8\x5d\x37\xca\x27"
1994 "\xf5\x2a\x9f\x78\xbb\xa3\xa8\x00\x30\xdb\x3d\x01"
1995 "\xd8\xdf\x78", 50) ? "failed" : "passed");
1996 obfuscate_bitmap(bmp2, 50 * 8, TRUE);
1997 printf("test 2 decode: %s\n",
1998 memcmp(bmp2, bmp2a, 50) ? "failed" : "passed");
2003 grid = minegen(w, h, n, x, y, unique, rs);
2007 * Set up the mine bitmap and obfuscate it.
2010 bmp = snewn((area + 7) / 8, unsigned char);
2011 memset(bmp, 0, (area + 7) / 8);
2012 for (i = 0; i < area; i++) {
2014 bmp[i / 8] |= 0x80 >> (i % 8);
2016 obfuscate_bitmap(bmp, area, FALSE);
2019 * Now encode the resulting bitmap in hex. We can work to
2020 * nibble rather than byte granularity, since the obfuscation
2021 * function guarantees to return a bit string of the same
2022 * length as its input.
2024 ret = snewn((area+3)/4 + 100, char);
2025 p = ret + sprintf(ret, "%d,%d,m", x, y); /* 'm' == masked */
2026 for (i = 0; i < (area+3)/4; i++) {
2030 *p++ = "0123456789abcdef"[v & 0xF];
2042 static char *new_game_desc(game_params *params, random_state *rs,
2043 game_aux_info **aux, int interactive)
2046 * We generate the coordinates of an initial click even if they
2047 * aren't actually used. This has the effect of harmonising the
2048 * random number usage between interactive and batch use: if
2049 * you use `mines --generate' with an explicit random seed, you
2050 * should get exactly the same results as if you type the same
2051 * random seed into the interactive game and click in the same
2052 * initial location. (Of course you won't get the same grid if
2053 * you click in a _different_ initial location, but there's
2054 * nothing to be done about that.)
2056 int x = random_upto(rs, params->w);
2057 int y = random_upto(rs, params->h);
2061 * For batch-generated grids, pre-open one square.
2066 grid = new_mine_layout(params->w, params->h, params->n,
2067 x, y, params->unique, rs, &desc);
2071 char *rsdesc, *desc;
2073 rsdesc = random_state_encode(rs);
2074 desc = snewn(strlen(rsdesc) + 100, char);
2075 sprintf(desc, "r%d,%c,%s", params->n, (char)(params->unique ? 'u' : 'a'), rsdesc);
2081 static void game_free_aux_info(game_aux_info *aux)
2083 assert(!"Shouldn't happen");
2086 static char *validate_desc(game_params *params, char *desc)
2088 int wh = params->w * params->h;
2092 if (!*desc || !isdigit((unsigned char)*desc))
2093 return "No initial mine count in game description";
2094 while (*desc && isdigit((unsigned char)*desc))
2095 desc++; /* skip over mine count */
2097 return "No ',' after initial x-coordinate in game description";
2099 if (*desc != 'u' && *desc != 'a')
2100 return "No uniqueness specifier in game description";
2103 return "No ',' after uniqueness specifier in game description";
2104 /* now ignore the rest */
2106 if (!*desc || !isdigit((unsigned char)*desc))
2107 return "No initial x-coordinate in game description";
2109 if (x < 0 || x >= params->w)
2110 return "Initial x-coordinate was out of range";
2111 while (*desc && isdigit((unsigned char)*desc))
2112 desc++; /* skip over x coordinate */
2114 return "No ',' after initial x-coordinate in game description";
2115 desc++; /* eat comma */
2116 if (!*desc || !isdigit((unsigned char)*desc))
2117 return "No initial y-coordinate in game description";
2119 if (y < 0 || y >= params->h)
2120 return "Initial y-coordinate was out of range";
2121 while (*desc && isdigit((unsigned char)*desc))
2122 desc++; /* skip over y coordinate */
2124 return "No ',' after initial y-coordinate in game description";
2125 desc++; /* eat comma */
2126 /* eat `m', meaning `masked', if present */
2129 /* now just check length of remainder */
2130 if (strlen(desc) != (wh+3)/4)
2131 return "Game description is wrong length";
2137 static int open_square(game_state *state, int x, int y)
2139 int w = state->w, h = state->h;
2140 int xx, yy, nmines, ncovered;
2142 if (!state->layout->mines) {
2144 * We have a preliminary game in which the mine layout
2145 * hasn't been generated yet. Generate it based on the
2146 * initial click location.
2149 state->layout->mines = new_mine_layout(w, h, state->layout->n,
2150 x, y, state->layout->unique,
2153 midend_supersede_game_desc(state->layout->me, desc);
2155 random_free(state->layout->rs);
2156 state->layout->rs = NULL;
2159 if (state->layout->mines[y*w+x]) {
2161 * The player has landed on a mine. Bad luck. Expose the
2162 * mine that killed them, but not the rest (in case they
2163 * want to Undo and carry on playing).
2166 state->grid[y*w+x] = 65;
2171 * Otherwise, the player has opened a safe square. Mark it to-do.
2173 state->grid[y*w+x] = -10; /* `todo' value internal to this func */
2176 * Now go through the grid finding all `todo' values and
2177 * opening them. Every time one of them turns out to have no
2178 * neighbouring mines, we add all its unopened neighbours to
2181 * FIXME: We really ought to be able to do this better than
2182 * using repeated N^2 scans of the grid.
2185 int done_something = FALSE;
2187 for (yy = 0; yy < h; yy++)
2188 for (xx = 0; xx < w; xx++)
2189 if (state->grid[yy*w+xx] == -10) {
2192 assert(!state->layout->mines[yy*w+xx]);
2196 for (dx = -1; dx <= +1; dx++)
2197 for (dy = -1; dy <= +1; dy++)
2198 if (xx+dx >= 0 && xx+dx < state->w &&
2199 yy+dy >= 0 && yy+dy < state->h &&
2200 state->layout->mines[(yy+dy)*w+(xx+dx)])
2203 state->grid[yy*w+xx] = v;
2206 for (dx = -1; dx <= +1; dx++)
2207 for (dy = -1; dy <= +1; dy++)
2208 if (xx+dx >= 0 && xx+dx < state->w &&
2209 yy+dy >= 0 && yy+dy < state->h &&
2210 state->grid[(yy+dy)*w+(xx+dx)] == -2)
2211 state->grid[(yy+dy)*w+(xx+dx)] = -10;
2214 done_something = TRUE;
2217 if (!done_something)
2222 * Finally, scan the grid and see if exactly as many squares
2223 * are still covered as there are mines. If so, set the `won'
2224 * flag and fill in mine markers on all covered squares.
2226 nmines = ncovered = 0;
2227 for (yy = 0; yy < h; yy++)
2228 for (xx = 0; xx < w; xx++) {
2229 if (state->grid[yy*w+xx] < 0)
2231 if (state->layout->mines[yy*w+xx])
2234 assert(ncovered >= nmines);
2235 if (ncovered == nmines) {
2236 for (yy = 0; yy < h; yy++)
2237 for (xx = 0; xx < w; xx++) {
2238 if (state->grid[yy*w+xx] < 0)
2239 state->grid[yy*w+xx] = -1;
2247 static game_state *new_game(midend_data *me, game_params *params, char *desc)
2249 game_state *state = snew(game_state);
2250 int i, wh, x, y, ret, masked;
2253 state->w = params->w;
2254 state->h = params->h;
2255 state->n = params->n;
2256 state->dead = state->won = FALSE;
2257 state->used_solve = state->just_used_solve = FALSE;
2259 wh = state->w * state->h;
2261 state->layout = snew(struct mine_layout);
2262 memset(state->layout, 0, sizeof(struct mine_layout));
2263 state->layout->refcount = 1;
2265 state->grid = snewn(wh, char);
2266 memset(state->grid, -2, wh);
2270 state->layout->n = atoi(desc);
2271 while (*desc && isdigit((unsigned char)*desc))
2272 desc++; /* skip over mine count */
2273 if (*desc) desc++; /* eat comma */
2275 state->layout->unique = FALSE;
2277 state->layout->unique = TRUE;
2279 if (*desc) desc++; /* eat comma */
2281 state->layout->mines = NULL;
2282 state->layout->rs = random_state_decode(desc);
2283 state->layout->me = me;
2286 state->layout->rs = NULL;
2287 state->layout->me = NULL;
2289 state->layout->mines = snewn(wh, char);
2291 while (*desc && isdigit((unsigned char)*desc))
2292 desc++; /* skip over x coordinate */
2293 if (*desc) desc++; /* eat comma */
2295 while (*desc && isdigit((unsigned char)*desc))
2296 desc++; /* skip over y coordinate */
2297 if (*desc) desc++; /* eat comma */
2304 * We permit game IDs to be entered by hand without the
2305 * masking transformation.
2310 bmp = snewn((wh + 7) / 8, unsigned char);
2311 memset(bmp, 0, (wh + 7) / 8);
2312 for (i = 0; i < (wh+3)/4; i++) {
2316 assert(c != 0); /* validate_desc should have caught */
2317 if (c >= '0' && c <= '9')
2319 else if (c >= 'a' && c <= 'f')
2321 else if (c >= 'A' && c <= 'F')
2326 bmp[i / 2] |= v << (4 * (1 - (i % 2)));
2330 obfuscate_bitmap(bmp, wh, TRUE);
2332 memset(state->layout->mines, 0, wh);
2333 for (i = 0; i < wh; i++) {
2334 if (bmp[i / 8] & (0x80 >> (i % 8)))
2335 state->layout->mines[i] = 1;
2338 ret = open_square(state, x, y);
2345 static game_state *dup_game(game_state *state)
2347 game_state *ret = snew(game_state);
2352 ret->dead = state->dead;
2353 ret->won = state->won;
2354 ret->used_solve = state->used_solve;
2355 ret->just_used_solve = state->just_used_solve;
2356 ret->layout = state->layout;
2357 ret->layout->refcount++;
2358 ret->grid = snewn(ret->w * ret->h, char);
2359 memcpy(ret->grid, state->grid, ret->w * ret->h);
2364 static void free_game(game_state *state)
2366 if (--state->layout->refcount <= 0) {
2367 sfree(state->layout->mines);
2368 if (state->layout->rs)
2369 random_free(state->layout->rs);
2370 sfree(state->layout);
2376 static game_state *solve_game(game_state *state, game_aux_info *aux,
2380 * Simply expose the entire grid as if it were a completed
2386 if (!state->layout->mines) {
2387 *error = "Game has not been started yet";
2391 ret = dup_game(state);
2392 for (yy = 0; yy < ret->h; yy++)
2393 for (xx = 0; xx < ret->w; xx++) {
2395 if (ret->layout->mines[yy*ret->w+xx]) {
2396 ret->grid[yy*ret->w+xx] = -1;
2402 for (dx = -1; dx <= +1; dx++)
2403 for (dy = -1; dy <= +1; dy++)
2404 if (xx+dx >= 0 && xx+dx < ret->w &&
2405 yy+dy >= 0 && yy+dy < ret->h &&
2406 ret->layout->mines[(yy+dy)*ret->w+(xx+dx)])
2409 ret->grid[yy*ret->w+xx] = v;
2412 ret->used_solve = ret->just_used_solve = TRUE;
2418 static char *game_text_format(game_state *state)
2423 ret = snewn((state->w + 1) * state->h + 1, char);
2424 for (y = 0; y < state->h; y++) {
2425 for (x = 0; x < state->w; x++) {
2426 int v = state->grid[y*state->w+x];
2429 else if (v >= 1 && v <= 8)
2433 else if (v == -2 || v == -3)
2437 ret[y * (state->w+1) + x] = v;
2439 ret[y * (state->w+1) + state->w] = '\n';
2441 ret[(state->w + 1) * state->h] = '\0';
2447 int hx, hy, hradius; /* for mouse-down highlights */
2452 static game_ui *new_ui(game_state *state)
2454 game_ui *ui = snew(game_ui);
2455 ui->hx = ui->hy = -1;
2458 ui->flash_is_death = FALSE; /* *shrug* */
2462 static void free_ui(game_ui *ui)
2467 static game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
2468 int x, int y, int button)
2473 if (from->dead || from->won)
2474 return NULL; /* no further moves permitted */
2476 if (!IS_MOUSE_DOWN(button) && !IS_MOUSE_DRAG(button) &&
2477 !IS_MOUSE_RELEASE(button))
2482 if (cx < 0 || cx >= from->w || cy < 0 || cy >= from->h)
2485 if (button == LEFT_BUTTON || button == LEFT_DRAG ||
2486 button == MIDDLE_BUTTON || button == MIDDLE_DRAG) {
2488 * Mouse-downs and mouse-drags just cause highlighting
2493 ui->hradius = (from->grid[cy*from->w+cx] >= 0 ? 1 : 0);
2497 if (button == RIGHT_BUTTON) {
2499 * Right-clicking only works on a covered square, and it
2500 * toggles between -1 (marked as mine) and -2 (not marked
2503 * FIXME: question marks.
2505 if (from->grid[cy * from->w + cx] != -2 &&
2506 from->grid[cy * from->w + cx] != -1)
2509 ret = dup_game(from);
2510 ret->just_used_solve = FALSE;
2511 ret->grid[cy * from->w + cx] ^= (-2 ^ -1);
2516 if (button == LEFT_RELEASE || button == MIDDLE_RELEASE) {
2517 ui->hx = ui->hy = -1;
2521 * At this stage we must never return NULL: we have adjusted
2522 * the ui, so at worst we return `from'.
2526 * Left-clicking on a covered square opens a tile. Not
2527 * permitted if the tile is marked as a mine, for safety.
2528 * (Unmark it and _then_ open it.)
2530 if (button == LEFT_RELEASE &&
2531 (from->grid[cy * from->w + cx] == -2 ||
2532 from->grid[cy * from->w + cx] == -3)) {
2533 ret = dup_game(from);
2534 ret->just_used_solve = FALSE;
2535 open_square(ret, cx, cy);
2542 * Left-clicking or middle-clicking on an uncovered tile:
2543 * first we check to see if the number of mine markers
2544 * surrounding the tile is equal to its mine count, and if
2545 * so then we open all other surrounding squares.
2547 if (from->grid[cy * from->w + cx] > 0) {
2550 /* Count mine markers. */
2552 for (dy = -1; dy <= +1; dy++)
2553 for (dx = -1; dx <= +1; dx++)
2554 if (cx+dx >= 0 && cx+dx < from->w &&
2555 cy+dy >= 0 && cy+dy < from->h) {
2556 if (from->grid[(cy+dy)*from->w+(cx+dx)] == -1)
2560 if (n == from->grid[cy * from->w + cx]) {
2561 ret = dup_game(from);
2562 ret->just_used_solve = FALSE;
2563 for (dy = -1; dy <= +1; dy++)
2564 for (dx = -1; dx <= +1; dx++)
2565 if (cx+dx >= 0 && cx+dx < ret->w &&
2566 cy+dy >= 0 && cy+dy < ret->h &&
2567 (ret->grid[(cy+dy)*ret->w+(cx+dx)] == -2 ||
2568 ret->grid[(cy+dy)*ret->w+(cx+dx)] == -3))
2569 open_square(ret, cx+dx, cy+dy);
2582 /* ----------------------------------------------------------------------
2586 struct game_drawstate {
2590 * Items in this `grid' array have all the same values as in
2591 * the game_state grid, and in addition:
2593 * - -10 means the tile was drawn `specially' as a result of a
2594 * flash, so it will always need redrawing.
2596 * - -22 and -23 mean the tile is highlighted for a possible
2601 static void game_size(game_params *params, int *x, int *y)
2603 *x = BORDER * 2 + TILE_SIZE * params->w;
2604 *y = BORDER * 2 + TILE_SIZE * params->h;
2607 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2609 float *ret = snewn(3 * NCOLOURS, float);
2611 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2613 ret[COL_BACKGROUND2 * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 19.0 / 20.0;
2614 ret[COL_BACKGROUND2 * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 19.0 / 20.0;
2615 ret[COL_BACKGROUND2 * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 19.0 / 20.0;
2617 ret[COL_1 * 3 + 0] = 0.0F;
2618 ret[COL_1 * 3 + 1] = 0.0F;
2619 ret[COL_1 * 3 + 2] = 1.0F;
2621 ret[COL_2 * 3 + 0] = 0.0F;
2622 ret[COL_2 * 3 + 1] = 0.5F;
2623 ret[COL_2 * 3 + 2] = 0.0F;
2625 ret[COL_3 * 3 + 0] = 1.0F;
2626 ret[COL_3 * 3 + 1] = 0.0F;
2627 ret[COL_3 * 3 + 2] = 0.0F;
2629 ret[COL_4 * 3 + 0] = 0.0F;
2630 ret[COL_4 * 3 + 1] = 0.0F;
2631 ret[COL_4 * 3 + 2] = 0.5F;
2633 ret[COL_5 * 3 + 0] = 0.5F;
2634 ret[COL_5 * 3 + 1] = 0.0F;
2635 ret[COL_5 * 3 + 2] = 0.0F;
2637 ret[COL_6 * 3 + 0] = 0.0F;
2638 ret[COL_6 * 3 + 1] = 0.5F;
2639 ret[COL_6 * 3 + 2] = 0.5F;
2641 ret[COL_7 * 3 + 0] = 0.0F;
2642 ret[COL_7 * 3 + 1] = 0.0F;
2643 ret[COL_7 * 3 + 2] = 0.0F;
2645 ret[COL_8 * 3 + 0] = 0.5F;
2646 ret[COL_8 * 3 + 1] = 0.5F;
2647 ret[COL_8 * 3 + 2] = 0.5F;
2649 ret[COL_MINE * 3 + 0] = 0.0F;
2650 ret[COL_MINE * 3 + 1] = 0.0F;
2651 ret[COL_MINE * 3 + 2] = 0.0F;
2653 ret[COL_BANG * 3 + 0] = 1.0F;
2654 ret[COL_BANG * 3 + 1] = 0.0F;
2655 ret[COL_BANG * 3 + 2] = 0.0F;
2657 ret[COL_CROSS * 3 + 0] = 1.0F;
2658 ret[COL_CROSS * 3 + 1] = 0.0F;
2659 ret[COL_CROSS * 3 + 2] = 0.0F;
2661 ret[COL_FLAG * 3 + 0] = 1.0F;
2662 ret[COL_FLAG * 3 + 1] = 0.0F;
2663 ret[COL_FLAG * 3 + 2] = 0.0F;
2665 ret[COL_FLAGBASE * 3 + 0] = 0.0F;
2666 ret[COL_FLAGBASE * 3 + 1] = 0.0F;
2667 ret[COL_FLAGBASE * 3 + 2] = 0.0F;
2669 ret[COL_QUERY * 3 + 0] = 0.0F;
2670 ret[COL_QUERY * 3 + 1] = 0.0F;
2671 ret[COL_QUERY * 3 + 2] = 0.0F;
2673 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2674 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2675 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2677 ret[COL_LOWLIGHT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 2.0 / 3.0;
2678 ret[COL_LOWLIGHT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 2.0 / 3.0;
2679 ret[COL_LOWLIGHT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 2.0 / 3.0;
2681 *ncolours = NCOLOURS;
2685 static game_drawstate *game_new_drawstate(game_state *state)
2687 struct game_drawstate *ds = snew(struct game_drawstate);
2691 ds->started = FALSE;
2692 ds->grid = snewn(ds->w * ds->h, char);
2694 memset(ds->grid, -99, ds->w * ds->h);
2699 static void game_free_drawstate(game_drawstate *ds)
2705 static void draw_tile(frontend *fe, int x, int y, int v, int bg)
2711 if (v == -22 || v == -23) {
2715 * Omit the highlights in this case.
2717 draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2718 bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg);
2719 draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2720 draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2723 * Draw highlights to indicate the square is covered.
2725 coords[0] = x + TILE_SIZE - 1;
2726 coords[1] = y + TILE_SIZE - 1;
2727 coords[2] = x + TILE_SIZE - 1;
2730 coords[5] = y + TILE_SIZE - 1;
2731 draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT ^ hl);
2732 draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT ^ hl);
2736 draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT ^ hl);
2737 draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT ^ hl);
2739 draw_rect(fe, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
2740 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
2748 #define SETCOORD(n, dx, dy) do { \
2749 coords[(n)*2+0] = x + TILE_SIZE * (dx); \
2750 coords[(n)*2+1] = y + TILE_SIZE * (dy); \
2752 SETCOORD(0, 0.6, 0.35);
2753 SETCOORD(1, 0.6, 0.7);
2754 SETCOORD(2, 0.8, 0.8);
2755 SETCOORD(3, 0.25, 0.8);
2756 SETCOORD(4, 0.55, 0.7);
2757 SETCOORD(5, 0.55, 0.35);
2758 draw_polygon(fe, coords, 6, TRUE, COL_FLAGBASE);
2759 draw_polygon(fe, coords, 6, FALSE, COL_FLAGBASE);
2761 SETCOORD(0, 0.6, 0.2);
2762 SETCOORD(1, 0.6, 0.5);
2763 SETCOORD(2, 0.2, 0.35);
2764 draw_polygon(fe, coords, 3, TRUE, COL_FLAG);
2765 draw_polygon(fe, coords, 3, FALSE, COL_FLAG);
2768 } else if (v == -3) {
2770 * Draw a question mark.
2772 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2773 FONT_VARIABLE, TILE_SIZE * 6 / 8,
2774 ALIGN_VCENTRE | ALIGN_HCENTRE,
2779 * Clear the square to the background colour, and draw thin
2780 * grid lines along the top and left.
2782 * Exception is that for value 65 (mine we've just trodden
2783 * on), we clear the square to COL_BANG.
2785 draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2786 (v == 65 ? COL_BANG :
2787 bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg));
2788 draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2789 draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2791 if (v > 0 && v <= 8) {
2798 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2799 FONT_VARIABLE, TILE_SIZE * 7 / 8,
2800 ALIGN_VCENTRE | ALIGN_HCENTRE,
2801 (COL_1 - 1) + v, str);
2803 } else if (v >= 64) {
2807 * FIXME: this could be done better!
2810 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2811 FONT_VARIABLE, TILE_SIZE * 7 / 8,
2812 ALIGN_VCENTRE | ALIGN_HCENTRE,
2816 int cx = x + TILE_SIZE / 2;
2817 int cy = y + TILE_SIZE / 2;
2818 int r = TILE_SIZE / 2 - 3;
2820 int xdx = 1, xdy = 0, ydx = 0, ydy = 1;
2823 for (i = 0; i < 4*5*2; i += 5*2) {
2824 coords[i+2*0+0] = cx - r/6*xdx + r*4/5*ydx;
2825 coords[i+2*0+1] = cy - r/6*xdy + r*4/5*ydy;
2826 coords[i+2*1+0] = cx - r/6*xdx + r*ydx;
2827 coords[i+2*1+1] = cy - r/6*xdy + r*ydy;
2828 coords[i+2*2+0] = cx + r/6*xdx + r*ydx;
2829 coords[i+2*2+1] = cy + r/6*xdy + r*ydy;
2830 coords[i+2*3+0] = cx + r/6*xdx + r*4/5*ydx;
2831 coords[i+2*3+1] = cy + r/6*xdy + r*4/5*ydy;
2832 coords[i+2*4+0] = cx + r*3/5*xdx + r*3/5*ydx;
2833 coords[i+2*4+1] = cy + r*3/5*xdy + r*3/5*ydy;
2843 draw_polygon(fe, coords, 5*4, TRUE, COL_MINE);
2844 draw_polygon(fe, coords, 5*4, FALSE, COL_MINE);
2846 draw_rect(fe, cx-r/3, cy-r/3, r/3, r/4, COL_HIGHLIGHT);
2852 * Cross through the mine.
2855 for (dx = -1; dx <= +1; dx++) {
2856 draw_line(fe, x + 3 + dx, y + 2,
2857 x + TILE_SIZE - 3 + dx,
2858 y + TILE_SIZE - 2, COL_CROSS);
2859 draw_line(fe, x + TILE_SIZE - 3 + dx, y + 2,
2860 x + 3 + dx, y + TILE_SIZE - 2,
2867 draw_update(fe, x, y, TILE_SIZE, TILE_SIZE);
2870 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2871 game_state *state, int dir, game_ui *ui,
2872 float animtime, float flashtime)
2875 int mines, markers, bg;
2878 int frame = (flashtime / FLASH_FRAME);
2880 bg = (ui->flash_is_death ? COL_BACKGROUND : COL_LOWLIGHT);
2882 bg = (ui->flash_is_death ? COL_BANG : COL_HIGHLIGHT);
2884 bg = COL_BACKGROUND;
2890 TILE_SIZE * state->w + 2 * BORDER,
2891 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
2892 draw_update(fe, 0, 0,
2893 TILE_SIZE * state->w + 2 * BORDER,
2894 TILE_SIZE * state->h + 2 * BORDER);
2897 * Recessed area containing the whole puzzle.
2899 coords[0] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2900 coords[1] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2901 coords[2] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2902 coords[3] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2903 coords[4] = coords[2] - TILE_SIZE;
2904 coords[5] = coords[3] + TILE_SIZE;
2905 coords[8] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2906 coords[9] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2907 coords[6] = coords[8] + TILE_SIZE;
2908 coords[7] = coords[9] - TILE_SIZE;
2909 draw_polygon(fe, coords, 5, TRUE, COL_HIGHLIGHT);
2910 draw_polygon(fe, coords, 5, FALSE, COL_HIGHLIGHT);
2912 coords[1] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2913 coords[0] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2914 draw_polygon(fe, coords, 5, TRUE, COL_LOWLIGHT);
2915 draw_polygon(fe, coords, 5, FALSE, COL_LOWLIGHT);
2921 * Now draw the tiles. Also in this loop, count up the number
2922 * of mines and mine markers.
2924 mines = markers = 0;
2925 for (y = 0; y < ds->h; y++)
2926 for (x = 0; x < ds->w; x++) {
2927 int v = state->grid[y*ds->w+x];
2931 if (state->layout->mines && state->layout->mines[y*ds->w+x])
2934 if ((v == -2 || v == -3) &&
2935 (abs(x-ui->hx) <= ui->hradius && abs(y-ui->hy) <= ui->hradius))
2938 if (ds->grid[y*ds->w+x] != v || bg != COL_BACKGROUND) {
2939 draw_tile(fe, COORD(x), COORD(y), v, bg);
2940 ds->grid[y*ds->w+x] = (bg == COL_BACKGROUND ? v : -10);
2944 if (!state->layout->mines)
2945 mines = state->layout->n;
2948 * Update the status bar.
2951 char statusbar[512];
2953 sprintf(statusbar, "DEAD!");
2954 } else if (state->won) {
2955 if (state->used_solve)
2956 sprintf(statusbar, "Auto-solved.");
2958 sprintf(statusbar, "COMPLETED!");
2960 sprintf(statusbar, "Marked: %d / %d", markers, mines);
2963 sprintf(statusbar + strlen(statusbar),
2964 " Deaths: %d", ui->deaths);
2965 status_bar(fe, statusbar);
2969 static float game_anim_length(game_state *oldstate, game_state *newstate,
2970 int dir, game_ui *ui)
2975 static float game_flash_length(game_state *oldstate, game_state *newstate,
2976 int dir, game_ui *ui)
2978 if (oldstate->used_solve || newstate->used_solve)
2981 if (dir > 0 && !oldstate->dead && !oldstate->won) {
2982 if (newstate->dead) {
2983 ui->flash_is_death = TRUE;
2984 return 3 * FLASH_FRAME;
2986 if (newstate->won) {
2987 ui->flash_is_death = FALSE;
2988 return 2 * FLASH_FRAME;
2994 static int game_wants_statusbar(void)
2999 static int game_timing_state(game_state *state)
3001 if (state->dead || state->won || !state->layout->mines)
3007 #define thegame mines
3010 const struct game thegame = {
3011 "Mines", "games.mines",
3018 TRUE, game_configure, custom_params,
3027 TRUE, game_text_format,
3034 game_free_drawstate,
3038 game_wants_statusbar,
3039 TRUE, game_timing_state,
3040 BUTTON_BEATS(LEFT_BUTTON, RIGHT_BUTTON),