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 int game_fetch_preset(int i, char **name, game_params **params)
102 static const struct { int w, h, n; } values[] = {
108 if (i < 0 || i >= lenof(values))
111 ret = snew(game_params);
112 ret->w = values[i].w;
113 ret->h = values[i].h;
114 ret->n = values[i].n;
117 sprintf(str, "%dx%d, %d mines", ret->w, ret->h, ret->n);
124 static void free_params(game_params *params)
129 static game_params *dup_params(game_params *params)
131 game_params *ret = snew(game_params);
132 *ret = *params; /* structure copy */
136 static void decode_params(game_params *params, char const *string)
138 char const *p = string;
141 while (*p && isdigit((unsigned char)*p)) p++;
145 while (*p && isdigit((unsigned char)*p)) p++;
147 params->h = params->w;
152 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
154 params->n = params->w * params->h / 10;
160 params->unique = FALSE;
162 p++; /* skip any other gunk */
166 static char *encode_params(game_params *params, int full)
171 len = sprintf(ret, "%dx%d", params->w, params->h);
173 * Mine count is a generation-time parameter, since it can be
174 * deduced from the mine bitmap!
177 len += sprintf(ret+len, "n%d", params->n);
178 if (full && !params->unique)
180 assert(len < lenof(ret));
186 static config_item *game_configure(game_params *params)
191 ret = snewn(5, config_item);
193 ret[0].name = "Width";
194 ret[0].type = C_STRING;
195 sprintf(buf, "%d", params->w);
196 ret[0].sval = dupstr(buf);
199 ret[1].name = "Height";
200 ret[1].type = C_STRING;
201 sprintf(buf, "%d", params->h);
202 ret[1].sval = dupstr(buf);
205 ret[2].name = "Mines";
206 ret[2].type = C_STRING;
207 sprintf(buf, "%d", params->n);
208 ret[2].sval = dupstr(buf);
211 ret[3].name = "Ensure solubility";
212 ret[3].type = C_BOOLEAN;
214 ret[3].ival = params->unique;
224 static game_params *custom_params(config_item *cfg)
226 game_params *ret = snew(game_params);
228 ret->w = atoi(cfg[0].sval);
229 ret->h = atoi(cfg[1].sval);
230 ret->n = atoi(cfg[2].sval);
231 if (strchr(cfg[2].sval, '%'))
232 ret->n = ret->n * (ret->w * ret->h) / 100;
233 ret->unique = cfg[3].ival;
238 static char *validate_params(game_params *params)
241 * Lower limit on grid size: each dimension must be at least 3.
242 * 1 is theoretically workable if rather boring, but 2 is a
243 * real problem: there is often _no_ way to generate a uniquely
244 * solvable 2xn Mines grid. You either run into two mines
245 * blocking the way and no idea what's behind them, or one mine
246 * and no way to know which of the two rows it's in. If the
247 * mine count is even you can create a soluble grid by packing
248 * all the mines at one end (so what when you hit a two-mine
249 * wall there are only as many covered squares left as there
250 * are mines); but if it's odd, you are doomed, because you
251 * _have_ to have a gap somewhere which you can't determine the
254 if (params->w <= 2 || params->h <= 2)
255 return "Width and height must both be greater than two";
256 if (params->n > params->w * params->h - 9)
257 return "Too many mines for grid size";
260 * FIXME: Need more constraints here. Not sure what the
261 * sensible limits for Minesweeper actually are. The limits
262 * probably ought to change, however, depending on uniqueness.
268 /* ----------------------------------------------------------------------
269 * Minesweeper solver, used to ensure the generated grids are
270 * solvable without having to take risks.
274 * Count the bits in a word. Only needs to cope with 16 bits.
276 static int bitcount16(int word)
278 word = ((word & 0xAAAA) >> 1) + (word & 0x5555);
279 word = ((word & 0xCCCC) >> 2) + (word & 0x3333);
280 word = ((word & 0xF0F0) >> 4) + (word & 0x0F0F);
281 word = ((word & 0xFF00) >> 8) + (word & 0x00FF);
287 * We use a tree234 to store a large number of small localised
288 * sets, each with a mine count. We also keep some of those sets
289 * linked together into a to-do list.
292 short x, y, mask, mines;
294 struct set *prev, *next;
297 static int setcmp(void *av, void *bv)
299 struct set *a = (struct set *)av;
300 struct set *b = (struct set *)bv;
304 else if (a->y > b->y)
306 else if (a->x < b->x)
308 else if (a->x > b->x)
310 else if (a->mask < b->mask)
312 else if (a->mask > b->mask)
320 struct set *todo_head, *todo_tail;
323 static struct setstore *ss_new(void)
325 struct setstore *ss = snew(struct setstore);
326 ss->sets = newtree234(setcmp);
327 ss->todo_head = ss->todo_tail = NULL;
332 * Take two input sets, in the form (x,y,mask). Munge the first by
333 * taking either its intersection with the second or its difference
334 * with the second. Return the new mask part of the first set.
336 static int setmunge(int x1, int y1, int mask1, int x2, int y2, int mask2,
340 * Adjust the second set so that it has the same x,y
341 * coordinates as the first.
343 if (abs(x2-x1) >= 3 || abs(y2-y1) >= 3) {
347 mask2 &= ~(4|32|256);
357 mask2 &= ~(64|128|256);
369 * Invert the second set if `diff' is set (we're after A &~ B
370 * rather than A & B).
376 * Now all that's left is a logical AND.
378 return mask1 & mask2;
381 static void ss_add_todo(struct setstore *ss, struct set *s)
384 return; /* already on it */
386 #ifdef SOLVER_DIAGNOSTICS
387 printf("adding set on todo list: %d,%d %03x %d\n",
388 s->x, s->y, s->mask, s->mines);
391 s->prev = ss->todo_tail;
401 static void ss_add(struct setstore *ss, int x, int y, int mask, int mines)
408 * Normalise so that x and y are genuinely the bounding
411 while (!(mask & (1|8|64)))
413 while (!(mask & (1|2|4)))
417 * Create a set structure and add it to the tree.
419 s = snew(struct set);
425 if (add234(ss->sets, s) != s) {
427 * This set already existed! Free it and return.
434 * We've added a new set to the tree, so put it on the todo
440 static void ss_remove(struct setstore *ss, struct set *s)
442 struct set *next = s->next, *prev = s->prev;
444 #ifdef SOLVER_DIAGNOSTICS
445 printf("removing set %d,%d %03x\n", s->x, s->y, s->mask);
448 * Remove s from the todo list.
452 else if (s == ss->todo_head)
453 ss->todo_head = next;
457 else if (s == ss->todo_tail)
458 ss->todo_tail = prev;
463 * Remove s from the tree.
468 * Destroy the actual set structure.
474 * Return a dynamically allocated list of all the sets which
475 * overlap a provided input set.
477 static struct set **ss_overlap(struct setstore *ss, int x, int y, int mask)
479 struct set **ret = NULL;
480 int nret = 0, retsize = 0;
483 for (xx = x-3; xx < x+3; xx++)
484 for (yy = y-3; yy < y+3; yy++) {
489 * Find the first set with these top left coordinates.
495 if (findrelpos234(ss->sets, &stmp, NULL, REL234_GE, &pos)) {
496 while ((s = index234(ss->sets, pos)) != NULL &&
497 s->x == xx && s->y == yy) {
499 * This set potentially overlaps the input one.
500 * Compute the intersection to see if they
501 * really overlap, and add it to the list if
504 if (setmunge(x, y, mask, s->x, s->y, s->mask, FALSE)) {
506 * There's an overlap.
508 if (nret >= retsize) {
510 ret = sresize(ret, retsize, struct set *);
520 ret = sresize(ret, nret+1, struct set *);
527 * Get an element from the head of the set todo list.
529 static struct set *ss_todo(struct setstore *ss)
532 struct set *ret = ss->todo_head;
533 ss->todo_head = ret->next;
535 ss->todo_head->prev = NULL;
537 ss->todo_tail = NULL;
538 ret->next = ret->prev = NULL;
551 static void std_add(struct squaretodo *std, int i)
554 std->next[std->tail] = i;
561 static void known_squares(int w, int h, struct squaretodo *std,
563 int (*open)(void *ctx, int x, int y), 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
629 static int minesolve(int w, int h, int n, signed char *grid,
630 int (*open)(void *ctx, int x, int y),
631 struct perturbations *(*perturb)(void *ctx,
633 int x, int y, int mask),
634 void *ctx, random_state *rs)
636 struct setstore *ss = ss_new();
638 struct squaretodo astd, *std = &astd;
643 * Set up a linked list of squares with known contents, so that
644 * we can process them one by one.
646 std->next = snewn(w*h, int);
647 std->head = std->tail = -1;
650 * Initialise that list with all known squares in the input
653 for (y = 0; y < h; y++) {
654 for (x = 0; x < w; x++) {
662 * Main deductive loop.
665 int done_something = FALSE;
669 * If there are any known squares on the todo list, process
670 * them and construct a set for each.
672 while (std->head != -1) {
674 #ifdef SOLVER_DIAGNOSTICS
675 printf("known square at %d,%d [%d]\n", i%w, i/w, grid[i]);
677 std->head = std->next[i];
685 int dx, dy, mines, bit, val;
686 #ifdef SOLVER_DIAGNOSTICS
687 printf("creating set around this square\n");
690 * Empty square. Construct the set of non-known squares
691 * around this one, and determine its mine count.
696 for (dy = -1; dy <= +1; dy++) {
697 for (dx = -1; dx <= +1; dx++) {
698 #ifdef SOLVER_DIAGNOSTICS
699 printf("grid %d,%d = %d\n", x+dx, y+dy, grid[i+dy*w+dx]);
701 if (x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= h)
702 /* ignore this one */;
703 else if (grid[i+dy*w+dx] == -1)
705 else if (grid[i+dy*w+dx] == -2)
711 ss_add(ss, x-1, y-1, val, mines);
715 * Now, whether the square is empty or full, we must
716 * find any set which contains it and replace it with
717 * one which does not.
720 #ifdef SOLVER_DIAGNOSTICS
721 printf("finding sets containing known square %d,%d\n", x, y);
723 list = ss_overlap(ss, x, y, 1);
725 for (j = 0; list[j]; j++) {
726 int newmask, newmines;
731 * Compute the mask for this set minus the
732 * newly known square.
734 newmask = setmunge(s->x, s->y, s->mask, x, y, 1, TRUE);
737 * Compute the new mine count.
739 newmines = s->mines - (grid[i] == -1);
742 * Insert the new set into the collection,
743 * unless it's been whittled right down to
747 ss_add(ss, s->x, s->y, newmask, newmines);
750 * Destroy the old one; it is actually obsolete.
759 * Marking a fresh square as known certainly counts as
762 done_something = TRUE;
766 * Now pick a set off the to-do list and attempt deductions
769 if ((s = ss_todo(ss)) != NULL) {
771 #ifdef SOLVER_DIAGNOSTICS
772 printf("set to do: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
775 * Firstly, see if this set has a mine count of zero or
776 * of its own cardinality.
778 if (s->mines == 0 || s->mines == bitcount16(s->mask)) {
780 * If so, we can immediately mark all the squares
781 * in the set as known.
783 #ifdef SOLVER_DIAGNOSTICS
786 known_squares(w, h, std, grid, open, ctx,
787 s->x, s->y, s->mask, (s->mines != 0));
790 * Having done that, we need do nothing further
791 * with this set; marking all the squares in it as
792 * known will eventually eliminate it, and will
793 * also permit further deductions about anything
800 * Failing that, we now search through all the sets
801 * which overlap this one.
803 list = ss_overlap(ss, s->x, s->y, s->mask);
805 for (j = 0; list[j]; j++) {
806 struct set *s2 = list[j];
807 int swing, s2wing, swc, s2wc;
810 * Find the non-overlapping parts s2-s and s-s2,
811 * and their cardinalities.
813 * I'm going to refer to these parts as `wings'
814 * surrounding the central part common to both
815 * sets. The `s wing' is s-s2; the `s2 wing' is
818 swing = setmunge(s->x, s->y, s->mask, s2->x, s2->y, s2->mask,
820 s2wing = setmunge(s2->x, s2->y, s2->mask, s->x, s->y, s->mask,
822 swc = bitcount16(swing);
823 s2wc = bitcount16(s2wing);
826 * If one set has more mines than the other, and
827 * the number of extra mines is equal to the
828 * cardinality of that set's wing, then we can mark
829 * every square in the wing as a known mine, and
830 * every square in the other wing as known clear.
832 if (swc == s->mines - s2->mines ||
833 s2wc == s2->mines - s->mines) {
834 known_squares(w, h, std, grid, open, ctx,
836 (swc == s->mines - s2->mines));
837 known_squares(w, h, std, grid, open, ctx,
838 s2->x, s2->y, s2wing,
839 (s2wc == s2->mines - s->mines));
844 * Failing that, see if one set is a subset of the
845 * other. If so, we can divide up the mine count of
846 * the larger set between the smaller set and its
847 * complement, even if neither smaller set ends up
848 * being immediately clearable.
850 if (swc == 0 && s2wc != 0) {
851 /* s is a subset of s2. */
852 assert(s2->mines > s->mines);
853 ss_add(ss, s2->x, s2->y, s2wing, s2->mines - s->mines);
854 } else if (s2wc == 0 && swc != 0) {
855 /* s2 is a subset of s. */
856 assert(s->mines > s2->mines);
857 ss_add(ss, s->x, s->y, swing, s->mines - s2->mines);
864 * In this situation we have definitely done
865 * _something_, even if it's only reducing the size of
868 done_something = TRUE;
871 * We have nothing left on our todo list, which means
872 * all localised deductions have failed. Our next step
873 * is to resort to global deduction based on the total
874 * mine count. This is computationally expensive
875 * compared to any of the above deductions, which is
876 * why we only ever do it when all else fails, so that
877 * hopefully it won't have to happen too often.
879 * If you pass n<0 into this solver, that informs it
880 * that you do not know the total mine count, so it
881 * won't even attempt these deductions.
884 int minesleft, squaresleft;
885 int nsets, setused[10], cursor;
888 * Start by scanning the current grid state to work out
889 * how many unknown squares we still have, and how many
890 * mines are to be placed in them.
894 for (i = 0; i < w*h; i++) {
897 else if (grid[i] == -2)
901 #ifdef SOLVER_DIAGNOSTICS
902 printf("global deduction time: squaresleft=%d minesleft=%d\n",
903 squaresleft, minesleft);
904 for (y = 0; y < h; y++) {
905 for (x = 0; x < w; x++) {
921 * If there _are_ no unknown squares, we have actually
924 if (squaresleft == 0) {
925 assert(minesleft == 0);
930 * First really simple case: if there are no more mines
931 * left, or if there are exactly as many mines left as
932 * squares to play them in, then it's all easy.
934 if (minesleft == 0 || minesleft == squaresleft) {
935 for (i = 0; i < w*h; i++)
937 known_squares(w, h, std, grid, open, ctx,
938 i % w, i / w, 1, minesleft != 0);
939 continue; /* now go back to main deductive loop */
943 * Failing that, we have to do some _real_ work.
944 * Ideally what we do here is to try every single
945 * combination of the currently available sets, in an
946 * attempt to find a disjoint union (i.e. a set of
947 * squares with a known mine count between them) such
948 * that the remaining unknown squares _not_ contained
949 * in that union either contain no mines or are all
952 * Actually enumerating all 2^n possibilities will get
953 * a bit slow for large n, so I artificially cap this
954 * recursion at n=10 to avoid too much pain.
956 nsets = count234(ss->sets);
957 if (nsets <= lenof(setused)) {
959 * Doing this with actual recursive function calls
960 * would get fiddly because a load of local
961 * variables from this function would have to be
962 * passed down through the recursion. So instead
963 * I'm going to use a virtual recursion within this
964 * function. The way this works is:
966 * - we have an array `setused', such that
967 * setused[n] is 0 or 1 depending on whether set
968 * n is currently in the union we are
971 * - we have a value `cursor' which indicates how
972 * much of `setused' we have so far filled in.
973 * It's conceptually the recursion depth.
975 * We begin by setting `cursor' to zero. Then:
977 * - if cursor can advance, we advance it by one.
978 * We set the value in `setused' that it went
979 * past to 1 if that set is disjoint from
980 * anything else currently in `setused', or to 0
983 * - If cursor cannot advance because it has
984 * reached the end of the setused list, then we
985 * have a maximal disjoint union. Check to see
986 * whether its mine count has any useful
987 * properties. If so, mark all the squares not
988 * in the union as known and terminate.
990 * - If cursor has reached the end of setused and
991 * the algorithm _hasn't_ terminated, back
992 * cursor up to the nearest 1, turn it into a 0
993 * and advance cursor just past it.
995 * - If we attempt to back up to the nearest 1 and
996 * there isn't one at all, then we have gone
997 * through all disjoint unions of sets in the
998 * list and none of them has been helpful, so we
1001 struct set *sets[lenof(setused)];
1002 for (i = 0; i < nsets; i++)
1003 sets[i] = index234(ss->sets, i);
1008 if (cursor < nsets) {
1011 /* See if any existing set overlaps this one. */
1012 for (i = 0; i < cursor; i++)
1014 setmunge(sets[cursor]->x,
1017 sets[i]->x, sets[i]->y, sets[i]->mask,
1025 * We're adding this set to our union,
1026 * so adjust minesleft and squaresleft
1029 minesleft -= sets[cursor]->mines;
1030 squaresleft -= bitcount16(sets[cursor]->mask);
1033 setused[cursor++] = ok;
1035 #ifdef SOLVER_DIAGNOSTICS
1036 printf("trying a set combination with %d %d\n",
1037 squaresleft, minesleft);
1038 #endif /* SOLVER_DIAGNOSTICS */
1041 * We've reached the end. See if we've got
1042 * anything interesting.
1044 if (squaresleft > 0 &&
1045 (minesleft == 0 || minesleft == squaresleft)) {
1047 * We have! There is at least one
1048 * square not contained within the set
1049 * union we've just found, and we can
1050 * deduce that either all such squares
1051 * are mines or all are not (depending
1052 * on whether minesleft==0). So now all
1053 * we have to do is actually go through
1054 * the grid, find those squares, and
1057 for (i = 0; i < w*h; i++)
1058 if (grid[i] == -2) {
1062 for (j = 0; j < nsets; j++)
1064 setmunge(sets[j]->x, sets[j]->y,
1065 sets[j]->mask, x, y, 1,
1071 known_squares(w, h, std, grid,
1073 x, y, 1, minesleft != 0);
1076 done_something = TRUE;
1077 break; /* return to main deductive loop */
1081 * If we reach here, then this union hasn't
1082 * done us any good, so move on to the
1083 * next. Backtrack cursor to the nearest 1,
1084 * change it to a 0 and continue.
1086 while (--cursor >= 0 && !setused[cursor]);
1088 assert(setused[cursor]);
1091 * We're removing this set from our
1092 * union, so re-increment minesleft and
1095 minesleft += sets[cursor]->mines;
1096 squaresleft += bitcount16(sets[cursor]->mask);
1098 setused[cursor++] = 0;
1101 * We've backtracked all the way to the
1102 * start without finding a single 1,
1103 * which means that our virtual
1104 * recursion is complete and nothing
1119 #ifdef SOLVER_DIAGNOSTICS
1121 * Dump the current known state of the grid.
1123 printf("solver ran out of steam, ret=%d, grid:\n", nperturbs);
1124 for (y = 0; y < h; y++) {
1125 for (x = 0; x < w; x++) {
1126 int v = grid[y*w+x];
1142 for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1143 printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1148 * Now we really are at our wits' end as far as solving
1149 * this grid goes. Our only remaining option is to call
1150 * a perturb function and ask it to modify the grid to
1154 struct perturbations *ret;
1160 * Choose a set at random from the current selection,
1161 * and ask the perturb function to either fill or empty
1164 * If we have no sets at all, we must give up.
1166 if (count234(ss->sets) == 0) {
1167 #ifdef SOLVER_DIAGNOSTICS
1168 printf("perturbing on entire unknown set\n");
1170 ret = perturb(ctx, grid, 0, 0, 0);
1172 s = index234(ss->sets, random_upto(rs, count234(ss->sets)));
1173 #ifdef SOLVER_DIAGNOSTICS
1174 printf("perturbing on set %d,%d %03x\n", s->x, s->y, s->mask);
1176 ret = perturb(ctx, grid, s->x, s->y, s->mask);
1180 assert(ret->n > 0); /* otherwise should have been NULL */
1183 * A number of squares have been fiddled with, and
1184 * the returned structure tells us which. Adjust
1185 * the mine count in any set which overlaps one of
1186 * those squares, and put them back on the to-do
1187 * list. Also, if the square itself is marked as a
1188 * known non-mine, put it back on the squares-to-do
1191 for (i = 0; i < ret->n; i++) {
1192 #ifdef SOLVER_DIAGNOSTICS
1193 printf("perturbation %s mine at %d,%d\n",
1194 ret->changes[i].delta > 0 ? "added" : "removed",
1195 ret->changes[i].x, ret->changes[i].y);
1198 if (ret->changes[i].delta < 0 &&
1199 grid[ret->changes[i].y*w+ret->changes[i].x] != -2) {
1200 std_add(std, ret->changes[i].y*w+ret->changes[i].x);
1203 list = ss_overlap(ss,
1204 ret->changes[i].x, ret->changes[i].y, 1);
1206 for (j = 0; list[j]; j++) {
1207 list[j]->mines += ret->changes[i].delta;
1208 ss_add_todo(ss, list[j]);
1215 * Now free the returned data.
1217 sfree(ret->changes);
1220 #ifdef SOLVER_DIAGNOSTICS
1222 * Dump the current known state of the grid.
1224 printf("state after perturbation:\n");
1225 for (y = 0; y < h; y++) {
1226 for (x = 0; x < w; x++) {
1227 int v = grid[y*w+x];
1243 for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1244 printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1249 * And now we can go back round the deductive loop.
1256 * If we get here, even that didn't work (either we didn't
1257 * have a perturb function or it returned failure), so we
1264 * See if we've got any unknown squares left.
1266 for (y = 0; y < h; y++)
1267 for (x = 0; x < w; x++)
1268 if (grid[y*w+x] == -2) {
1269 nperturbs = -1; /* failed to complete */
1274 * Free the set list and square-todo list.
1278 while ((s = delpos234(ss->sets, 0)) != NULL)
1280 freetree234(ss->sets);
1288 /* ----------------------------------------------------------------------
1289 * Grid generator which uses the above solver.
1296 int allow_big_perturbs;
1300 static int mineopen(void *vctx, int x, int y)
1302 struct minectx *ctx = (struct minectx *)vctx;
1305 assert(x >= 0 && x < ctx->w && y >= 0 && y < ctx->h);
1306 if (ctx->grid[y * ctx->w + x])
1307 return -1; /* *bang* */
1310 for (i = -1; i <= +1; i++) {
1311 if (x + i < 0 || x + i >= ctx->w)
1313 for (j = -1; j <= +1; j++) {
1314 if (y + j < 0 || y + j >= ctx->h)
1316 if (i == 0 && j == 0)
1318 if (ctx->grid[(y+j) * ctx->w + (x+i)])
1326 /* Structure used internally to mineperturb(). */
1328 int x, y, type, random;
1330 static int squarecmp(const void *av, const void *bv)
1332 const struct square *a = (const struct square *)av;
1333 const struct square *b = (const struct square *)bv;
1334 if (a->type < b->type)
1336 else if (a->type > b->type)
1338 else if (a->random < b->random)
1340 else if (a->random > b->random)
1342 else if (a->y < b->y)
1344 else if (a->y > b->y)
1346 else if (a->x < b->x)
1348 else if (a->x > b->x)
1354 * Normally this function is passed an (x,y,mask) set description.
1355 * On occasions, though, there is no _localised_ set being used,
1356 * and the set being perturbed is supposed to be the entirety of
1357 * the unreachable area. This is signified by the special case
1358 * mask==0: in this case, anything labelled -2 in the grid is part
1361 * Allowing perturbation in this special case appears to make it
1362 * guaranteeably possible to generate a workable grid for any mine
1363 * density, but they tend to be a bit boring, with mines packed
1364 * densely into far corners of the grid and the remainder being
1365 * less dense than one might like. Therefore, to improve overall
1366 * grid quality I disable this feature for the first few attempts,
1367 * and fall back to it after no useful grid has been generated.
1369 static struct perturbations *mineperturb(void *vctx, signed char *grid,
1370 int setx, int sety, int mask)
1372 struct minectx *ctx = (struct minectx *)vctx;
1373 struct square *sqlist;
1374 int x, y, dx, dy, i, n, nfull, nempty;
1375 struct square **tofill, **toempty, **todo;
1376 int ntofill, ntoempty, ntodo, dtodo, dset;
1377 struct perturbations *ret;
1380 if (!mask && !ctx->allow_big_perturbs)
1384 * Make a list of all the squares in the grid which we can
1385 * possibly use. This list should be in preference order, which
1388 * - first, unknown squares on the boundary of known space
1389 * - next, unknown squares beyond that boundary
1390 * - as a very last resort, known squares, but not within one
1391 * square of the starting position.
1393 * Each of these sections needs to be shuffled independently.
1394 * We do this by preparing list of all squares and then sorting
1395 * it with a random secondary key.
1397 sqlist = snewn(ctx->w * ctx->h, struct square);
1399 for (y = 0; y < ctx->h; y++)
1400 for (x = 0; x < ctx->w; x++) {
1402 * If this square is too near the starting position,
1403 * don't put it on the list at all.
1405 if (abs(y - ctx->sy) <= 1 && abs(x - ctx->sx) <= 1)
1409 * If this square is in the input set, also don't put
1412 if ((mask == 0 && grid[y*ctx->w+x] == -2) ||
1413 (x >= setx && x < setx + 3 &&
1414 y >= sety && y < sety + 3 &&
1415 mask & (1 << ((y-sety)*3+(x-setx)))))
1421 if (grid[y*ctx->w+x] != -2) {
1422 sqlist[n].type = 3; /* known square */
1425 * Unknown square. Examine everything around it and
1426 * see if it borders on any known squares. If it
1427 * does, it's class 1, otherwise it's 2.
1432 for (dy = -1; dy <= +1; dy++)
1433 for (dx = -1; dx <= +1; dx++)
1434 if (x+dx >= 0 && x+dx < ctx->w &&
1435 y+dy >= 0 && y+dy < ctx->h &&
1436 grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1443 * Finally, a random number to cause qsort to
1444 * shuffle within each group.
1446 sqlist[n].random = random_bits(ctx->rs, 31);
1451 qsort(sqlist, n, sizeof(struct square), squarecmp);
1454 * Now count up the number of full and empty squares in the set
1455 * we've been provided.
1459 for (dy = 0; dy < 3; dy++)
1460 for (dx = 0; dx < 3; dx++)
1461 if (mask & (1 << (dy*3+dx))) {
1462 assert(setx+dx <= ctx->w);
1463 assert(sety+dy <= ctx->h);
1464 if (ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1470 for (y = 0; y < ctx->h; y++)
1471 for (x = 0; x < ctx->w; x++)
1472 if (grid[y*ctx->w+x] == -2) {
1473 if (ctx->grid[y*ctx->w+x])
1481 * Now go through our sorted list until we find either `nfull'
1482 * empty squares, or `nempty' full squares; these will be
1483 * swapped with the appropriate squares in the set to either
1484 * fill or empty the set while keeping the same number of mines
1487 ntofill = ntoempty = 0;
1489 tofill = snewn(9, struct square *);
1490 toempty = snewn(9, struct square *);
1492 tofill = snewn(ctx->w * ctx->h, struct square *);
1493 toempty = snewn(ctx->w * ctx->h, struct square *);
1495 for (i = 0; i < n; i++) {
1496 struct square *sq = &sqlist[i];
1497 if (ctx->grid[sq->y * ctx->w + sq->x])
1498 toempty[ntoempty++] = sq;
1500 tofill[ntofill++] = sq;
1501 if (ntofill == nfull || ntoempty == nempty)
1506 * If we haven't found enough empty squares outside the set to
1507 * empty it into _or_ enough full squares outside it to fill it
1508 * up with, we'll have to settle for doing only a partial job.
1509 * In this case we choose to always _fill_ the set (because
1510 * this case will tend to crop up when we're working with very
1511 * high mine densities and the only way to get a solvable grid
1512 * is going to be to pack most of the mines solidly around the
1513 * edges). So now our job is to make a list of the empty
1514 * squares in the set, and shuffle that list so that we fill a
1515 * random selection of them.
1517 if (ntofill != nfull && ntoempty != nempty) {
1520 assert(ntoempty != 0);
1522 setlist = snewn(ctx->w * ctx->h, int);
1525 for (dy = 0; dy < 3; dy++)
1526 for (dx = 0; dx < 3; dx++)
1527 if (mask & (1 << (dy*3+dx))) {
1528 assert(setx+dx <= ctx->w);
1529 assert(sety+dy <= ctx->h);
1530 if (!ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1531 setlist[i++] = (sety+dy)*ctx->w+(setx+dx);
1534 for (y = 0; y < ctx->h; y++)
1535 for (x = 0; x < ctx->w; x++)
1536 if (grid[y*ctx->w+x] == -2) {
1537 if (!ctx->grid[y*ctx->w+x])
1538 setlist[i++] = y*ctx->w+x;
1541 assert(i > ntoempty);
1543 * Now pick `ntoempty' items at random from the list.
1545 for (k = 0; k < ntoempty; k++) {
1546 int index = k + random_upto(ctx->rs, i - k);
1550 setlist[k] = setlist[index];
1551 setlist[index] = tmp;
1557 * Now we're pretty much there. We need to either
1558 * (a) put a mine in each of the empty squares in the set, and
1559 * take one out of each square in `toempty'
1560 * (b) take a mine out of each of the full squares in the set,
1561 * and put one in each square in `tofill'
1562 * depending on which one we've found enough squares to do.
1564 * So we start by constructing our list of changes to return to
1565 * the solver, so that it can update its data structures
1566 * efficiently rather than having to rescan the whole grid.
1568 ret = snew(struct perturbations);
1569 if (ntofill == nfull) {
1577 * (We also fall into this case if we've constructed a
1587 ret->changes = snewn(ret->n, struct perturbation);
1588 for (i = 0; i < ntodo; i++) {
1589 ret->changes[i].x = todo[i]->x;
1590 ret->changes[i].y = todo[i]->y;
1591 ret->changes[i].delta = dtodo;
1593 /* now i == ntodo */
1596 assert(todo == toempty);
1597 for (j = 0; j < ntoempty; j++) {
1598 ret->changes[i].x = setlist[j] % ctx->w;
1599 ret->changes[i].y = setlist[j] / ctx->w;
1600 ret->changes[i].delta = dset;
1605 for (dy = 0; dy < 3; dy++)
1606 for (dx = 0; dx < 3; dx++)
1607 if (mask & (1 << (dy*3+dx))) {
1608 int currval = (ctx->grid[(sety+dy)*ctx->w+(setx+dx)] ? +1 : -1);
1609 if (dset == -currval) {
1610 ret->changes[i].x = setx + dx;
1611 ret->changes[i].y = sety + dy;
1612 ret->changes[i].delta = dset;
1617 for (y = 0; y < ctx->h; y++)
1618 for (x = 0; x < ctx->w; x++)
1619 if (grid[y*ctx->w+x] == -2) {
1620 int currval = (ctx->grid[y*ctx->w+x] ? +1 : -1);
1621 if (dset == -currval) {
1622 ret->changes[i].x = x;
1623 ret->changes[i].y = y;
1624 ret->changes[i].delta = dset;
1629 assert(i == ret->n);
1635 * Having set up the precise list of changes we're going to
1636 * make, we now simply make them and return.
1638 for (i = 0; i < ret->n; i++) {
1641 x = ret->changes[i].x;
1642 y = ret->changes[i].y;
1643 delta = ret->changes[i].delta;
1646 * Check we're not trying to add an existing mine or remove
1649 assert((delta < 0) ^ (ctx->grid[y*ctx->w+x] == 0));
1652 * Actually make the change.
1654 ctx->grid[y*ctx->w+x] = (delta > 0);
1657 * Update any numbers already present in the grid.
1659 for (dy = -1; dy <= +1; dy++)
1660 for (dx = -1; dx <= +1; dx++)
1661 if (x+dx >= 0 && x+dx < ctx->w &&
1662 y+dy >= 0 && y+dy < ctx->h &&
1663 grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1664 if (dx == 0 && dy == 0) {
1666 * The square itself is marked as known in
1667 * the grid. Mark it as a mine if it's a
1668 * mine, or else work out its number.
1671 grid[y*ctx->w+x] = -1;
1673 int dx2, dy2, minecount = 0;
1674 for (dy2 = -1; dy2 <= +1; dy2++)
1675 for (dx2 = -1; dx2 <= +1; dx2++)
1676 if (x+dx2 >= 0 && x+dx2 < ctx->w &&
1677 y+dy2 >= 0 && y+dy2 < ctx->h &&
1678 ctx->grid[(y+dy2)*ctx->w+(x+dx2)])
1680 grid[y*ctx->w+x] = minecount;
1683 if (grid[(y+dy)*ctx->w+(x+dx)] >= 0)
1684 grid[(y+dy)*ctx->w+(x+dx)] += delta;
1689 #ifdef GENERATION_DIAGNOSTICS
1692 printf("grid after perturbing:\n");
1693 for (yy = 0; yy < ctx->h; yy++) {
1694 for (xx = 0; xx < ctx->w; xx++) {
1695 int v = ctx->grid[yy*ctx->w+xx];
1696 if (yy == ctx->sy && xx == ctx->sx) {
1714 static char *minegen(int w, int h, int n, int x, int y, int unique,
1717 char *ret = snewn(w*h, char);
1725 memset(ret, 0, w*h);
1728 * Start by placing n mines, none of which is at x,y or within
1732 int *tmp = snewn(w*h, int);
1736 * Write down the list of possible mine locations.
1739 for (i = 0; i < h; i++)
1740 for (j = 0; j < w; j++)
1741 if (abs(i - y) > 1 || abs(j - x) > 1)
1745 * Now pick n off the list at random.
1749 i = random_upto(rs, k);
1757 #ifdef GENERATION_DIAGNOSTICS
1760 printf("grid after initial generation:\n");
1761 for (yy = 0; yy < h; yy++) {
1762 for (xx = 0; xx < w; xx++) {
1763 int v = ret[yy*w+xx];
1764 if (yy == y && xx == x) {
1780 * Now set up a results grid to run the solver in, and a
1781 * context for the solver to open squares. Then run the solver
1782 * repeatedly; if the number of perturb steps ever goes up or
1783 * it ever returns -1, give up completely.
1785 * We bypass this bit if we're not after a unique grid.
1788 signed char *solvegrid = snewn(w*h, char);
1789 struct minectx actx, *ctx = &actx;
1790 int solveret, prevret = -2;
1798 ctx->allow_big_perturbs = (ntries > 100);
1801 memset(solvegrid, -2, w*h);
1802 solvegrid[y*w+x] = mineopen(ctx, x, y);
1803 assert(solvegrid[y*w+x] == 0); /* by deliberate arrangement */
1806 minesolve(w, h, n, solvegrid, mineopen, mineperturb, ctx, rs);
1807 if (solveret < 0 || (prevret >= 0 && solveret >= prevret)) {
1810 } else if (solveret == 0) {
1827 * The Mines game descriptions contain the location of every mine,
1828 * and can therefore be used to cheat.
1830 * It would be pointless to attempt to _prevent_ this form of
1831 * cheating by encrypting the description, since Mines is
1832 * open-source so anyone can find out the encryption key. However,
1833 * I think it is worth doing a bit of gentle obfuscation to prevent
1834 * _accidental_ spoilers: if you happened to note that the game ID
1835 * starts with an F, for example, you might be unable to put the
1836 * knowledge of those mines out of your mind while playing. So,
1837 * just as discussions of film endings are rot13ed to avoid
1838 * spoiling it for people who don't want to be told, we apply a
1839 * keyless, reversible, but visually completely obfuscatory masking
1840 * function to the mine bitmap.
1842 static void obfuscate_bitmap(unsigned char *bmp, int bits, int decode)
1844 int bytes, firsthalf, secondhalf;
1846 unsigned char *seedstart;
1848 unsigned char *targetstart;
1854 * My obfuscation algorithm is similar in concept to the OAEP
1855 * encoding used in some forms of RSA. Here's a specification
1858 * + We have a `masking function' which constructs a stream of
1859 * pseudorandom bytes from a seed of some number of input
1862 * + We pad out our input bit stream to a whole number of
1863 * bytes by adding up to 7 zero bits on the end. (In fact
1864 * the bitmap passed as input to this function will already
1865 * have had this done in practice.)
1867 * + We divide the _byte_ stream exactly in half, rounding the
1868 * half-way position _down_. So an 81-bit input string, for
1869 * example, rounds up to 88 bits or 11 bytes, and then
1870 * dividing by two gives 5 bytes in the first half and 6 in
1873 * + We generate a mask from the second half of the bytes, and
1874 * XOR it over the first half.
1876 * + We generate a mask from the (encoded) first half of the
1877 * bytes, and XOR it over the second half. Any null bits at
1878 * the end which were added as padding are cleared back to
1879 * zero even if this operation would have made them nonzero.
1881 * To de-obfuscate, the steps are precisely the same except
1882 * that the final two are reversed.
1884 * Finally, our masking function. Given an input seed string of
1885 * bytes, the output mask consists of concatenating the SHA-1
1886 * hashes of the seed string and successive decimal integers,
1890 bytes = (bits + 7) / 8;
1891 firsthalf = bytes / 2;
1892 secondhalf = bytes - firsthalf;
1894 steps[decode ? 1 : 0].seedstart = bmp + firsthalf;
1895 steps[decode ? 1 : 0].seedlen = secondhalf;
1896 steps[decode ? 1 : 0].targetstart = bmp;
1897 steps[decode ? 1 : 0].targetlen = firsthalf;
1899 steps[decode ? 0 : 1].seedstart = bmp;
1900 steps[decode ? 0 : 1].seedlen = firsthalf;
1901 steps[decode ? 0 : 1].targetstart = bmp + firsthalf;
1902 steps[decode ? 0 : 1].targetlen = secondhalf;
1904 for (i = 0; i < 2; i++) {
1905 SHA_State base, final;
1906 unsigned char digest[20];
1908 int digestpos = 20, counter = 0;
1911 SHA_Bytes(&base, steps[i].seedstart, steps[i].seedlen);
1913 for (j = 0; j < steps[i].targetlen; j++) {
1914 if (digestpos >= 20) {
1915 sprintf(numberbuf, "%d", counter++);
1917 SHA_Bytes(&final, numberbuf, strlen(numberbuf));
1918 SHA_Final(&final, digest);
1921 steps[i].targetstart[j] ^= digest[digestpos++];
1925 * Mask off the pad bits in the final byte after both steps.
1928 bmp[bits / 8] &= 0xFF & (0xFF00 >> (bits % 8));
1932 static char *new_mine_layout(int w, int h, int n, int x, int y, int unique,
1933 random_state *rs, char **game_desc)
1935 signed char *grid, *ret, *p;
1939 #ifdef TEST_OBFUSCATION
1940 static int tested_obfuscation = FALSE;
1941 if (!tested_obfuscation) {
1943 * A few simple test vectors for the obfuscator.
1945 * First test: the 28-bit stream 1234567. This divides up
1946 * into 1234 and 567[0]. The SHA of 56 70 30 (appending
1947 * "0") is 15ce8ab946640340bbb99f3f48fd2c45d1a31d30. Thus,
1948 * we XOR the 16-bit string 15CE into the input 1234 to get
1949 * 07FA. Next, we SHA that with "0": the SHA of 07 FA 30 is
1950 * 3370135c5e3da4fed937adc004a79533962b6391. So we XOR the
1951 * 12-bit string 337 into the input 567 to get 650. Thus
1952 * our output is 07FA650.
1955 unsigned char bmp1[] = "\x12\x34\x56\x70";
1956 obfuscate_bitmap(bmp1, 28, FALSE);
1957 printf("test 1 encode: %s\n",
1958 memcmp(bmp1, "\x07\xfa\x65\x00", 4) ? "failed" : "passed");
1959 obfuscate_bitmap(bmp1, 28, TRUE);
1960 printf("test 1 decode: %s\n",
1961 memcmp(bmp1, "\x12\x34\x56\x70", 4) ? "failed" : "passed");
1964 * Second test: a long string to make sure we switch from
1965 * one SHA to the next correctly. My input string this time
1966 * is simply fifty bytes of zeroes.
1969 unsigned char bmp2[50];
1970 unsigned char bmp2a[50];
1971 memset(bmp2, 0, 50);
1972 memset(bmp2a, 0, 50);
1973 obfuscate_bitmap(bmp2, 50 * 8, FALSE);
1975 * SHA of twenty-five zero bytes plus "0" is
1976 * b202c07b990c01f6ff2d544707f60e506019b671. SHA of
1977 * twenty-five zero bytes plus "1" is
1978 * fcb1d8b5a2f6b592fe6780b36aa9d65dd7aa6db9. Thus our
1979 * first half becomes
1980 * b202c07b990c01f6ff2d544707f60e506019b671fcb1d8b5a2.
1982 * SHA of that lot plus "0" is
1983 * 10b0af913db85d37ca27f52a9f78bba3a80030db. SHA of the
1984 * same string plus "1" is
1985 * 3d01d8df78e76d382b8106f480135a1bc751d725. So the
1986 * second half becomes
1987 * 10b0af913db85d37ca27f52a9f78bba3a80030db3d01d8df78.
1989 printf("test 2 encode: %s\n",
1990 memcmp(bmp2, "\xb2\x02\xc0\x7b\x99\x0c\x01\xf6\xff\x2d\x54"
1991 "\x47\x07\xf6\x0e\x50\x60\x19\xb6\x71\xfc\xb1\xd8"
1992 "\xb5\xa2\x10\xb0\xaf\x91\x3d\xb8\x5d\x37\xca\x27"
1993 "\xf5\x2a\x9f\x78\xbb\xa3\xa8\x00\x30\xdb\x3d\x01"
1994 "\xd8\xdf\x78", 50) ? "failed" : "passed");
1995 obfuscate_bitmap(bmp2, 50 * 8, TRUE);
1996 printf("test 2 decode: %s\n",
1997 memcmp(bmp2, bmp2a, 50) ? "failed" : "passed");
2002 grid = minegen(w, h, n, x, y, unique, rs);
2006 * Set up the mine bitmap and obfuscate it.
2009 bmp = snewn((area + 7) / 8, unsigned char);
2010 memset(bmp, 0, (area + 7) / 8);
2011 for (i = 0; i < area; i++) {
2013 bmp[i / 8] |= 0x80 >> (i % 8);
2015 obfuscate_bitmap(bmp, area, FALSE);
2018 * Now encode the resulting bitmap in hex. We can work to
2019 * nibble rather than byte granularity, since the obfuscation
2020 * function guarantees to return a bit string of the same
2021 * length as its input.
2023 ret = snewn((area+3)/4 + 100, char);
2024 p = ret + sprintf(ret, "%d,%d,m", x, y); /* 'm' == masked */
2025 for (i = 0; i < (area+3)/4; i++) {
2029 *p++ = "0123456789abcdef"[v & 0xF];
2041 static char *new_game_desc(game_params *params, random_state *rs,
2042 game_aux_info **aux, int interactive)
2046 * For batch-generated grids, pre-open one square.
2048 int x = random_upto(rs, params->w);
2049 int y = random_upto(rs, params->h);
2053 grid = new_mine_layout(params->w, params->h, params->n,
2054 x, y, params->unique, rs, &desc);
2058 char *rsdesc, *desc;
2060 rsdesc = random_state_encode(rs);
2061 desc = snewn(strlen(rsdesc) + 100, char);
2062 sprintf(desc, "r%d,%c,%s", params->n, params->unique ? 'u' : 'a', rsdesc);
2068 static void game_free_aux_info(game_aux_info *aux)
2070 assert(!"Shouldn't happen");
2073 static char *validate_desc(game_params *params, char *desc)
2075 int wh = params->w * params->h;
2079 if (!*desc || !isdigit((unsigned char)*desc))
2080 return "No initial mine count in game description";
2081 while (*desc && isdigit((unsigned char)*desc))
2082 desc++; /* skip over mine count */
2084 return "No ',' after initial x-coordinate in game description";
2086 if (*desc != 'u' && *desc != 'a')
2087 return "No uniqueness specifier in game description";
2090 return "No ',' after uniqueness specifier in game description";
2091 /* now ignore the rest */
2093 if (!*desc || !isdigit((unsigned char)*desc))
2094 return "No initial x-coordinate in game description";
2096 if (x < 0 || x >= params->w)
2097 return "Initial x-coordinate was out of range";
2098 while (*desc && isdigit((unsigned char)*desc))
2099 desc++; /* skip over x coordinate */
2101 return "No ',' after initial x-coordinate in game description";
2102 desc++; /* eat comma */
2103 if (!*desc || !isdigit((unsigned char)*desc))
2104 return "No initial y-coordinate in game description";
2106 if (y < 0 || y >= params->h)
2107 return "Initial y-coordinate was out of range";
2108 while (*desc && isdigit((unsigned char)*desc))
2109 desc++; /* skip over y coordinate */
2111 return "No ',' after initial y-coordinate in game description";
2112 desc++; /* eat comma */
2113 /* eat `m', meaning `masked', if present */
2116 /* now just check length of remainder */
2117 if (strlen(desc) != (wh+3)/4)
2118 return "Game description is wrong length";
2124 static int open_square(game_state *state, int x, int y)
2126 int w = state->w, h = state->h;
2127 int xx, yy, nmines, ncovered;
2129 if (!state->layout->mines) {
2131 * We have a preliminary game in which the mine layout
2132 * hasn't been generated yet. Generate it based on the
2133 * initial click location.
2136 state->layout->mines = new_mine_layout(w, h, state->layout->n,
2137 x, y, state->layout->unique,
2140 midend_supersede_game_desc(state->layout->me, desc);
2142 random_free(state->layout->rs);
2143 state->layout->rs = NULL;
2146 if (state->layout->mines[y*w+x]) {
2148 * The player has landed on a mine. Bad luck. Expose the
2149 * mine that killed them, but not the rest (in case they
2150 * want to Undo and carry on playing).
2153 state->grid[y*w+x] = 65;
2158 * Otherwise, the player has opened a safe square. Mark it to-do.
2160 state->grid[y*w+x] = -10; /* `todo' value internal to this func */
2163 * Now go through the grid finding all `todo' values and
2164 * opening them. Every time one of them turns out to have no
2165 * neighbouring mines, we add all its unopened neighbours to
2168 * FIXME: We really ought to be able to do this better than
2169 * using repeated N^2 scans of the grid.
2172 int done_something = FALSE;
2174 for (yy = 0; yy < h; yy++)
2175 for (xx = 0; xx < w; xx++)
2176 if (state->grid[yy*w+xx] == -10) {
2179 assert(!state->layout->mines[yy*w+xx]);
2183 for (dx = -1; dx <= +1; dx++)
2184 for (dy = -1; dy <= +1; dy++)
2185 if (xx+dx >= 0 && xx+dx < state->w &&
2186 yy+dy >= 0 && yy+dy < state->h &&
2187 state->layout->mines[(yy+dy)*w+(xx+dx)])
2190 state->grid[yy*w+xx] = v;
2193 for (dx = -1; dx <= +1; dx++)
2194 for (dy = -1; dy <= +1; dy++)
2195 if (xx+dx >= 0 && xx+dx < state->w &&
2196 yy+dy >= 0 && yy+dy < state->h &&
2197 state->grid[(yy+dy)*w+(xx+dx)] == -2)
2198 state->grid[(yy+dy)*w+(xx+dx)] = -10;
2201 done_something = TRUE;
2204 if (!done_something)
2209 * Finally, scan the grid and see if exactly as many squares
2210 * are still covered as there are mines. If so, set the `won'
2211 * flag and fill in mine markers on all covered squares.
2213 nmines = ncovered = 0;
2214 for (yy = 0; yy < h; yy++)
2215 for (xx = 0; xx < w; xx++) {
2216 if (state->grid[yy*w+xx] < 0)
2218 if (state->layout->mines[yy*w+xx])
2221 assert(ncovered >= nmines);
2222 if (ncovered == nmines) {
2223 for (yy = 0; yy < h; yy++)
2224 for (xx = 0; xx < w; xx++) {
2225 if (state->grid[yy*w+xx] < 0)
2226 state->grid[yy*w+xx] = -1;
2234 static game_state *new_game(midend_data *me, game_params *params, char *desc)
2236 game_state *state = snew(game_state);
2237 int i, wh, x, y, ret, masked;
2240 state->w = params->w;
2241 state->h = params->h;
2242 state->n = params->n;
2243 state->dead = state->won = FALSE;
2244 state->used_solve = state->just_used_solve = FALSE;
2246 wh = state->w * state->h;
2248 state->layout = snew(struct mine_layout);
2249 state->layout->refcount = 1;
2251 state->grid = snewn(wh, char);
2252 memset(state->grid, -2, wh);
2256 state->layout->n = atoi(desc);
2257 while (*desc && isdigit((unsigned char)*desc))
2258 desc++; /* skip over mine count */
2259 if (*desc) desc++; /* eat comma */
2261 state->layout->unique = FALSE;
2263 state->layout->unique = TRUE;
2265 if (*desc) desc++; /* eat comma */
2267 state->layout->mines = NULL;
2268 state->layout->rs = random_state_decode(desc);
2269 state->layout->me = me;
2272 state->layout->rs = NULL;
2273 state->layout->me = NULL;
2275 state->layout->mines = snewn(wh, char);
2277 while (*desc && isdigit((unsigned char)*desc))
2278 desc++; /* skip over x coordinate */
2279 if (*desc) desc++; /* eat comma */
2281 while (*desc && isdigit((unsigned char)*desc))
2282 desc++; /* skip over y coordinate */
2283 if (*desc) desc++; /* eat comma */
2290 * We permit game IDs to be entered by hand without the
2291 * masking transformation.
2296 bmp = snewn((wh + 7) / 8, unsigned char);
2297 memset(bmp, 0, (wh + 7) / 8);
2298 for (i = 0; i < (wh+3)/4; i++) {
2302 assert(c != 0); /* validate_desc should have caught */
2303 if (c >= '0' && c <= '9')
2305 else if (c >= 'a' && c <= 'f')
2307 else if (c >= 'A' && c <= 'F')
2312 bmp[i / 2] |= v << (4 * (1 - (i % 2)));
2316 obfuscate_bitmap(bmp, wh, TRUE);
2318 memset(state->layout->mines, 0, wh);
2319 for (i = 0; i < wh; i++) {
2320 if (bmp[i / 8] & (0x80 >> (i % 8)))
2321 state->layout->mines[i] = 1;
2324 ret = open_square(state, x, y);
2330 static game_state *dup_game(game_state *state)
2332 game_state *ret = snew(game_state);
2337 ret->dead = state->dead;
2338 ret->won = state->won;
2339 ret->used_solve = state->used_solve;
2340 ret->just_used_solve = state->just_used_solve;
2341 ret->layout = state->layout;
2342 ret->layout->refcount++;
2343 ret->grid = snewn(ret->w * ret->h, char);
2344 memcpy(ret->grid, state->grid, ret->w * ret->h);
2349 static void free_game(game_state *state)
2351 if (--state->layout->refcount <= 0) {
2352 sfree(state->layout->mines);
2353 if (state->layout->rs)
2354 random_free(state->layout->rs);
2355 sfree(state->layout);
2361 static game_state *solve_game(game_state *state, game_aux_info *aux,
2365 * Simply expose the entire grid as if it were a completed
2371 if (!state->layout->mines) {
2372 *error = "Game has not been started yet";
2376 ret = dup_game(state);
2377 for (yy = 0; yy < ret->h; yy++)
2378 for (xx = 0; xx < ret->w; xx++) {
2380 if (ret->layout->mines[yy*ret->w+xx]) {
2381 ret->grid[yy*ret->w+xx] = -1;
2387 for (dx = -1; dx <= +1; dx++)
2388 for (dy = -1; dy <= +1; dy++)
2389 if (xx+dx >= 0 && xx+dx < ret->w &&
2390 yy+dy >= 0 && yy+dy < ret->h &&
2391 ret->layout->mines[(yy+dy)*ret->w+(xx+dx)])
2394 ret->grid[yy*ret->w+xx] = v;
2397 ret->used_solve = ret->just_used_solve = TRUE;
2403 static char *game_text_format(game_state *state)
2408 ret = snewn((state->w + 1) * state->h + 1, char);
2409 for (y = 0; y < state->h; y++) {
2410 for (x = 0; x < state->w; x++) {
2411 int v = state->grid[y*state->w+x];
2414 else if (v >= 1 && v <= 8)
2418 else if (v == -2 || v == -3)
2422 ret[y * (state->w+1) + x] = v;
2424 ret[y * (state->w+1) + state->w] = '\n';
2426 ret[(state->w + 1) * state->h] = '\0';
2432 int hx, hy, hradius; /* for mouse-down highlights */
2437 static game_ui *new_ui(game_state *state)
2439 game_ui *ui = snew(game_ui);
2440 ui->hx = ui->hy = -1;
2443 ui->flash_is_death = FALSE; /* *shrug* */
2447 static void free_ui(game_ui *ui)
2452 static game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
2453 int x, int y, int button)
2458 if (from->dead || from->won)
2459 return NULL; /* no further moves permitted */
2461 if (!IS_MOUSE_DOWN(button) && !IS_MOUSE_DRAG(button) &&
2462 !IS_MOUSE_RELEASE(button))
2467 if (cx < 0 || cx >= from->w || cy < 0 || cy >= from->h)
2470 if (button == LEFT_BUTTON || button == LEFT_DRAG ||
2471 button == MIDDLE_BUTTON || button == MIDDLE_DRAG) {
2473 * Mouse-downs and mouse-drags just cause highlighting
2478 ui->hradius = (from->grid[cy*from->w+cx] >= 0 ? 1 : 0);
2482 if (button == RIGHT_BUTTON) {
2484 * Right-clicking only works on a covered square, and it
2485 * toggles between -1 (marked as mine) and -2 (not marked
2488 * FIXME: question marks.
2490 if (from->grid[cy * from->w + cx] != -2 &&
2491 from->grid[cy * from->w + cx] != -1)
2494 ret = dup_game(from);
2495 ret->just_used_solve = FALSE;
2496 ret->grid[cy * from->w + cx] ^= (-2 ^ -1);
2501 if (button == LEFT_RELEASE || button == MIDDLE_RELEASE) {
2502 ui->hx = ui->hy = -1;
2506 * At this stage we must never return NULL: we have adjusted
2507 * the ui, so at worst we return `from'.
2511 * Left-clicking on a covered square opens a tile. Not
2512 * permitted if the tile is marked as a mine, for safety.
2513 * (Unmark it and _then_ open it.)
2515 if (button == LEFT_RELEASE &&
2516 (from->grid[cy * from->w + cx] == -2 ||
2517 from->grid[cy * from->w + cx] == -3)) {
2518 ret = dup_game(from);
2519 ret->just_used_solve = FALSE;
2520 open_square(ret, cx, cy);
2527 * Left-clicking or middle-clicking on an uncovered tile:
2528 * first we check to see if the number of mine markers
2529 * surrounding the tile is equal to its mine count, and if
2530 * so then we open all other surrounding squares.
2532 if (from->grid[cy * from->w + cx] > 0) {
2535 /* Count mine markers. */
2537 for (dy = -1; dy <= +1; dy++)
2538 for (dx = -1; dx <= +1; dx++)
2539 if (cx+dx >= 0 && cx+dx < from->w &&
2540 cy+dy >= 0 && cy+dy < from->h) {
2541 if (from->grid[(cy+dy)*from->w+(cx+dx)] == -1)
2545 if (n == from->grid[cy * from->w + cx]) {
2546 ret = dup_game(from);
2547 ret->just_used_solve = FALSE;
2548 for (dy = -1; dy <= +1; dy++)
2549 for (dx = -1; dx <= +1; dx++)
2550 if (cx+dx >= 0 && cx+dx < ret->w &&
2551 cy+dy >= 0 && cy+dy < ret->h &&
2552 (ret->grid[(cy+dy)*ret->w+(cx+dx)] == -2 ||
2553 ret->grid[(cy+dy)*ret->w+(cx+dx)] == -3))
2554 open_square(ret, cx+dx, cy+dy);
2567 /* ----------------------------------------------------------------------
2571 struct game_drawstate {
2575 * Items in this `grid' array have all the same values as in
2576 * the game_state grid, and in addition:
2578 * - -10 means the tile was drawn `specially' as a result of a
2579 * flash, so it will always need redrawing.
2581 * - -22 and -23 mean the tile is highlighted for a possible
2586 static void game_size(game_params *params, int *x, int *y)
2588 *x = BORDER * 2 + TILE_SIZE * params->w;
2589 *y = BORDER * 2 + TILE_SIZE * params->h;
2592 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2594 float *ret = snewn(3 * NCOLOURS, float);
2596 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2598 ret[COL_BACKGROUND2 * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 19.0 / 20.0;
2599 ret[COL_BACKGROUND2 * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 19.0 / 20.0;
2600 ret[COL_BACKGROUND2 * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 19.0 / 20.0;
2602 ret[COL_1 * 3 + 0] = 0.0F;
2603 ret[COL_1 * 3 + 1] = 0.0F;
2604 ret[COL_1 * 3 + 2] = 1.0F;
2606 ret[COL_2 * 3 + 0] = 0.0F;
2607 ret[COL_2 * 3 + 1] = 0.5F;
2608 ret[COL_2 * 3 + 2] = 0.0F;
2610 ret[COL_3 * 3 + 0] = 1.0F;
2611 ret[COL_3 * 3 + 1] = 0.0F;
2612 ret[COL_3 * 3 + 2] = 0.0F;
2614 ret[COL_4 * 3 + 0] = 0.0F;
2615 ret[COL_4 * 3 + 1] = 0.0F;
2616 ret[COL_4 * 3 + 2] = 0.5F;
2618 ret[COL_5 * 3 + 0] = 0.5F;
2619 ret[COL_5 * 3 + 1] = 0.0F;
2620 ret[COL_5 * 3 + 2] = 0.0F;
2622 ret[COL_6 * 3 + 0] = 0.0F;
2623 ret[COL_6 * 3 + 1] = 0.5F;
2624 ret[COL_6 * 3 + 2] = 0.5F;
2626 ret[COL_7 * 3 + 0] = 0.0F;
2627 ret[COL_7 * 3 + 1] = 0.0F;
2628 ret[COL_7 * 3 + 2] = 0.0F;
2630 ret[COL_8 * 3 + 0] = 0.5F;
2631 ret[COL_8 * 3 + 1] = 0.5F;
2632 ret[COL_8 * 3 + 2] = 0.5F;
2634 ret[COL_MINE * 3 + 0] = 0.0F;
2635 ret[COL_MINE * 3 + 1] = 0.0F;
2636 ret[COL_MINE * 3 + 2] = 0.0F;
2638 ret[COL_BANG * 3 + 0] = 1.0F;
2639 ret[COL_BANG * 3 + 1] = 0.0F;
2640 ret[COL_BANG * 3 + 2] = 0.0F;
2642 ret[COL_CROSS * 3 + 0] = 1.0F;
2643 ret[COL_CROSS * 3 + 1] = 0.0F;
2644 ret[COL_CROSS * 3 + 2] = 0.0F;
2646 ret[COL_FLAG * 3 + 0] = 1.0F;
2647 ret[COL_FLAG * 3 + 1] = 0.0F;
2648 ret[COL_FLAG * 3 + 2] = 0.0F;
2650 ret[COL_FLAGBASE * 3 + 0] = 0.0F;
2651 ret[COL_FLAGBASE * 3 + 1] = 0.0F;
2652 ret[COL_FLAGBASE * 3 + 2] = 0.0F;
2654 ret[COL_QUERY * 3 + 0] = 0.0F;
2655 ret[COL_QUERY * 3 + 1] = 0.0F;
2656 ret[COL_QUERY * 3 + 2] = 0.0F;
2658 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2659 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2660 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2662 ret[COL_LOWLIGHT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 2.0 / 3.0;
2663 ret[COL_LOWLIGHT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 2.0 / 3.0;
2664 ret[COL_LOWLIGHT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 2.0 / 3.0;
2666 *ncolours = NCOLOURS;
2670 static game_drawstate *game_new_drawstate(game_state *state)
2672 struct game_drawstate *ds = snew(struct game_drawstate);
2676 ds->started = FALSE;
2677 ds->grid = snewn(ds->w * ds->h, char);
2679 memset(ds->grid, -99, ds->w * ds->h);
2684 static void game_free_drawstate(game_drawstate *ds)
2690 static void draw_tile(frontend *fe, int x, int y, int v, int bg)
2696 if (v == -22 || v == -23) {
2700 * Omit the highlights in this case.
2702 draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2703 bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg);
2704 draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2705 draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2708 * Draw highlights to indicate the square is covered.
2710 coords[0] = x + TILE_SIZE - 1;
2711 coords[1] = y + TILE_SIZE - 1;
2712 coords[2] = x + TILE_SIZE - 1;
2715 coords[5] = y + TILE_SIZE - 1;
2716 draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT ^ hl);
2717 draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT ^ hl);
2721 draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT ^ hl);
2722 draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT ^ hl);
2724 draw_rect(fe, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
2725 TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
2733 #define SETCOORD(n, dx, dy) do { \
2734 coords[(n)*2+0] = x + TILE_SIZE * (dx); \
2735 coords[(n)*2+1] = y + TILE_SIZE * (dy); \
2737 SETCOORD(0, 0.6, 0.35);
2738 SETCOORD(1, 0.6, 0.7);
2739 SETCOORD(2, 0.8, 0.8);
2740 SETCOORD(3, 0.25, 0.8);
2741 SETCOORD(4, 0.55, 0.7);
2742 SETCOORD(5, 0.55, 0.35);
2743 draw_polygon(fe, coords, 6, TRUE, COL_FLAGBASE);
2744 draw_polygon(fe, coords, 6, FALSE, COL_FLAGBASE);
2746 SETCOORD(0, 0.6, 0.2);
2747 SETCOORD(1, 0.6, 0.5);
2748 SETCOORD(2, 0.2, 0.35);
2749 draw_polygon(fe, coords, 3, TRUE, COL_FLAG);
2750 draw_polygon(fe, coords, 3, FALSE, COL_FLAG);
2753 } else if (v == -3) {
2755 * Draw a question mark.
2757 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2758 FONT_VARIABLE, TILE_SIZE * 6 / 8,
2759 ALIGN_VCENTRE | ALIGN_HCENTRE,
2764 * Clear the square to the background colour, and draw thin
2765 * grid lines along the top and left.
2767 * Exception is that for value 65 (mine we've just trodden
2768 * on), we clear the square to COL_BANG.
2770 draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2771 (v == 65 ? COL_BANG :
2772 bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg));
2773 draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2774 draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2776 if (v > 0 && v <= 8) {
2783 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2784 FONT_VARIABLE, TILE_SIZE * 7 / 8,
2785 ALIGN_VCENTRE | ALIGN_HCENTRE,
2786 (COL_1 - 1) + v, str);
2788 } else if (v >= 64) {
2792 * FIXME: this could be done better!
2795 draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2796 FONT_VARIABLE, TILE_SIZE * 7 / 8,
2797 ALIGN_VCENTRE | ALIGN_HCENTRE,
2801 int cx = x + TILE_SIZE / 2;
2802 int cy = y + TILE_SIZE / 2;
2803 int r = TILE_SIZE / 2 - 3;
2805 int xdx = 1, xdy = 0, ydx = 0, ydy = 1;
2808 for (i = 0; i < 4*5*2; i += 5*2) {
2809 coords[i+2*0+0] = cx - r/6*xdx + r*4/5*ydx;
2810 coords[i+2*0+1] = cy - r/6*xdy + r*4/5*ydy;
2811 coords[i+2*1+0] = cx - r/6*xdx + r*ydx;
2812 coords[i+2*1+1] = cy - r/6*xdy + r*ydy;
2813 coords[i+2*2+0] = cx + r/6*xdx + r*ydx;
2814 coords[i+2*2+1] = cy + r/6*xdy + r*ydy;
2815 coords[i+2*3+0] = cx + r/6*xdx + r*4/5*ydx;
2816 coords[i+2*3+1] = cy + r/6*xdy + r*4/5*ydy;
2817 coords[i+2*4+0] = cx + r*3/5*xdx + r*3/5*ydx;
2818 coords[i+2*4+1] = cy + r*3/5*xdy + r*3/5*ydy;
2828 draw_polygon(fe, coords, 5*4, TRUE, COL_MINE);
2829 draw_polygon(fe, coords, 5*4, FALSE, COL_MINE);
2831 draw_rect(fe, cx-r/3, cy-r/3, r/3, r/4, COL_HIGHLIGHT);
2837 * Cross through the mine.
2840 for (dx = -1; dx <= +1; dx++) {
2841 draw_line(fe, x + 3 + dx, y + 2,
2842 x + TILE_SIZE - 3 + dx,
2843 y + TILE_SIZE - 2, COL_CROSS);
2844 draw_line(fe, x + TILE_SIZE - 3 + dx, y + 2,
2845 x + 3 + dx, y + TILE_SIZE - 2,
2852 draw_update(fe, x, y, TILE_SIZE, TILE_SIZE);
2855 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2856 game_state *state, int dir, game_ui *ui,
2857 float animtime, float flashtime)
2860 int mines, markers, bg;
2863 int frame = (flashtime / FLASH_FRAME);
2865 bg = (ui->flash_is_death ? COL_BACKGROUND : COL_LOWLIGHT);
2867 bg = (ui->flash_is_death ? COL_BANG : COL_HIGHLIGHT);
2869 bg = COL_BACKGROUND;
2875 TILE_SIZE * state->w + 2 * BORDER,
2876 TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
2877 draw_update(fe, 0, 0,
2878 TILE_SIZE * state->w + 2 * BORDER,
2879 TILE_SIZE * state->h + 2 * BORDER);
2882 * Recessed area containing the whole puzzle.
2884 coords[0] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2885 coords[1] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2886 coords[2] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2887 coords[3] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2888 coords[4] = coords[2] - TILE_SIZE;
2889 coords[5] = coords[3] + TILE_SIZE;
2890 coords[8] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2891 coords[9] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2892 coords[6] = coords[8] + TILE_SIZE;
2893 coords[7] = coords[9] - TILE_SIZE;
2894 draw_polygon(fe, coords, 5, TRUE, COL_HIGHLIGHT);
2895 draw_polygon(fe, coords, 5, FALSE, COL_HIGHLIGHT);
2897 coords[1] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2898 coords[0] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2899 draw_polygon(fe, coords, 5, TRUE, COL_LOWLIGHT);
2900 draw_polygon(fe, coords, 5, FALSE, COL_LOWLIGHT);
2906 * Now draw the tiles. Also in this loop, count up the number
2907 * of mines and mine markers.
2909 mines = markers = 0;
2910 for (y = 0; y < ds->h; y++)
2911 for (x = 0; x < ds->w; x++) {
2912 int v = state->grid[y*ds->w+x];
2916 if (state->layout->mines && state->layout->mines[y*ds->w+x])
2919 if ((v == -2 || v == -3) &&
2920 (abs(x-ui->hx) <= ui->hradius && abs(y-ui->hy) <= ui->hradius))
2923 if (ds->grid[y*ds->w+x] != v || bg != COL_BACKGROUND) {
2924 draw_tile(fe, COORD(x), COORD(y), v, bg);
2925 ds->grid[y*ds->w+x] = (bg == COL_BACKGROUND ? v : -10);
2929 if (!state->layout->mines)
2930 mines = state->layout->n;
2933 * Update the status bar.
2936 char statusbar[512];
2938 sprintf(statusbar, "DEAD!");
2939 } else if (state->won) {
2940 if (state->used_solve)
2941 sprintf(statusbar, "Auto-solved.");
2943 sprintf(statusbar, "COMPLETED!");
2945 sprintf(statusbar, "Marked: %d / %d", markers, mines);
2948 sprintf(statusbar + strlen(statusbar),
2949 " Deaths: %d", ui->deaths);
2950 status_bar(fe, statusbar);
2954 static float game_anim_length(game_state *oldstate, game_state *newstate,
2955 int dir, game_ui *ui)
2960 static float game_flash_length(game_state *oldstate, game_state *newstate,
2961 int dir, game_ui *ui)
2963 if (oldstate->used_solve || newstate->used_solve)
2966 if (dir > 0 && !oldstate->dead && !oldstate->won) {
2967 if (newstate->dead) {
2968 ui->flash_is_death = TRUE;
2969 return 3 * FLASH_FRAME;
2971 if (newstate->won) {
2972 ui->flash_is_death = FALSE;
2973 return 2 * FLASH_FRAME;
2979 static int game_wants_statusbar(void)
2984 static int game_timing_state(game_state *state)
2986 if (state->dead || state->won || !state->layout->mines)
2992 #define thegame mines
2995 const struct game thegame = {
2996 "Mines", "games.mines",
3003 TRUE, game_configure, custom_params,
3012 TRUE, game_text_format,
3019 game_free_drawstate,
3023 game_wants_statusbar,
3024 TRUE, game_timing_state,
3025 BUTTON_BEATS(LEFT_BUTTON, RIGHT_BUTTON),