2 * mines.c: Minesweeper clone with sophisticated grid generation.
6 * - possibly disable undo? Or alternatively mark game states as
7 * `cheated', although that's horrid.
8 * + OK. Rather than _disabling_ undo, we have a hook callable
9 * in the game backend which is called before we do an undo.
10 * That hook can talk to the game_ui and set the cheated flag,
11 * and then make_move can avoid setting the `won' flag after that.
13 * - delay game description generation until first click
14 * + do we actually _need_ to do this? Hmm.
15 * + it's a perfectly good puzzle game without
16 * + but it might be useful when we start timing, since it
17 * ensures the user is really paying attention.
21 * - question marks (arrgh, preferences?)
23 * - sensible parameter constraints
24 * + 30x16: 191 mines just about works if rather slowly, 192 is
25 * just about doom (the latter corresponding to a density of
27 * + 9x9: 45 mines works - over 1 in 2! 50 seems a bit slow.
28 * + it might not be feasible to work out the exact limit
43 COL_1
, COL_2
, COL_3
, COL_4
, COL_5
, COL_6
, COL_7
, COL_8
,
44 COL_MINE
, COL_BANG
, COL_CROSS
, COL_FLAG
, COL_FLAGBASE
, COL_QUERY
,
45 COL_HIGHLIGHT
, COL_LOWLIGHT
,
50 #define BORDER (TILE_SIZE * 3 / 2)
51 #define HIGHLIGHT_WIDTH 2
52 #define OUTER_HIGHLIGHT_WIDTH 3
53 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
54 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
56 #define FLASH_FRAME 0.13F
64 int w
, h
, n
, dead
, won
;
65 char *mines
; /* real mine positions */
66 char *grid
; /* player knowledge */
68 * Each item in the `grid' array is one of the following values:
70 * - 0 to 8 mean the square is open and has a surrounding mine
73 * - -1 means the square is marked as a mine.
75 * - -2 means the square is unknown.
77 * - -3 means the square is marked with a question mark
78 * (FIXME: do we even want to bother with this?).
80 * - 64 means the square has had a mine revealed when the game
83 * - 65 means the square had a mine revealed and this was the
84 * one the player hits.
86 * - 66 means the square has a crossed-out mine because the
87 * player had incorrectly marked it.
91 static game_params
*default_params(void)
93 game_params
*ret
= snew(game_params
);
102 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
106 static const struct { int w
, h
, n
; } values
[] = {
112 if (i
< 0 || i
>= lenof(values
))
115 ret
= snew(game_params
);
116 ret
->w
= values
[i
].w
;
117 ret
->h
= values
[i
].h
;
118 ret
->n
= values
[i
].n
;
121 sprintf(str
, "%dx%d, %d mines", ret
->w
, ret
->h
, ret
->n
);
128 static void free_params(game_params
*params
)
133 static game_params
*dup_params(game_params
*params
)
135 game_params
*ret
= snew(game_params
);
136 *ret
= *params
; /* structure copy */
140 static void decode_params(game_params
*params
, char const *string
)
142 char const *p
= string
;
145 while (*p
&& isdigit((unsigned char)*p
)) p
++;
149 while (*p
&& isdigit((unsigned char)*p
)) p
++;
151 params
->h
= params
->w
;
156 while (*p
&& (*p
== '.' || isdigit((unsigned char)*p
))) p
++;
158 params
->n
= params
->w
* params
->h
/ 10;
164 params
->unique
= FALSE
;
166 p
++; /* skip any other gunk */
170 static char *encode_params(game_params
*params
, int full
)
175 len
= sprintf(ret
, "%dx%d", params
->w
, params
->h
);
177 * Mine count is a generation-time parameter, since it can be
178 * deduced from the mine bitmap!
181 len
+= sprintf(ret
+len
, "n%d", params
->n
);
182 if (full
&& !params
->unique
)
184 assert(len
< lenof(ret
));
190 static config_item
*game_configure(game_params
*params
)
195 ret
= snewn(5, config_item
);
197 ret
[0].name
= "Width";
198 ret
[0].type
= C_STRING
;
199 sprintf(buf
, "%d", params
->w
);
200 ret
[0].sval
= dupstr(buf
);
203 ret
[1].name
= "Height";
204 ret
[1].type
= C_STRING
;
205 sprintf(buf
, "%d", params
->h
);
206 ret
[1].sval
= dupstr(buf
);
209 ret
[2].name
= "Mines";
210 ret
[2].type
= C_STRING
;
211 sprintf(buf
, "%d", params
->n
);
212 ret
[2].sval
= dupstr(buf
);
215 ret
[3].name
= "Ensure solubility";
216 ret
[3].type
= C_BOOLEAN
;
218 ret
[3].ival
= params
->unique
;
228 static game_params
*custom_params(config_item
*cfg
)
230 game_params
*ret
= snew(game_params
);
232 ret
->w
= atoi(cfg
[0].sval
);
233 ret
->h
= atoi(cfg
[1].sval
);
234 ret
->n
= atoi(cfg
[2].sval
);
235 ret
->unique
= cfg
[3].ival
;
240 static char *validate_params(game_params
*params
)
242 if (params
->w
<= 0 && params
->h
<= 0)
243 return "Width and height must both be greater than zero";
245 return "Width must be greater than zero";
247 return "Height must be greater than zero";
250 * FIXME: Need more constraints here. Not sure what the
251 * sensible limits for Minesweeper actually are. The limits
252 * probably ought to change, however, depending on uniqueness.
258 /* ----------------------------------------------------------------------
259 * Minesweeper solver, used to ensure the generated grids are
260 * solvable without having to take risks.
264 * Count the bits in a word. Only needs to cope with 16 bits.
266 static int bitcount16(int word
)
268 word
= ((word
& 0xAAAA) >> 1) + (word
& 0x5555);
269 word
= ((word
& 0xCCCC) >> 2) + (word
& 0x3333);
270 word
= ((word
& 0xF0F0) >> 4) + (word
& 0x0F0F);
271 word
= ((word
& 0xFF00) >> 8) + (word
& 0x00FF);
277 * We use a tree234 to store a large number of small localised
278 * sets, each with a mine count. We also keep some of those sets
279 * linked together into a to-do list.
282 short x
, y
, mask
, mines
;
284 struct set
*prev
, *next
;
287 static int setcmp(void *av
, void *bv
)
289 struct set
*a
= (struct set
*)av
;
290 struct set
*b
= (struct set
*)bv
;
294 else if (a
->y
> b
->y
)
296 else if (a
->x
< b
->x
)
298 else if (a
->x
> b
->x
)
300 else if (a
->mask
< b
->mask
)
302 else if (a
->mask
> b
->mask
)
310 struct set
*todo_head
, *todo_tail
;
313 static struct setstore
*ss_new(void)
315 struct setstore
*ss
= snew(struct setstore
);
316 ss
->sets
= newtree234(setcmp
);
317 ss
->todo_head
= ss
->todo_tail
= NULL
;
322 * Take two input sets, in the form (x,y,mask). Munge the first by
323 * taking either its intersection with the second or its difference
324 * with the second. Return the new mask part of the first set.
326 static int setmunge(int x1
, int y1
, int mask1
, int x2
, int y2
, int mask2
,
330 * Adjust the second set so that it has the same x,y
331 * coordinates as the first.
333 if (abs(x2
-x1
) >= 3 || abs(y2
-y1
) >= 3) {
337 mask2
&= ~(4|32|256);
347 mask2
&= ~(64|128|256);
359 * Invert the second set if `diff' is set (we're after A &~ B
360 * rather than A & B).
366 * Now all that's left is a logical AND.
368 return mask1
& mask2
;
371 static void ss_add_todo(struct setstore
*ss
, struct set
*s
)
374 return; /* already on it */
376 #ifdef SOLVER_DIAGNOSTICS
377 printf("adding set on todo list: %d,%d %03x %d\n",
378 s
->x
, s
->y
, s
->mask
, s
->mines
);
381 s
->prev
= ss
->todo_tail
;
391 static void ss_add(struct setstore
*ss
, int x
, int y
, int mask
, int mines
)
398 * Normalise so that x and y are genuinely the bounding
401 while (!(mask
& (1|8|64)))
403 while (!(mask
& (1|2|4)))
407 * Create a set structure and add it to the tree.
409 s
= snew(struct set
);
415 if (add234(ss
->sets
, s
) != s
) {
417 * This set already existed! Free it and return.
424 * We've added a new set to the tree, so put it on the todo
430 static void ss_remove(struct setstore
*ss
, struct set
*s
)
432 struct set
*next
= s
->next
, *prev
= s
->prev
;
434 #ifdef SOLVER_DIAGNOSTICS
435 printf("removing set %d,%d %03x\n", s
->x
, s
->y
, s
->mask
);
438 * Remove s from the todo list.
442 else if (s
== ss
->todo_head
)
443 ss
->todo_head
= next
;
447 else if (s
== ss
->todo_tail
)
448 ss
->todo_tail
= prev
;
453 * Remove s from the tree.
458 * Destroy the actual set structure.
464 * Return a dynamically allocated list of all the sets which
465 * overlap a provided input set.
467 static struct set
**ss_overlap(struct setstore
*ss
, int x
, int y
, int mask
)
469 struct set
**ret
= NULL
;
470 int nret
= 0, retsize
= 0;
473 for (xx
= x
-3; xx
< x
+3; xx
++)
474 for (yy
= y
-3; yy
< y
+3; yy
++) {
479 * Find the first set with these top left coordinates.
485 if (findrelpos234(ss
->sets
, &stmp
, NULL
, REL234_GE
, &pos
)) {
486 while ((s
= index234(ss
->sets
, pos
)) != NULL
&&
487 s
->x
== xx
&& s
->y
== yy
) {
489 * This set potentially overlaps the input one.
490 * Compute the intersection to see if they
491 * really overlap, and add it to the list if
494 if (setmunge(x
, y
, mask
, s
->x
, s
->y
, s
->mask
, FALSE
)) {
496 * There's an overlap.
498 if (nret
>= retsize
) {
500 ret
= sresize(ret
, retsize
, struct set
*);
510 ret
= sresize(ret
, nret
+1, struct set
*);
517 * Get an element from the head of the set todo list.
519 static struct set
*ss_todo(struct setstore
*ss
)
522 struct set
*ret
= ss
->todo_head
;
523 ss
->todo_head
= ret
->next
;
525 ss
->todo_head
->prev
= NULL
;
527 ss
->todo_tail
= NULL
;
528 ret
->next
= ret
->prev
= NULL
;
541 static void std_add(struct squaretodo
*std
, int i
)
544 std
->next
[std
->tail
] = i
;
551 static void known_squares(int w
, int h
, struct squaretodo
*std
, char *grid
,
552 int (*open
)(void *ctx
, int x
, int y
), void *openctx
,
553 int x
, int y
, int mask
, int mine
)
559 for (yy
= 0; yy
< 3; yy
++)
560 for (xx
= 0; xx
< 3; xx
++) {
562 int i
= (y
+ yy
) * w
+ (x
+ xx
);
565 * It's possible that this square is _already_
566 * known, in which case we don't try to add it to
572 grid
[i
] = -1; /* and don't open it! */
574 grid
[i
] = open(openctx
, x
+ xx
, y
+ yy
);
575 assert(grid
[i
] != -1); /* *bang* */
586 * This is data returned from the `perturb' function. It details
587 * which squares have become mines and which have become clear. The
588 * solver is (of course) expected to honourably not use that
589 * knowledge directly, but to efficently adjust its internal data
590 * structures and proceed based on only the information it
593 struct perturbation
{
595 int delta
; /* +1 == become a mine; -1 == cleared */
597 struct perturbations
{
599 struct perturbation
*changes
;
603 * Main solver entry point. You give it a grid of existing
604 * knowledge (-1 for a square known to be a mine, 0-8 for empty
605 * squares with a given number of neighbours, -2 for completely
606 * unknown), plus a function which you can call to open new squares
607 * once you're confident of them. It fills in as much more of the
612 * - -1 means deduction stalled and nothing could be done
613 * - 0 means deduction succeeded fully
614 * - >0 means deduction succeeded but some number of perturbation
615 * steps were required; the exact return value is the number of
618 static int minesolve(int w
, int h
, int n
, char *grid
,
619 int (*open
)(void *ctx
, int x
, int y
),
620 struct perturbations
*(*perturb
)(void *ctx
, char *grid
,
621 int x
, int y
, int mask
),
622 void *ctx
, random_state
*rs
)
624 struct setstore
*ss
= ss_new();
626 struct squaretodo astd
, *std
= &astd
;
631 * Set up a linked list of squares with known contents, so that
632 * we can process them one by one.
634 std
->next
= snewn(w
*h
, int);
635 std
->head
= std
->tail
= -1;
638 * Initialise that list with all known squares in the input
641 for (y
= 0; y
< h
; y
++) {
642 for (x
= 0; x
< w
; x
++) {
650 * Main deductive loop.
653 int done_something
= FALSE
;
657 * If there are any known squares on the todo list, process
658 * them and construct a set for each.
660 while (std
->head
!= -1) {
662 #ifdef SOLVER_DIAGNOSTICS
663 printf("known square at %d,%d [%d]\n", i
%w
, i
/w
, grid
[i
]);
665 std
->head
= std
->next
[i
];
673 int dx
, dy
, mines
, bit
, val
;
674 #ifdef SOLVER_DIAGNOSTICS
675 printf("creating set around this square\n");
678 * Empty square. Construct the set of non-known squares
679 * around this one, and determine its mine count.
684 for (dy
= -1; dy
<= +1; dy
++) {
685 for (dx
= -1; dx
<= +1; dx
++) {
686 #ifdef SOLVER_DIAGNOSTICS
687 printf("grid %d,%d = %d\n", x
+dx
, y
+dy
, grid
[i
+dy
*w
+dx
]);
689 if (x
+dx
< 0 || x
+dx
>= w
|| y
+dy
< 0 || y
+dy
>= h
)
690 /* ignore this one */;
691 else if (grid
[i
+dy
*w
+dx
] == -1)
693 else if (grid
[i
+dy
*w
+dx
] == -2)
699 ss_add(ss
, x
-1, y
-1, val
, mines
);
703 * Now, whether the square is empty or full, we must
704 * find any set which contains it and replace it with
705 * one which does not.
708 #ifdef SOLVER_DIAGNOSTICS
709 printf("finding sets containing known square %d,%d\n", x
, y
);
711 list
= ss_overlap(ss
, x
, y
, 1);
713 for (j
= 0; list
[j
]; j
++) {
714 int newmask
, newmines
;
719 * Compute the mask for this set minus the
720 * newly known square.
722 newmask
= setmunge(s
->x
, s
->y
, s
->mask
, x
, y
, 1, TRUE
);
725 * Compute the new mine count.
727 newmines
= s
->mines
- (grid
[i
] == -1);
730 * Insert the new set into the collection,
731 * unless it's been whittled right down to
735 ss_add(ss
, s
->x
, s
->y
, newmask
, newmines
);
738 * Destroy the old one; it is actually obsolete.
747 * Marking a fresh square as known certainly counts as
750 done_something
= TRUE
;
754 * Now pick a set off the to-do list and attempt deductions
757 if ((s
= ss_todo(ss
)) != NULL
) {
759 #ifdef SOLVER_DIAGNOSTICS
760 printf("set to do: %d,%d %03x %d\n", s
->x
, s
->y
, s
->mask
, s
->mines
);
763 * Firstly, see if this set has a mine count of zero or
764 * of its own cardinality.
766 if (s
->mines
== 0 || s
->mines
== bitcount16(s
->mask
)) {
768 * If so, we can immediately mark all the squares
769 * in the set as known.
771 #ifdef SOLVER_DIAGNOSTICS
774 known_squares(w
, h
, std
, grid
, open
, ctx
,
775 s
->x
, s
->y
, s
->mask
, (s
->mines
!= 0));
778 * Having done that, we need do nothing further
779 * with this set; marking all the squares in it as
780 * known will eventually eliminate it, and will
781 * also permit further deductions about anything
788 * Failing that, we now search through all the sets
789 * which overlap this one.
791 list
= ss_overlap(ss
, s
->x
, s
->y
, s
->mask
);
793 for (j
= 0; list
[j
]; j
++) {
794 struct set
*s2
= list
[j
];
795 int swing
, s2wing
, swc
, s2wc
;
798 * Find the non-overlapping parts s2-s and s-s2,
799 * and their cardinalities.
801 * I'm going to refer to these parts as `wings'
802 * surrounding the central part common to both
803 * sets. The `s wing' is s-s2; the `s2 wing' is
806 swing
= setmunge(s
->x
, s
->y
, s
->mask
, s2
->x
, s2
->y
, s2
->mask
,
808 s2wing
= setmunge(s2
->x
, s2
->y
, s2
->mask
, s
->x
, s
->y
, s
->mask
,
810 swc
= bitcount16(swing
);
811 s2wc
= bitcount16(s2wing
);
814 * If one set has more mines than the other, and
815 * the number of extra mines is equal to the
816 * cardinality of that set's wing, then we can mark
817 * every square in the wing as a known mine, and
818 * every square in the other wing as known clear.
820 if (swc
== s
->mines
- s2
->mines
||
821 s2wc
== s2
->mines
- s
->mines
) {
822 known_squares(w
, h
, std
, grid
, open
, ctx
,
824 (swc
== s
->mines
- s2
->mines
));
825 known_squares(w
, h
, std
, grid
, open
, ctx
,
826 s2
->x
, s2
->y
, s2wing
,
827 (s2wc
== s2
->mines
- s
->mines
));
832 * Failing that, see if one set is a subset of the
833 * other. If so, we can divide up the mine count of
834 * the larger set between the smaller set and its
835 * complement, even if neither smaller set ends up
836 * being immediately clearable.
838 if (swc
== 0 && s2wc
!= 0) {
839 /* s is a subset of s2. */
840 assert(s2
->mines
> s
->mines
);
841 ss_add(ss
, s2
->x
, s2
->y
, s2wing
, s2
->mines
- s
->mines
);
842 } else if (s2wc
== 0 && swc
!= 0) {
843 /* s2 is a subset of s. */
844 assert(s
->mines
> s2
->mines
);
845 ss_add(ss
, s
->x
, s
->y
, swing
, s
->mines
- s2
->mines
);
852 * In this situation we have definitely done
853 * _something_, even if it's only reducing the size of
856 done_something
= TRUE
;
859 * We have nothing left on our todo list, which means
860 * all localised deductions have failed. Our next step
861 * is to resort to global deduction based on the total
862 * mine count. This is computationally expensive
863 * compared to any of the above deductions, which is
864 * why we only ever do it when all else fails, so that
865 * hopefully it won't have to happen too often.
867 * If you pass n<0 into this solver, that informs it
868 * that you do not know the total mine count, so it
869 * won't even attempt these deductions.
872 int minesleft
, squaresleft
;
873 int nsets
, setused
[10], cursor
;
876 * Start by scanning the current grid state to work out
877 * how many unknown squares we still have, and how many
878 * mines are to be placed in them.
882 for (i
= 0; i
< w
*h
; i
++) {
885 else if (grid
[i
] == -2)
889 #ifdef SOLVER_DIAGNOSTICS
890 printf("global deduction time: squaresleft=%d minesleft=%d\n",
891 squaresleft
, minesleft
);
892 for (y
= 0; y
< h
; y
++) {
893 for (x
= 0; x
< w
; x
++) {
909 * If there _are_ no unknown squares, we have actually
912 if (squaresleft
== 0) {
913 assert(minesleft
== 0);
918 * First really simple case: if there are no more mines
919 * left, or if there are exactly as many mines left as
920 * squares to play them in, then it's all easy.
922 if (minesleft
== 0 || minesleft
== squaresleft
) {
923 for (i
= 0; i
< w
*h
; i
++)
925 known_squares(w
, h
, std
, grid
, open
, ctx
,
926 i
% w
, i
/ w
, 1, minesleft
!= 0);
927 continue; /* now go back to main deductive loop */
931 * Failing that, we have to do some _real_ work.
932 * Ideally what we do here is to try every single
933 * combination of the currently available sets, in an
934 * attempt to find a disjoint union (i.e. a set of
935 * squares with a known mine count between them) such
936 * that the remaining unknown squares _not_ contained
937 * in that union either contain no mines or are all
940 * Actually enumerating all 2^n possibilities will get
941 * a bit slow for large n, so I artificially cap this
942 * recursion at n=10 to avoid too much pain.
944 nsets
= count234(ss
->sets
);
945 if (nsets
<= lenof(setused
)) {
947 * Doing this with actual recursive function calls
948 * would get fiddly because a load of local
949 * variables from this function would have to be
950 * passed down through the recursion. So instead
951 * I'm going to use a virtual recursion within this
952 * function. The way this works is:
954 * - we have an array `setused', such that
955 * setused[n] is 0 or 1 depending on whether set
956 * n is currently in the union we are
959 * - we have a value `cursor' which indicates how
960 * much of `setused' we have so far filled in.
961 * It's conceptually the recursion depth.
963 * We begin by setting `cursor' to zero. Then:
965 * - if cursor can advance, we advance it by one.
966 * We set the value in `setused' that it went
967 * past to 1 if that set is disjoint from
968 * anything else currently in `setused', or to 0
971 * - If cursor cannot advance because it has
972 * reached the end of the setused list, then we
973 * have a maximal disjoint union. Check to see
974 * whether its mine count has any useful
975 * properties. If so, mark all the squares not
976 * in the union as known and terminate.
978 * - If cursor has reached the end of setused and
979 * the algorithm _hasn't_ terminated, back
980 * cursor up to the nearest 1, turn it into a 0
981 * and advance cursor just past it.
983 * - If we attempt to back up to the nearest 1 and
984 * there isn't one at all, then we have gone
985 * through all disjoint unions of sets in the
986 * list and none of them has been helpful, so we
989 struct set
*sets
[lenof(setused
)];
990 for (i
= 0; i
< nsets
; i
++)
991 sets
[i
] = index234(ss
->sets
, i
);
996 if (cursor
< nsets
) {
999 /* See if any existing set overlaps this one. */
1000 for (i
= 0; i
< cursor
; i
++)
1002 setmunge(sets
[cursor
]->x
,
1005 sets
[i
]->x
, sets
[i
]->y
, sets
[i
]->mask
,
1013 * We're adding this set to our union,
1014 * so adjust minesleft and squaresleft
1017 minesleft
-= sets
[cursor
]->mines
;
1018 squaresleft
-= bitcount16(sets
[cursor
]->mask
);
1021 setused
[cursor
++] = ok
;
1023 #ifdef SOLVER_DIAGNOSTICS
1024 printf("trying a set combination with %d %d\n",
1025 squaresleft
, minesleft
);
1026 #endif SOLVER_DIAGNOSTICS
1029 * We've reached the end. See if we've got
1030 * anything interesting.
1032 if (squaresleft
> 0 &&
1033 (minesleft
== 0 || minesleft
== squaresleft
)) {
1035 * We have! There is at least one
1036 * square not contained within the set
1037 * union we've just found, and we can
1038 * deduce that either all such squares
1039 * are mines or all are not (depending
1040 * on whether minesleft==0). So now all
1041 * we have to do is actually go through
1042 * the grid, find those squares, and
1045 for (i
= 0; i
< w
*h
; i
++)
1046 if (grid
[i
] == -2) {
1050 for (j
= 0; j
< nsets
; j
++)
1052 setmunge(sets
[j
]->x
, sets
[j
]->y
,
1053 sets
[j
]->mask
, x
, y
, 1,
1059 known_squares(w
, h
, std
, grid
,
1061 x
, y
, 1, minesleft
!= 0);
1064 done_something
= TRUE
;
1065 break; /* return to main deductive loop */
1069 * If we reach here, then this union hasn't
1070 * done us any good, so move on to the
1071 * next. Backtrack cursor to the nearest 1,
1072 * change it to a 0 and continue.
1074 while (cursor
-- >= 0 && !setused
[cursor
]);
1076 assert(setused
[cursor
]);
1079 * We're removing this set from our
1080 * union, so re-increment minesleft and
1083 minesleft
+= sets
[cursor
]->mines
;
1084 squaresleft
+= bitcount16(sets
[cursor
]->mask
);
1086 setused
[cursor
++] = 0;
1089 * We've backtracked all the way to the
1090 * start without finding a single 1,
1091 * which means that our virtual
1092 * recursion is complete and nothing
1107 #ifdef SOLVER_DIAGNOSTICS
1109 * Dump the current known state of the grid.
1111 printf("solver ran out of steam, ret=%d, grid:\n", nperturbs
);
1112 for (y
= 0; y
< h
; y
++) {
1113 for (x
= 0; x
< w
; x
++) {
1114 int v
= grid
[y
*w
+x
];
1130 for (i
= 0; (s
= index234(ss
->sets
, i
)) != NULL
; i
++)
1131 printf("remaining set: %d,%d %03x %d\n", s
->x
, s
->y
, s
->mask
, s
->mines
);
1136 * Now we really are at our wits' end as far as solving
1137 * this grid goes. Our only remaining option is to call
1138 * a perturb function and ask it to modify the grid to
1142 struct perturbations
*ret
;
1148 * Choose a set at random from the current selection,
1149 * and ask the perturb function to either fill or empty
1152 * If we have no sets at all, we must give up.
1154 if (count234(ss
->sets
) == 0)
1156 s
= index234(ss
->sets
, random_upto(rs
, count234(ss
->sets
)));
1157 #ifdef SOLVER_DIAGNOSTICS
1158 printf("perturbing on set %d,%d %03x\n", s
->x
, s
->y
, s
->mask
);
1160 ret
= perturb(ctx
, grid
, s
->x
, s
->y
, s
->mask
);
1163 assert(ret
->n
> 0); /* otherwise should have been NULL */
1166 * A number of squares have been fiddled with, and
1167 * the returned structure tells us which. Adjust
1168 * the mine count in any set which overlaps one of
1169 * those squares, and put them back on the to-do
1172 for (i
= 0; i
< ret
->n
; i
++) {
1173 #ifdef SOLVER_DIAGNOSTICS
1174 printf("perturbation %s mine at %d,%d\n",
1175 ret
->changes
[i
].delta
> 0 ?
"added" : "removed",
1176 ret
->changes
[i
].x
, ret
->changes
[i
].y
);
1179 list
= ss_overlap(ss
,
1180 ret
->changes
[i
].x
, ret
->changes
[i
].y
, 1);
1182 for (j
= 0; list
[j
]; j
++) {
1183 list
[j
]->mines
+= ret
->changes
[i
].delta
;
1184 ss_add_todo(ss
, list
[j
]);
1191 * Now free the returned data.
1193 sfree(ret
->changes
);
1196 #ifdef SOLVER_DIAGNOSTICS
1198 * Dump the current known state of the grid.
1200 printf("state after perturbation:\n", nperturbs
);
1201 for (y
= 0; y
< h
; y
++) {
1202 for (x
= 0; x
< w
; x
++) {
1203 int v
= grid
[y
*w
+x
];
1219 for (i
= 0; (s
= index234(ss
->sets
, i
)) != NULL
; i
++)
1220 printf("remaining set: %d,%d %03x %d\n", s
->x
, s
->y
, s
->mask
, s
->mines
);
1225 * And now we can go back round the deductive loop.
1232 * If we get here, even that didn't work (either we didn't
1233 * have a perturb function or it returned failure), so we
1240 * See if we've got any unknown squares left.
1242 for (y
= 0; y
< h
; y
++)
1243 for (x
= 0; x
< w
; x
++)
1244 if (grid
[y
*w
+x
] == -2) {
1245 nperturbs
= -1; /* failed to complete */
1250 * Free the set list and square-todo list.
1254 while ((s
= delpos234(ss
->sets
, 0)) != NULL
)
1256 freetree234(ss
->sets
);
1264 /* ----------------------------------------------------------------------
1265 * Grid generator which uses the above solver.
1275 static int mineopen(void *vctx
, int x
, int y
)
1277 struct minectx
*ctx
= (struct minectx
*)vctx
;
1280 assert(x
>= 0 && x
< ctx
->w
&& y
>= 0 && y
< ctx
->h
);
1281 if (ctx
->grid
[y
* ctx
->w
+ x
])
1282 return -1; /* *bang* */
1285 for (i
= -1; i
<= +1; i
++) {
1286 if (x
+ i
< 0 || x
+ i
>= ctx
->w
)
1288 for (j
= -1; j
<= +1; j
++) {
1289 if (y
+ j
< 0 || y
+ j
>= ctx
->h
)
1291 if (i
== 0 && j
== 0)
1293 if (ctx
->grid
[(y
+j
) * ctx
->w
+ (x
+i
)])
1301 /* Structure used internally to mineperturb(). */
1303 int x
, y
, type
, random
;
1305 static int squarecmp(const void *av
, const void *bv
)
1307 const struct square
*a
= (const struct square
*)av
;
1308 const struct square
*b
= (const struct square
*)bv
;
1309 if (a
->type
< b
->type
)
1311 else if (a
->type
> b
->type
)
1313 else if (a
->random
< b
->random
)
1315 else if (a
->random
> b
->random
)
1317 else if (a
->y
< b
->y
)
1319 else if (a
->y
> b
->y
)
1321 else if (a
->x
< b
->x
)
1323 else if (a
->x
> b
->x
)
1328 static struct perturbations
*mineperturb(void *vctx
, char *grid
,
1329 int setx
, int sety
, int mask
)
1331 struct minectx
*ctx
= (struct minectx
*)vctx
;
1332 struct square
*sqlist
;
1333 int x
, y
, dx
, dy
, i
, n
, nfull
, nempty
;
1334 struct square
*tofill
[9], *toempty
[9], **todo
;
1335 int ntofill
, ntoempty
, ntodo
, dtodo
, dset
;
1336 struct perturbations
*ret
;
1339 * Make a list of all the squares in the grid which we can
1340 * possibly use. This list should be in preference order, which
1343 * - first, unknown squares on the boundary of known space
1344 * - next, unknown squares beyond that boundary
1345 * - as a very last resort, known squares, but not within one
1346 * square of the starting position.
1348 * Each of these sections needs to be shuffled independently.
1349 * We do this by preparing list of all squares and then sorting
1350 * it with a random secondary key.
1352 sqlist
= snewn(ctx
->w
* ctx
->h
, struct square
);
1354 for (y
= 0; y
< ctx
->h
; y
++)
1355 for (x
= 0; x
< ctx
->w
; x
++) {
1357 * If this square is too near the starting position,
1358 * don't put it on the list at all.
1360 if (abs(y
- ctx
->sy
) <= 1 && abs(x
- ctx
->sx
) <= 1)
1364 * If this square is in the input set, also don't put
1367 if (x
>= setx
&& x
< setx
+ 3 &&
1368 y
>= sety
&& y
< sety
+ 3 &&
1369 mask
& (1 << ((y
-sety
)*3+(x
-setx
))))
1375 if (grid
[y
*ctx
->w
+x
] != -2) {
1376 sqlist
[n
].type
= 3; /* known square */
1379 * Unknown square. Examine everything around it and
1380 * see if it borders on any known squares. If it
1381 * does, it's class 1, otherwise it's 2.
1386 for (dy
= -1; dy
<= +1; dy
++)
1387 for (dx
= -1; dx
<= +1; dx
++)
1388 if (x
+dx
>= 0 && x
+dx
< ctx
->w
&&
1389 y
+dy
>= 0 && y
+dy
< ctx
->h
&&
1390 grid
[(y
+dy
)*ctx
->w
+(x
+dx
)] != -2) {
1397 * Finally, a random number to cause qsort to
1398 * shuffle within each group.
1400 sqlist
[n
].random
= random_bits(ctx
->rs
, 31);
1405 qsort(sqlist
, n
, sizeof(struct square
), squarecmp
);
1408 * Now count up the number of full and empty squares in the set
1409 * we've been provided.
1412 for (dy
= 0; dy
< 3; dy
++)
1413 for (dx
= 0; dx
< 3; dx
++)
1414 if (mask
& (1 << (dy
*3+dx
))) {
1415 assert(setx
+dx
<= ctx
->w
);
1416 assert(sety
+dy
<= ctx
->h
);
1417 if (ctx
->grid
[(sety
+dy
)*ctx
->w
+(setx
+dx
)])
1424 * Now go through our sorted list until we find either `nfull'
1425 * empty squares, or `nempty' full squares; these will be
1426 * swapped with the appropriate squares in the set to either
1427 * fill or empty the set while keeping the same number of mines
1430 ntofill
= ntoempty
= 0;
1431 for (i
= 0; i
< n
; i
++) {
1432 struct square
*sq
= &sqlist
[i
];
1433 if (ctx
->grid
[sq
->y
* ctx
->w
+ sq
->x
])
1434 toempty
[ntoempty
++] = sq
;
1436 tofill
[ntofill
++] = sq
;
1437 if (ntofill
== nfull
|| ntoempty
== nempty
)
1442 * If this didn't work at all, I think we just give up.
1444 if (ntofill
!= nfull
&& ntoempty
!= nempty
) {
1450 * Now we're pretty much there. We need to either
1451 * (a) put a mine in each of the empty squares in the set, and
1452 * take one out of each square in `toempty'
1453 * (b) take a mine out of each of the full squares in the set,
1454 * and put one in each square in `tofill'
1455 * depending on which one we've found enough squares to do.
1457 * So we start by constructing our list of changes to return to
1458 * the solver, so that it can update its data structures
1459 * efficiently rather than having to rescan the whole grid.
1461 ret
= snew(struct perturbations
);
1462 if (ntofill
== nfull
) {
1474 ret
->changes
= snewn(ret
->n
, struct perturbation
);
1475 for (i
= 0; i
< ntodo
; i
++) {
1476 ret
->changes
[i
].x
= todo
[i
]->x
;
1477 ret
->changes
[i
].y
= todo
[i
]->y
;
1478 ret
->changes
[i
].delta
= dtodo
;
1480 /* now i == ntodo */
1481 for (dy
= 0; dy
< 3; dy
++)
1482 for (dx
= 0; dx
< 3; dx
++)
1483 if (mask
& (1 << (dy
*3+dx
))) {
1484 int currval
= (ctx
->grid
[(sety
+dy
)*ctx
->w
+(setx
+dx
)] ?
+1 : -1);
1485 if (dset
== -currval
) {
1486 ret
->changes
[i
].x
= setx
+ dx
;
1487 ret
->changes
[i
].y
= sety
+ dy
;
1488 ret
->changes
[i
].delta
= dset
;
1492 assert(i
== ret
->n
);
1497 * Having set up the precise list of changes we're going to
1498 * make, we now simply make them and return.
1500 for (i
= 0; i
< ret
->n
; i
++) {
1503 x
= ret
->changes
[i
].x
;
1504 y
= ret
->changes
[i
].y
;
1505 delta
= ret
->changes
[i
].delta
;
1508 * Check we're not trying to add an existing mine or remove
1511 assert((delta
< 0) ^ (ctx
->grid
[y
*ctx
->w
+x
] == 0));
1514 * Actually make the change.
1516 ctx
->grid
[y
*ctx
->w
+x
] = (delta
> 0);
1519 * Update any numbers already present in the grid.
1521 for (dy
= -1; dy
<= +1; dy
++)
1522 for (dx
= -1; dx
<= +1; dx
++)
1523 if (x
+dx
>= 0 && x
+dx
< ctx
->w
&&
1524 y
+dy
>= 0 && y
+dy
< ctx
->h
&&
1525 grid
[(y
+dy
)*ctx
->w
+(x
+dx
)] != -2) {
1526 if (dx
== 0 && dy
== 0) {
1528 * The square itself is marked as known in
1529 * the grid. Mark it as a mine if it's a
1530 * mine, or else work out its number.
1533 grid
[y
*ctx
->w
+x
] = -1;
1535 int dx2
, dy2
, minecount
= 0;
1536 for (dy2
= -1; dy2
<= +1; dy2
++)
1537 for (dx2
= -1; dx2
<= +1; dx2
++)
1538 if (x
+dx2
>= 0 && x
+dx2
< ctx
->w
&&
1539 y
+dy2
>= 0 && y
+dy2
< ctx
->h
&&
1540 ctx
->grid
[(y
+dy2
)*ctx
->w
+(x
+dx2
)])
1542 grid
[y
*ctx
->w
+x
] = minecount
;
1545 if (grid
[(y
+dy
)*ctx
->w
+(x
+dx
)] >= 0)
1546 grid
[(y
+dy
)*ctx
->w
+(x
+dx
)] += delta
;
1551 #ifdef GENERATION_DIAGNOSTICS
1554 printf("grid after perturbing:\n");
1555 for (yy
= 0; yy
< ctx
->h
; yy
++) {
1556 for (xx
= 0; xx
< ctx
->w
; xx
++) {
1557 int v
= ctx
->grid
[yy
*ctx
->w
+xx
];
1558 if (yy
== ctx
->sy
&& xx
== ctx
->sx
) {
1576 static char *minegen(int w
, int h
, int n
, int x
, int y
, int unique
,
1579 char *ret
= snewn(w
*h
, char);
1585 memset(ret
, 0, w
*h
);
1588 * Start by placing n mines, none of which is at x,y or within
1592 int *tmp
= snewn(w
*h
, int);
1596 * Write down the list of possible mine locations.
1599 for (i
= 0; i
< h
; i
++)
1600 for (j
= 0; j
< w
; j
++)
1601 if (abs(i
- y
) > 1 || abs(j
- x
) > 1)
1605 * Now pick n off the list at random.
1609 i
= random_upto(rs
, k
);
1617 #ifdef GENERATION_DIAGNOSTICS
1620 printf("grid after initial generation:\n");
1621 for (yy
= 0; yy
< h
; yy
++) {
1622 for (xx
= 0; xx
< w
; xx
++) {
1623 int v
= ret
[yy
*w
+xx
];
1624 if (yy
== y
&& xx
== x
) {
1640 * Now set up a results grid to run the solver in, and a
1641 * context for the solver to open squares. Then run the solver
1642 * repeatedly; if the number of perturb steps ever goes up or
1643 * it ever returns -1, give up completely.
1645 * We bypass this bit if we're not after a unique grid.
1648 char *solvegrid
= snewn(w
*h
, char);
1649 struct minectx actx
, *ctx
= &actx
;
1650 int solveret
, prevret
= -2;
1660 memset(solvegrid
, -2, w
*h
);
1661 solvegrid
[y
*w
+x
] = mineopen(ctx
, x
, y
);
1662 assert(solvegrid
[y
*w
+x
] == 0); /* by deliberate arrangement */
1665 minesolve(w
, h
, n
, solvegrid
, mineopen
, mineperturb
, ctx
, rs
);
1666 if (solveret
< 0 || (prevret
>= 0 && solveret
>= prevret
)) {
1669 } else if (solveret
== 0) {
1686 * The Mines game descriptions contain the location of every mine,
1687 * and can therefore be used to cheat.
1689 * It would be pointless to attempt to _prevent_ this form of
1690 * cheating by encrypting the description, since Mines is
1691 * open-source so anyone can find out the encryption key. However,
1692 * I think it is worth doing a bit of gentle obfuscation to prevent
1693 * _accidental_ spoilers: if you happened to note that the game ID
1694 * starts with an F, for example, you might be unable to put the
1695 * knowledge of those mines out of your mind while playing. So,
1696 * just as discussions of film endings are rot13ed to avoid
1697 * spoiling it for people who don't want to be told, we apply a
1698 * keyless, reversible, but visually completely obfuscatory masking
1699 * function to the mine bitmap.
1701 static void obfuscate_bitmap(unsigned char *bmp
, int bits
, int decode
)
1703 int bytes
, firsthalf
, secondhalf
;
1705 unsigned char *seedstart
;
1707 unsigned char *targetstart
;
1713 * My obfuscation algorithm is similar in concept to the OAEP
1714 * encoding used in some forms of RSA. Here's a specification
1717 * + We have a `masking function' which constructs a stream of
1718 * pseudorandom bytes from a seed of some number of input
1721 * + We pad out our input bit stream to a whole number of
1722 * bytes by adding up to 7 zero bits on the end. (In fact
1723 * the bitmap passed as input to this function will already
1724 * have had this done in practice.)
1726 * + We divide the _byte_ stream exactly in half, rounding the
1727 * half-way position _down_. So an 81-bit input string, for
1728 * example, rounds up to 88 bits or 11 bytes, and then
1729 * dividing by two gives 5 bytes in the first half and 6 in
1732 * + We generate a mask from the second half of the bytes, and
1733 * XOR it over the first half.
1735 * + We generate a mask from the (encoded) first half of the
1736 * bytes, and XOR it over the second half. Any null bits at
1737 * the end which were added as padding are cleared back to
1738 * zero even if this operation would have made them nonzero.
1740 * To de-obfuscate, the steps are precisely the same except
1741 * that the final two are reversed.
1743 * Finally, our masking function. Given an input seed string of
1744 * bytes, the output mask consists of concatenating the SHA-1
1745 * hashes of the seed string and successive decimal integers,
1749 bytes
= (bits
+ 7) / 8;
1750 firsthalf
= bytes
/ 2;
1751 secondhalf
= bytes
- firsthalf
;
1753 steps
[decode ?
1 : 0].seedstart
= bmp
+ firsthalf
;
1754 steps
[decode ?
1 : 0].seedlen
= secondhalf
;
1755 steps
[decode ?
1 : 0].targetstart
= bmp
;
1756 steps
[decode ?
1 : 0].targetlen
= firsthalf
;
1758 steps
[decode ?
0 : 1].seedstart
= bmp
;
1759 steps
[decode ?
0 : 1].seedlen
= firsthalf
;
1760 steps
[decode ?
0 : 1].targetstart
= bmp
+ firsthalf
;
1761 steps
[decode ?
0 : 1].targetlen
= secondhalf
;
1763 for (i
= 0; i
< 2; i
++) {
1764 SHA_State base
, final
;
1765 unsigned char digest
[20];
1767 int digestpos
= 20, counter
= 0;
1770 SHA_Bytes(&base
, steps
[i
].seedstart
, steps
[i
].seedlen
);
1772 for (j
= 0; j
< steps
[i
].targetlen
; j
++) {
1773 if (digestpos
>= 20) {
1774 sprintf(numberbuf
, "%d", counter
++);
1776 SHA_Bytes(&final
, numberbuf
, strlen(numberbuf
));
1777 SHA_Final(&final
, digest
);
1780 steps
[i
].targetstart
[j
] ^= digest
[digestpos
]++;
1784 * Mask off the pad bits in the final byte after both steps.
1787 bmp
[bits
/ 8] &= 0xFF & (0xFF00 >> (bits
% 8));
1791 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1792 game_aux_info
**aux
)
1794 char *grid
, *ret
, *p
;
1799 * FIXME: allow user to specify initial open square.
1801 x
= random_upto(rs
, params
->w
);
1802 y
= random_upto(rs
, params
->h
);
1804 grid
= minegen(params
->w
, params
->h
, params
->n
, x
, y
, params
->unique
, rs
);
1807 * Set up the mine bitmap and obfuscate it.
1809 area
= params
->w
* params
->h
;
1810 bmp
= snewn((area
+ 7) / 8, unsigned char);
1811 memset(bmp
, 0, (area
+ 7) / 8);
1812 for (i
= 0; i
< area
; i
++) {
1814 bmp
[i
/ 8] |= 0x80 >> (i
% 8);
1816 obfuscate_bitmap(bmp
, area
, FALSE
);
1819 * Now encode the resulting bitmap in hex. We can work to
1820 * nibble rather than byte granularity, since the obfuscation
1821 * function guarantees to return a bit string of the same
1822 * length as its input.
1824 ret
= snewn((area
+3)/4 + 100, char);
1825 p
= ret
+ sprintf(ret
, "%d,%d,m", x
, y
); /* 'm' == masked */
1826 for (i
= 0; i
< (area
+3)/4; i
++) {
1830 *p
++ = "0123456789abcdef"[v
& 0xF];
1839 static void game_free_aux_info(game_aux_info
*aux
)
1841 assert(!"Shouldn't happen");
1844 static char *validate_desc(game_params
*params
, char *desc
)
1846 int wh
= params
->w
* params
->h
;
1849 if (!*desc
|| !isdigit((unsigned char)*desc
))
1850 return "No initial x-coordinate in game description";
1852 if (x
< 0 || x
>= params
->w
)
1853 return "Initial x-coordinate was out of range";
1854 while (*desc
&& isdigit((unsigned char)*desc
))
1855 desc
++; /* skip over x coordinate */
1857 return "No ',' after initial x-coordinate in game description";
1858 desc
++; /* eat comma */
1859 if (!*desc
|| !isdigit((unsigned char)*desc
))
1860 return "No initial y-coordinate in game description";
1862 if (y
< 0 || y
>= params
->h
)
1863 return "Initial y-coordinate was out of range";
1864 while (*desc
&& isdigit((unsigned char)*desc
))
1865 desc
++; /* skip over y coordinate */
1867 return "No ',' after initial y-coordinate in game description";
1868 desc
++; /* eat comma */
1869 /* eat `m', meaning `masked', if present */
1872 /* now just check length of remainder */
1873 if (strlen(desc
) != (wh
+3)/4)
1874 return "Game description is wrong length";
1879 static int open_square(game_state
*state
, int x
, int y
)
1881 int w
= state
->w
, h
= state
->h
;
1882 int xx
, yy
, nmines
, ncovered
;
1884 if (state
->mines
[y
*w
+x
]) {
1886 * The player has landed on a mine. Bad luck. Expose all
1890 for (yy
= 0; yy
< h
; yy
++)
1891 for (xx
= 0; xx
< w
; xx
++) {
1892 if (state
->mines
[yy
*w
+xx
] &&
1893 (state
->grid
[yy
*w
+xx
] == -2 ||
1894 state
->grid
[yy
*w
+xx
] == -3)) {
1895 state
->grid
[yy
*w
+xx
] = 64;
1897 if (!state
->mines
[yy
*w
+xx
] &&
1898 state
->grid
[yy
*w
+xx
] == -1) {
1899 state
->grid
[yy
*w
+xx
] = 66;
1902 state
->grid
[y
*w
+x
] = 65;
1907 * Otherwise, the player has opened a safe square. Mark it to-do.
1909 state
->grid
[y
*w
+x
] = -10; /* `todo' value internal to this func */
1912 * Now go through the grid finding all `todo' values and
1913 * opening them. Every time one of them turns out to have no
1914 * neighbouring mines, we add all its unopened neighbours to
1917 * FIXME: We really ought to be able to do this better than
1918 * using repeated N^2 scans of the grid.
1921 int done_something
= FALSE
;
1923 for (yy
= 0; yy
< h
; yy
++)
1924 for (xx
= 0; xx
< w
; xx
++)
1925 if (state
->grid
[yy
*w
+xx
] == -10) {
1928 assert(!state
->mines
[yy
*w
+xx
]);
1932 for (dx
= -1; dx
<= +1; dx
++)
1933 for (dy
= -1; dy
<= +1; dy
++)
1934 if (xx
+dx
>= 0 && xx
+dx
< state
->w
&&
1935 yy
+dy
>= 0 && yy
+dy
< state
->h
&&
1936 state
->mines
[(yy
+dy
)*w
+(xx
+dx
)])
1939 state
->grid
[yy
*w
+xx
] = v
;
1942 for (dx
= -1; dx
<= +1; dx
++)
1943 for (dy
= -1; dy
<= +1; dy
++)
1944 if (xx
+dx
>= 0 && xx
+dx
< state
->w
&&
1945 yy
+dy
>= 0 && yy
+dy
< state
->h
&&
1946 state
->grid
[(yy
+dy
)*w
+(xx
+dx
)] == -2)
1947 state
->grid
[(yy
+dy
)*w
+(xx
+dx
)] = -10;
1950 done_something
= TRUE
;
1953 if (!done_something
)
1958 * Finally, scan the grid and see if exactly as many squares
1959 * are still covered as there are mines. If so, set the `won'
1960 * flag and fill in mine markers on all covered squares.
1962 nmines
= ncovered
= 0;
1963 for (yy
= 0; yy
< h
; yy
++)
1964 for (xx
= 0; xx
< w
; xx
++) {
1965 if (state
->grid
[yy
*w
+xx
] < 0)
1967 if (state
->mines
[yy
*w
+xx
])
1970 assert(ncovered
>= nmines
);
1971 if (ncovered
== nmines
) {
1972 for (yy
= 0; yy
< h
; yy
++)
1973 for (xx
= 0; xx
< w
; xx
++) {
1974 if (state
->grid
[yy
*w
+xx
] < 0)
1975 state
->grid
[yy
*w
+xx
] = -1;
1983 static game_state
*new_game(game_params
*params
, char *desc
)
1985 game_state
*state
= snew(game_state
);
1986 int i
, wh
, x
, y
, ret
, masked
;
1989 state
->w
= params
->w
;
1990 state
->h
= params
->h
;
1991 state
->n
= params
->n
;
1992 state
->dead
= state
->won
= FALSE
;
1994 wh
= state
->w
* state
->h
;
1995 state
->mines
= snewn(wh
, char);
1998 while (*desc
&& isdigit((unsigned char)*desc
))
1999 desc
++; /* skip over x coordinate */
2000 if (*desc
) desc
++; /* eat comma */
2002 while (*desc
&& isdigit((unsigned char)*desc
))
2003 desc
++; /* skip over y coordinate */
2004 if (*desc
) desc
++; /* eat comma */
2011 * We permit game IDs to be entered by hand without the
2012 * masking transformation.
2017 bmp
= snewn((wh
+ 7) / 8, unsigned char);
2018 memset(bmp
, 0, (wh
+ 7) / 8);
2019 for (i
= 0; i
< (wh
+3)/4; i
++) {
2023 assert(c
!= 0); /* validate_desc should have caught */
2024 if (c
>= '0' && c
<= '9')
2026 else if (c
>= 'a' && c
<= 'f')
2028 else if (c
>= 'A' && c
<= 'F')
2033 bmp
[i
/ 2] |= v
<< (4 * (1 - (i
% 2)));
2037 obfuscate_bitmap(bmp
, wh
, TRUE
);
2039 memset(state
->mines
, 0, wh
);
2040 for (i
= 0; i
< wh
; i
++) {
2041 if (bmp
[i
/ 8] & (0x80 >> (i
% 8)))
2042 state
->mines
[i
] = 1;
2045 state
->grid
= snewn(wh
, char);
2046 memset(state
->grid
, -2, wh
);
2048 ret
= open_square(state
, x
, y
);
2050 * FIXME: This shouldn't be an assert. Perhaps we actually
2051 * ought to check it in validate_params! Alternatively, we can
2052 * remove the assert completely and actually permit a game
2053 * description to start you off dead.
2060 static game_state
*dup_game(game_state
*state
)
2062 game_state
*ret
= snew(game_state
);
2067 ret
->dead
= state
->dead
;
2068 ret
->won
= state
->won
;
2069 ret
->mines
= snewn(ret
->w
* ret
->h
, char);
2070 memcpy(ret
->mines
, state
->mines
, ret
->w
* ret
->h
);
2071 ret
->grid
= snewn(ret
->w
* ret
->h
, char);
2072 memcpy(ret
->grid
, state
->grid
, ret
->w
* ret
->h
);
2077 static void free_game(game_state
*state
)
2079 sfree(state
->mines
);
2084 static game_state
*solve_game(game_state
*state
, game_aux_info
*aux
,
2090 static char *game_text_format(game_state
*state
)
2096 int hx
, hy
, hradius
; /* for mouse-down highlights */
2100 static game_ui
*new_ui(game_state
*state
)
2102 game_ui
*ui
= snew(game_ui
);
2103 ui
->hx
= ui
->hy
= -1;
2105 ui
->flash_is_death
= FALSE
; /* *shrug* */
2109 static void free_ui(game_ui
*ui
)
2114 static game_state
*make_move(game_state
*from
, game_ui
*ui
, int x
, int y
,
2120 if (from
->dead
|| from
->won
)
2121 return NULL
; /* no further moves permitted */
2123 if (!IS_MOUSE_DOWN(button
) && !IS_MOUSE_DRAG(button
) &&
2124 !IS_MOUSE_RELEASE(button
))
2129 if (cx
< 0 || cx
>= from
->w
|| cy
< 0 || cy
> from
->h
)
2132 if (button
== LEFT_BUTTON
|| button
== LEFT_DRAG
) {
2134 * Mouse-downs and mouse-drags just cause highlighting
2139 ui
->hradius
= (from
->grid
[cy
*from
->w
+cx
] >= 0 ?
1 : 0);
2143 if (button
== RIGHT_BUTTON
) {
2145 * Right-clicking only works on a covered square, and it
2146 * toggles between -1 (marked as mine) and -2 (not marked
2149 * FIXME: question marks.
2151 if (from
->grid
[cy
* from
->w
+ cx
] != -2 &&
2152 from
->grid
[cy
* from
->w
+ cx
] != -1)
2155 ret
= dup_game(from
);
2156 ret
->grid
[cy
* from
->w
+ cx
] ^= (-2 ^ -1);
2161 if (button
== LEFT_RELEASE
) {
2162 ui
->hx
= ui
->hy
= -1;
2166 * At this stage we must never return NULL: we have adjusted
2167 * the ui, so at worst we return `from'.
2171 * Left-clicking on a covered square opens a tile. Not
2172 * permitted if the tile is marked as a mine, for safety.
2173 * (Unmark it and _then_ open it.)
2175 if (from
->grid
[cy
* from
->w
+ cx
] == -2 ||
2176 from
->grid
[cy
* from
->w
+ cx
] == -3) {
2177 ret
= dup_game(from
);
2178 open_square(ret
, cx
, cy
);
2183 * Left-clicking on an uncovered tile: first we check to see if
2184 * the number of mine markers surrounding the tile is equal to
2185 * its mine count, and if so then we open all other surrounding
2188 if (from
->grid
[cy
* from
->w
+ cx
] > 0) {
2191 /* Count mine markers. */
2193 for (dy
= -1; dy
<= +1; dy
++)
2194 for (dx
= -1; dx
<= +1; dx
++)
2195 if (cx
+dx
>= 0 && cx
+dx
< from
->w
&&
2196 cy
+dy
>= 0 && cy
+dy
< from
->h
) {
2197 if (from
->grid
[(cy
+dy
)*from
->w
+(cx
+dx
)] == -1)
2201 if (n
== from
->grid
[cy
* from
->w
+ cx
]) {
2202 ret
= dup_game(from
);
2203 for (dy
= -1; dy
<= +1; dy
++)
2204 for (dx
= -1; dx
<= +1; dx
++)
2205 if (cx
+dx
>= 0 && cx
+dx
< ret
->w
&&
2206 cy
+dy
>= 0 && cy
+dy
< ret
->h
&&
2207 (ret
->grid
[(cy
+dy
)*ret
->w
+(cx
+dx
)] == -2 ||
2208 ret
->grid
[(cy
+dy
)*ret
->w
+(cx
+dx
)] == -3))
2209 open_square(ret
, cx
+dx
, cy
+dy
);
2220 /* ----------------------------------------------------------------------
2224 struct game_drawstate
{
2228 * Items in this `grid' array have all the same values as in
2229 * the game_state grid, and in addition:
2231 * - -10 means the tile was drawn `specially' as a result of a
2232 * flash, so it will always need redrawing.
2234 * - -22 and -23 mean the tile is highlighted for a possible
2239 static void game_size(game_params
*params
, int *x
, int *y
)
2241 *x
= BORDER
* 2 + TILE_SIZE
* params
->w
;
2242 *y
= BORDER
* 2 + TILE_SIZE
* params
->h
;
2245 static float *game_colours(frontend
*fe
, game_state
*state
, int *ncolours
)
2247 float *ret
= snewn(3 * NCOLOURS
, float);
2249 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
2251 ret
[COL_1
* 3 + 0] = 0.0F
;
2252 ret
[COL_1
* 3 + 1] = 0.0F
;
2253 ret
[COL_1
* 3 + 2] = 1.0F
;
2255 ret
[COL_2
* 3 + 0] = 0.0F
;
2256 ret
[COL_2
* 3 + 1] = 0.5F
;
2257 ret
[COL_2
* 3 + 2] = 0.0F
;
2259 ret
[COL_3
* 3 + 0] = 1.0F
;
2260 ret
[COL_3
* 3 + 1] = 0.0F
;
2261 ret
[COL_3
* 3 + 2] = 0.0F
;
2263 ret
[COL_4
* 3 + 0] = 0.0F
;
2264 ret
[COL_4
* 3 + 1] = 0.0F
;
2265 ret
[COL_4
* 3 + 2] = 0.5F
;
2267 ret
[COL_5
* 3 + 0] = 0.5F
;
2268 ret
[COL_5
* 3 + 1] = 0.0F
;
2269 ret
[COL_5
* 3 + 2] = 0.0F
;
2271 ret
[COL_6
* 3 + 0] = 0.0F
;
2272 ret
[COL_6
* 3 + 1] = 0.5F
;
2273 ret
[COL_6
* 3 + 2] = 0.5F
;
2275 ret
[COL_7
* 3 + 0] = 0.0F
;
2276 ret
[COL_7
* 3 + 1] = 0.0F
;
2277 ret
[COL_7
* 3 + 2] = 0.0F
;
2279 ret
[COL_8
* 3 + 0] = 0.5F
;
2280 ret
[COL_8
* 3 + 1] = 0.5F
;
2281 ret
[COL_8
* 3 + 2] = 0.5F
;
2283 ret
[COL_MINE
* 3 + 0] = 0.0F
;
2284 ret
[COL_MINE
* 3 + 1] = 0.0F
;
2285 ret
[COL_MINE
* 3 + 2] = 0.0F
;
2287 ret
[COL_BANG
* 3 + 0] = 1.0F
;
2288 ret
[COL_BANG
* 3 + 1] = 0.0F
;
2289 ret
[COL_BANG
* 3 + 2] = 0.0F
;
2291 ret
[COL_CROSS
* 3 + 0] = 1.0F
;
2292 ret
[COL_CROSS
* 3 + 1] = 0.0F
;
2293 ret
[COL_CROSS
* 3 + 2] = 0.0F
;
2295 ret
[COL_FLAG
* 3 + 0] = 1.0F
;
2296 ret
[COL_FLAG
* 3 + 1] = 0.0F
;
2297 ret
[COL_FLAG
* 3 + 2] = 0.0F
;
2299 ret
[COL_FLAGBASE
* 3 + 0] = 0.0F
;
2300 ret
[COL_FLAGBASE
* 3 + 1] = 0.0F
;
2301 ret
[COL_FLAGBASE
* 3 + 2] = 0.0F
;
2303 ret
[COL_QUERY
* 3 + 0] = 0.0F
;
2304 ret
[COL_QUERY
* 3 + 1] = 0.0F
;
2305 ret
[COL_QUERY
* 3 + 2] = 0.0F
;
2307 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
2308 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
2309 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
2311 ret
[COL_LOWLIGHT
* 3 + 0] = ret
[COL_BACKGROUND
* 3 + 0] * 2.0 / 3.0;
2312 ret
[COL_LOWLIGHT
* 3 + 1] = ret
[COL_BACKGROUND
* 3 + 1] * 2.0 / 3.0;
2313 ret
[COL_LOWLIGHT
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2] * 2.0 / 3.0;
2315 *ncolours
= NCOLOURS
;
2319 static game_drawstate
*game_new_drawstate(game_state
*state
)
2321 struct game_drawstate
*ds
= snew(struct game_drawstate
);
2325 ds
->started
= FALSE
;
2326 ds
->grid
= snewn(ds
->w
* ds
->h
, char);
2328 memset(ds
->grid
, -99, ds
->w
* ds
->h
);
2333 static void game_free_drawstate(game_drawstate
*ds
)
2339 static void draw_tile(frontend
*fe
, int x
, int y
, int v
, int bg
)
2345 if (v
== -22 || v
== -23) {
2349 * Omit the highlights in this case.
2351 draw_rect(fe
, x
, y
, TILE_SIZE
, TILE_SIZE
, bg
);
2352 draw_line(fe
, x
, y
, x
+ TILE_SIZE
- 1, y
, COL_LOWLIGHT
);
2353 draw_line(fe
, x
, y
, x
, y
+ TILE_SIZE
- 1, COL_LOWLIGHT
);
2356 * Draw highlights to indicate the square is covered.
2358 coords
[0] = x
+ TILE_SIZE
- 1;
2359 coords
[1] = y
+ TILE_SIZE
- 1;
2360 coords
[2] = x
+ TILE_SIZE
- 1;
2363 coords
[5] = y
+ TILE_SIZE
- 1;
2364 draw_polygon(fe
, coords
, 3, TRUE
, COL_LOWLIGHT
^ hl
);
2365 draw_polygon(fe
, coords
, 3, FALSE
, COL_LOWLIGHT
^ hl
);
2369 draw_polygon(fe
, coords
, 3, TRUE
, COL_HIGHLIGHT
^ hl
);
2370 draw_polygon(fe
, coords
, 3, FALSE
, COL_HIGHLIGHT
^ hl
);
2372 draw_rect(fe
, x
+ HIGHLIGHT_WIDTH
, y
+ HIGHLIGHT_WIDTH
,
2373 TILE_SIZE
- 2*HIGHLIGHT_WIDTH
, TILE_SIZE
- 2*HIGHLIGHT_WIDTH
,
2381 #define SETCOORD(n, dx, dy) do { \
2382 coords[(n)*2+0] = x + TILE_SIZE * (dx); \
2383 coords[(n)*2+1] = y + TILE_SIZE * (dy); \
2385 SETCOORD(0, 0.6, 0.35);
2386 SETCOORD(1, 0.6, 0.7);
2387 SETCOORD(2, 0.8, 0.8);
2388 SETCOORD(3, 0.25, 0.8);
2389 SETCOORD(4, 0.55, 0.7);
2390 SETCOORD(5, 0.55, 0.35);
2391 draw_polygon(fe
, coords
, 6, TRUE
, COL_FLAGBASE
);
2392 draw_polygon(fe
, coords
, 6, FALSE
, COL_FLAGBASE
);
2394 SETCOORD(0, 0.6, 0.2);
2395 SETCOORD(1, 0.6, 0.5);
2396 SETCOORD(2, 0.2, 0.35);
2397 draw_polygon(fe
, coords
, 3, TRUE
, COL_FLAG
);
2398 draw_polygon(fe
, coords
, 3, FALSE
, COL_FLAG
);
2401 } else if (v
== -3) {
2403 * Draw a question mark.
2405 draw_text(fe
, x
+ TILE_SIZE
/ 2, y
+ TILE_SIZE
/ 2,
2406 FONT_VARIABLE
, TILE_SIZE
* 6 / 8,
2407 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
2412 * Clear the square to the background colour, and draw thin
2413 * grid lines along the top and left.
2415 * Exception is that for value 65 (mine we've just trodden
2416 * on), we clear the square to COL_BANG.
2418 draw_rect(fe
, x
, y
, TILE_SIZE
, TILE_SIZE
,
2419 (v
== 65 ? COL_BANG
: bg
));
2420 draw_line(fe
, x
, y
, x
+ TILE_SIZE
- 1, y
, COL_LOWLIGHT
);
2421 draw_line(fe
, x
, y
, x
, y
+ TILE_SIZE
- 1, COL_LOWLIGHT
);
2423 if (v
> 0 && v
<= 8) {
2430 draw_text(fe
, x
+ TILE_SIZE
/ 2, y
+ TILE_SIZE
/ 2,
2431 FONT_VARIABLE
, TILE_SIZE
* 7 / 8,
2432 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
2433 (COL_1
- 1) + v
, str
);
2435 } else if (v
>= 64) {
2439 * FIXME: this could be done better!
2442 draw_text(fe
, x
+ TILE_SIZE
/ 2, y
+ TILE_SIZE
/ 2,
2443 FONT_VARIABLE
, TILE_SIZE
* 7 / 8,
2444 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
2448 int cx
= x
+ TILE_SIZE
/ 2;
2449 int cy
= y
+ TILE_SIZE
/ 2;
2450 int r
= TILE_SIZE
/ 2 - 3;
2452 int xdx
= 1, xdy
= 0, ydx
= 0, ydy
= 1;
2455 for (i
= 0; i
< 4*5*2; i
+= 5*2) {
2456 coords
[i
+2*0+0] = cx
- r
/6*xdx
+ r
*4/5*ydx
;
2457 coords
[i
+2*0+1] = cy
- r
/6*xdy
+ r
*4/5*ydy
;
2458 coords
[i
+2*1+0] = cx
- r
/6*xdx
+ r
*ydx
;
2459 coords
[i
+2*1+1] = cy
- r
/6*xdy
+ r
*ydy
;
2460 coords
[i
+2*2+0] = cx
+ r
/6*xdx
+ r
*ydx
;
2461 coords
[i
+2*2+1] = cy
+ r
/6*xdy
+ r
*ydy
;
2462 coords
[i
+2*3+0] = cx
+ r
/6*xdx
+ r
*4/5*ydx
;
2463 coords
[i
+2*3+1] = cy
+ r
/6*xdy
+ r
*4/5*ydy
;
2464 coords
[i
+2*4+0] = cx
+ r
*3/5*xdx
+ r
*3/5*ydx
;
2465 coords
[i
+2*4+1] = cy
+ r
*3/5*xdy
+ r
*3/5*ydy
;
2475 draw_polygon(fe
, coords
, 5*4, TRUE
, COL_MINE
);
2476 draw_polygon(fe
, coords
, 5*4, FALSE
, COL_MINE
);
2478 draw_rect(fe
, cx
-r
/3, cy
-r
/3, r
/3, r
/4, COL_HIGHLIGHT
);
2484 * Cross through the mine.
2487 for (dx
= -1; dx
<= +1; dx
++) {
2488 draw_line(fe
, x
+ 3 + dx
, y
+ 2,
2489 x
+ TILE_SIZE
- 3 + dx
,
2490 y
+ TILE_SIZE
- 2, COL_CROSS
);
2491 draw_line(fe
, x
+ TILE_SIZE
- 3 + dx
, y
+ 2,
2492 x
+ 3 + dx
, y
+ TILE_SIZE
- 2,
2499 draw_update(fe
, x
, y
, TILE_SIZE
, TILE_SIZE
);
2502 static void game_redraw(frontend
*fe
, game_drawstate
*ds
, game_state
*oldstate
,
2503 game_state
*state
, int dir
, game_ui
*ui
,
2504 float animtime
, float flashtime
)
2507 int mines
, markers
, bg
;
2510 int frame
= (flashtime
/ FLASH_FRAME
);
2512 bg
= (ui
->flash_is_death ? COL_BACKGROUND
: COL_LOWLIGHT
);
2514 bg
= (ui
->flash_is_death ? COL_BANG
: COL_HIGHLIGHT
);
2516 bg
= COL_BACKGROUND
;
2522 TILE_SIZE
* state
->w
+ 2 * BORDER
,
2523 TILE_SIZE
* state
->h
+ 2 * BORDER
, COL_BACKGROUND
);
2524 draw_update(fe
, 0, 0,
2525 TILE_SIZE
* state
->w
+ 2 * BORDER
,
2526 TILE_SIZE
* state
->h
+ 2 * BORDER
);
2529 * Recessed area containing the whole puzzle.
2531 coords
[0] = COORD(state
->w
) + OUTER_HIGHLIGHT_WIDTH
- 1;
2532 coords
[1] = COORD(state
->h
) + OUTER_HIGHLIGHT_WIDTH
- 1;
2533 coords
[2] = COORD(state
->w
) + OUTER_HIGHLIGHT_WIDTH
- 1;
2534 coords
[3] = COORD(0) - OUTER_HIGHLIGHT_WIDTH
;
2535 coords
[4] = COORD(0) - OUTER_HIGHLIGHT_WIDTH
;
2536 coords
[5] = COORD(state
->h
) + OUTER_HIGHLIGHT_WIDTH
- 1;
2537 draw_polygon(fe
, coords
, 3, TRUE
, COL_HIGHLIGHT
);
2538 draw_polygon(fe
, coords
, 3, FALSE
, COL_HIGHLIGHT
);
2540 coords
[1] = COORD(0) - OUTER_HIGHLIGHT_WIDTH
;
2541 coords
[0] = COORD(0) - OUTER_HIGHLIGHT_WIDTH
;
2542 draw_polygon(fe
, coords
, 3, TRUE
, COL_LOWLIGHT
);
2543 draw_polygon(fe
, coords
, 3, FALSE
, COL_LOWLIGHT
);
2549 * Now draw the tiles. Also in this loop, count up the number
2550 * of mines and mine markers.
2552 mines
= markers
= 0;
2553 for (y
= 0; y
< ds
->h
; y
++)
2554 for (x
= 0; x
< ds
->w
; x
++) {
2555 int v
= state
->grid
[y
*ds
->w
+x
];
2559 if (state
->mines
[y
*ds
->w
+x
])
2562 if ((v
== -2 || v
== -3) &&
2563 (abs(x
-ui
->hx
) <= ui
->hradius
&& abs(y
-ui
->hy
) <= ui
->hradius
))
2566 if (ds
->grid
[y
*ds
->w
+x
] != v
|| bg
!= COL_BACKGROUND
) {
2567 draw_tile(fe
, COORD(x
), COORD(y
), v
, bg
);
2568 ds
->grid
[y
*ds
->w
+x
] = (bg
== COL_BACKGROUND ? v
: -10);
2573 * Update the status bar.
2576 char statusbar
[512];
2578 sprintf(statusbar
, "GAME OVER!");
2579 } else if (state
->won
) {
2580 sprintf(statusbar
, "COMPLETED!");
2582 sprintf(statusbar
, "Mines marked: %d / %d", markers
, mines
);
2584 status_bar(fe
, statusbar
);
2588 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
2589 int dir
, game_ui
*ui
)
2594 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
2595 int dir
, game_ui
*ui
)
2597 if (dir
> 0 && !oldstate
->dead
&& !oldstate
->won
) {
2598 if (newstate
->dead
) {
2599 ui
->flash_is_death
= TRUE
;
2600 return 3 * FLASH_FRAME
;
2602 if (newstate
->won
) {
2603 ui
->flash_is_death
= FALSE
;
2604 return 2 * FLASH_FRAME
;
2610 static int game_wants_statusbar(void)
2616 #define thegame mines
2619 const struct game thegame
= {
2620 "Mines", "games.mines",
2627 TRUE
, game_configure
, custom_params
,
2636 FALSE
, game_text_format
,
2643 game_free_drawstate
,
2647 game_wants_statusbar
,