1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
use rand::Rng;
use std::fmt;
#[derive(Clone, Copy)]
struct Cell {
neighbors: u8,
revealed: bool,
flagged: bool,
mine: bool,
}
impl fmt::Display for Cell {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.flagged {
write!(f, "F")?;
}
if !self.revealed {
write!(f, "+")?;
return Ok(());
}
if self.mine {
write!(f, "M")?;
return Ok(());
}
if self.neighbors > 0 {
write!(f, "{}", self.neighbors)?;
} else {
write!(f, "_")?;
}
Ok(())
}
}
#[derive(Clone)]
struct Grid(Vec<Vec<Cell>>);
impl fmt::Display for Grid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for row in self.0.iter() {
for cell in row.iter() {
write!(f, " {} ", cell)?;
}
write!(f, "\n")?;
}
Ok(())
}
}
fn mark_neighbors(grid: &mut Grid, x: usize, y: usize) {
for row in y.saturating_sub(1)..=y.saturating_add(1) {
for col in x.saturating_sub(1)..=x.saturating_add(1) {
if x == col && y == row {
continue;
}
let Some(cell) = grid.0.get_mut(row).and_then(|row| row.get_mut(col)) else {
continue;
};
cell.neighbors += 1;
}
}
}
fn plant_mines(grid: &mut Grid, mines: u8) {
let mut rng = rand::thread_rng();
let mut mines_left = mines;
while mines_left > 0 {
let row = rng.gen_range(0..grid.0.len());
let col = rng.gen_range(0..grid.0[0].len());
let cell: &mut Cell = &mut grid.0[row][col];
if !cell.mine {
mines_left -= 1;
cell.mine = true;
mark_neighbors(grid, col, row);
}
}
}
fn main() {
let mut grid = Grid(vec![
vec![
Cell {
neighbors: 0,
flagged: false,
mine: false,
revealed: false,
};
9
];
9
]);
plant_mines(&mut grid, 10);
println!("{}", grid);
}
|