Skip to content

Commit

Permalink
fix(win-state): ensure that if remaining unexposed tiles are all bomb…
Browse files Browse the repository at this point in the history
…s the user wins
  • Loading branch information
cpcloud committed Jul 27, 2023
1 parent d4390c9 commit 47ec337
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/sweep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,13 @@ impl Board {
}

pub(crate) fn won(&self) -> bool {
let exposed_or_correctly_flagged = self.seen.len() + self.correctly_flagged_mines;
let nseen = self.seen.len();
let exposed_or_correctly_flagged = nseen + self.correctly_flagged_mines;
let ntiles = self.rows * self.columns;

assert!(exposed_or_correctly_flagged <= ntiles);
ntiles == exposed_or_correctly_flagged

ntiles == exposed_or_correctly_flagged || (self.tiles.len() - nseen) == self.mines
}

fn index_from_coord(&self, (r, c): Coordinate) -> usize {
Expand Down Expand Up @@ -181,6 +184,12 @@ impl Board {
self.tiles.get_mut(index).ok_or(Error::GetTile((i, j)))
}

pub(crate) fn flag_all(&mut self) {
for tile in self.tiles.iter_mut() {
tile.flagged = !tile.exposed && tile.mine;
}
}

pub(crate) fn flag(&mut self, i: usize, j: usize) -> Result<bool, Error> {
let nflagged = self.flagged_cells;
let tile = self.tile(i, j)?;
Expand Down
7 changes: 6 additions & 1 deletion src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ fn align_strings_to_char(strings: &[&str], c: char) -> Vec<String> {
let max_rests = rests.iter().map(|&r| r.len()).max().unwrap();
firsts
.into_iter()
.zip(rests.into_iter())
.zip(rests)
.map(|(first, rest)| format!("{first:>max_firsts$}{rest:<max_rests$}"))
.collect()
}
Expand Down Expand Up @@ -238,6 +238,10 @@ impl App {
self.board.flag(r, c)?;
Ok(())
}

pub(crate) fn flag_all(&mut self) {
self.board.flag_all()
}
}

impl Ui {
Expand Down Expand Up @@ -474,6 +478,7 @@ impl Ui {

// if the user has lost or won, display a banner indicating so
if lost || app.won() {
app.flag_all();
let area = centered_rect(20, 3, final_mines_rect);
frame.render_widget(Clear, area); // this clears out the background
frame.render_widget(
Expand Down

0 comments on commit 47ec337

Please sign in to comment.