feat: fields which have all bombs already flags can be auto opened
This commit is contained in:
parent
038c2d8257
commit
2697fe0899
@ -1,3 +1,12 @@
|
||||
# Minesweeper using Rust & WASM
|
||||
|
||||
Tutorial: https://www.youtube.com/watch?v=0ywizYLPV00
|
||||
|
||||
## Development
|
||||
|
||||
```
|
||||
wasm-pack build --target web
|
||||
serve
|
||||
```
|
||||
|
||||
If it says that you don't have `serve`, you can install from here: https://www.npmjs.com/package/serve.
|
||||
|
||||
@ -23,7 +23,7 @@ html {
|
||||
<body>
|
||||
<div id="root">
|
||||
<script type="module">
|
||||
import init, { getState, openField } from "./pkg/rust_wasm_minesweeper.js";
|
||||
import init, { getState, openField, toggleFlag } from "./pkg/rust_wasm_minesweeper.js";
|
||||
|
||||
async function main() {
|
||||
await init();
|
||||
@ -50,6 +50,12 @@ html {
|
||||
openField(x, y);
|
||||
render();
|
||||
});
|
||||
|
||||
elem.addEventListener("contextmenu", e => {
|
||||
e.preventDefault();
|
||||
toggleFlag(x, y);
|
||||
render();
|
||||
});
|
||||
root.appendChild(elem);
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,3 +19,8 @@ pub fn get_state() -> String {
|
||||
pub fn open_field(x: usize, y: usize) {
|
||||
MINESWEEPER.with(move |ms| ms.borrow_mut().open((x, y)));
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = toggleFlag)]
|
||||
pub fn toggle_flag(x: usize, y: usize) {
|
||||
MINESWEEPER.with(|ms| ms.borrow_mut().toggle_flag((x, y)));
|
||||
}
|
||||
|
||||
@ -75,8 +75,29 @@ impl Minesweeper {
|
||||
.count() as u8
|
||||
}
|
||||
|
||||
pub fn count_flags(&self, position: Position) -> u8 {
|
||||
self.iter_neighbours(position)
|
||||
.filter(|pos| self.flags.contains(pos))
|
||||
.count() as u8
|
||||
}
|
||||
|
||||
pub fn open(&mut self, position: Position) -> Option<OpenResult> {
|
||||
if self.game_over || self.open_fields.contains(&position) || self.flags.contains(&position) {
|
||||
if self.open_fields.contains(&position) {
|
||||
let mines = self.count_mines(position);
|
||||
let flags = self.count_flags(position);
|
||||
|
||||
if mines == flags {
|
||||
for neighbour in self.iter_neighbours(position) {
|
||||
if !self.flags.contains(&neighbour) && !self.open_fields.contains(&neighbour) {
|
||||
self.open(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.game_over || self.flags.contains(&position) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@ -89,7 +110,9 @@ impl Minesweeper {
|
||||
let mines = self.count_mines(position);
|
||||
if mines == 0 {
|
||||
for neighbour in self.iter_neighbours(position) {
|
||||
self.open(neighbour);
|
||||
if !self.open_fields.contains(&neighbour) {
|
||||
self.open(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(OpenResult::NoMine(mines))
|
||||
|
||||
Loading…
Reference in New Issue
Block a user