Skip to content

Commit

Permalink
Add toggle flag and fix neighbour mines calculation.
Browse files Browse the repository at this point in the history
  • Loading branch information
jespermb committed Sep 27, 2022
1 parent a8fb789 commit ae22153
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ crate-type = ["cdylib"]
[dependencies]
rand = "0.8.5"
wasm-bindgen = "0.2.83"
getrandom = { version = "0.2", features = ["js"] }
getrandom = { version = "0.2", features = ["js"] }
7 changes: 6 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<body>
<div id="game"></div>
<script type="module">
import init, { getGame, openCell } from "./pkg/MineSweeper.js";
import init, { getGame, openCell, toggleFlag } from "./pkg/MineSweeper.js";
init().then(() => {
render(getGame());
});
Expand Down Expand Up @@ -54,6 +54,11 @@
e.preventDefault();
render(openCell(x, y));
});
element.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
render(toggleFlag(x, y));
return false;
}, false);

gameElement.appendChild(element);
}
Expand Down
7 changes: 4 additions & 3 deletions src/MineSweeper.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::ops::Index;
use std::fmt::{Display, Write};

use crate::random::random_number;
Expand Down Expand Up @@ -92,8 +91,8 @@ impl MineSweeper {
let width = self.width;
let height = self.height;

(x.min(1) - 1..=(x + 1).max(width - 1)).flat_map(move |i| (
y.min(1) - 1..=(y + 1).max(height - 1)).map(move |j| (i, j)
(x.max(1) - 1..=(x + 1).min(width - 1)).flat_map(move |i| (
y.max(1) - 1..=(y + 1).min(height - 1)).map(move |j| (i, j)
)).filter(move |&pos| pos != (x, y))
}

Expand Down Expand Up @@ -127,6 +126,8 @@ mod test {
ms.open_cell((5, 5));
ms.toggle_flag((6, 6));
ms.open_cell((6, 6));
ms.open_cell((1, 1));
ms.open_cell((10, 10));

println!("{}", ms);
}
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ pub fn open_field(x: usize, y:usize) -> String {
return game.borrow().to_string();
})
}

#[wasm_bindgen(js_name = toggleFlag)]
pub fn toggle_flag(x: usize, y:usize) -> String {
GAME.with(|game| {
game.borrow_mut().toggle_flag((x, y));
return game.borrow().to_string();
})
}

0 comments on commit ae22153

Please sign in to comment.