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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use crate::timer::Timer;
use crate::types::*;
use crossterm::event;
use rand::prelude::*;
/// Represents the Minesweeper game board and its state.
pub struct Board {
grid: Vec<CellBox>,
/// Board width in cells.
pub width: usize,
/// Board height in cells.
pub height: usize,
/// Timer tracking game duration.
pub timer: Timer,
mines_placed: bool,
mines_to_place: usize,
}
impl Board {
/// Creates a new board with default configuration.
pub fn new() -> Board {
let grid = vec![
CellBox {
kind: CellKind::Number(0),
state: CellState::Hidden,
};
DEFAULT_CONFIG.width * DEFAULT_CONFIG.height
];
Board {
grid,
width: DEFAULT_CONFIG.width,
height: DEFAULT_CONFIG.height,
timer: Timer::new(),
mines_to_place: DEFAULT_CONFIG.mines,
mines_placed: false,
}
}
/// Creates a new board with a custom configuration.
pub fn new_with_config(config: GameConfig) -> Board {
let grid = vec![
CellBox {
kind: CellKind::Number(0),
state: CellState::Hidden,
};
config.width * config.height
];
Board {
grid,
width: config.width,
height: config.height,
timer: Timer::new(),
mines_to_place: config.mines,
mines_placed: false,
}
}
/// Initializes the board, placing mines and calculating numbers.
///
/// Ensures the first click is never a mine.
pub fn initialize_board(&mut self, initial_click_x: isize, initial_click_y: isize) {
let mut rng = rand::rng();
let mut set_index = (0..(self.width * self.height)).collect::<Vec<usize>>();
set_index.shuffle(&mut rng);
for i in 0..self.mines_to_place {
let mut idx = set_index[i];
if (idx % self.width) as isize == initial_click_x
&& (idx as isize - initial_click_x) / self.width as isize == initial_click_y
{
// if the random index is the same as the first clicked cell
// pick the next index in the shuffled list this will always be valid
idx = set_index[self.mines_to_place];
}
self.grid[idx].kind = CellKind::Mine;
let x = (idx % self.width) as isize;
let y = (idx as isize - x) / self.width as isize;
for dy in -1..=1 {
for dx in -1..=1 {
if dx == 0 && dy == 0 {
continue;
}
if let Some(neighbor) = self.get_cell_mut(x + dx, y + dy) {
if let CellKind::Number(ref mut n) = neighbor.kind {
*n += 1;
}
}
}
}
}
self.timer.start();
}
/// Resets the board to its initial state.
pub fn reset(&mut self) {
self.grid.iter_mut().for_each(|cell| {
cell.kind = CellKind::Number(0);
cell.state = CellState::Hidden;
});
self.mines_placed = false;
self.timer.reset();
}
/// Gets a reference to a cell at (x, y).
pub fn get_cell(&self, x: isize, y: isize) -> Option<&CellBox> {
if x >= 0 && x < self.width as isize && y >= 0 && y < self.height as isize {
let index = y * self.width as isize + x;
Some(&self.grid[index as usize])
} else {
None
}
}
/// Gets a mutable reference to a cell at (x, y).
pub fn get_cell_mut(&mut self, x: isize, y: isize) -> Option<&mut CellBox> {
if x >= 0 && x < self.width as isize && y >= 0 && y < self.height as isize {
let index = y * self.width as isize + x;
Some(&mut self.grid[index as usize])
} else {
None
}
}
/// Returns the starting position for rendering the board in the terminal.
pub fn get_board_start_pos(&self) -> (u16, u16) {
let (cols, rows) = crossterm::terminal::size().expect("Failed to get terminal size");
let board_start_x = (cols as i16 - (self.width * 2 + 2) as i16) / 2;
let board_start_y = (rows as i16 - self.height as i16) / 2;
(board_start_x as u16, board_start_y as u16)
}
/// Checks if the win condition is met.
fn check_win_condition(&mut self) -> Option<GameState> {
for cell in self.grid.iter() {
if cell.kind != CellKind::Mine && cell.state != CellState::Revealed {
return None; // Found a non-mine cell that is not revealed
}
}
self.timer.stop();
Some(GameState::Won) // All non-mine cells are revealed
}
/// Reveals adjacent empty cells.
///
/// Returns Some(GameState) if the game state changes (win/loss).
pub fn reveal_adjacent_empty(&mut self, x: isize, y: isize) -> Option<GameState> {
let mut to_reveal = vec![(x, y)];
while let Some((cx, cy)) = to_reveal.pop() {
if let Some(cell) = self.get_cell_mut(cx, cy) {
match cell.state {
CellState::Revealed | CellState::Flagged => continue, // Skip if already revealed or flagged
CellState::Hidden => {
cell.state = CellState::Revealed;
if cell.kind == CellKind::Mine {
self.timer.stop();
return Some(GameState::Lost); // Stop if it's a mine
}
}
}
if cell.kind != CellKind::Number(0) {
continue; // Stop if it's not an empty cell
}
for dy in -1..=1 {
for dx in -1..=1 {
if dx == 0 && dy == 0 {
continue;
}
if let Some(neighbor) = self.get_cell_mut(cx + dx, cy + dy) {
match neighbor.kind {
CellKind::Number(_) => {
to_reveal.push((cx + dx, cy + dy));
}
_ => (), // Do nothing for mines
}
}
}
}
}
}
return self.check_win_condition();
}
/// Reveals all non-flagged adjacent cells around a given cell.
///
/// Returns Some(GameState) if the game state changes (win/loss).
pub fn reveal_non_flagged(&mut self, x: isize, y: isize) -> Option<GameState> {
let mut ret = None;
for dy in -1..=1 {
for dx in -1..=1 {
if dx == 0 && dy == 0 {
continue;
}
if let Some(neighbor) = self.get_cell_mut(x + dx, y + dy) {
if neighbor.state != CellState::Flagged {
ret = self.reveal_adjacent_empty(x + dx, y + dy);
}
}
}
}
if ret.is_none() {
ret = self.check_win_condition();
}
return ret;
}
/// Reveals all mines on the board.
pub fn reveal_all_mines(&mut self) {
for cell in self.grid.iter_mut() {
if cell.kind == CellKind::Mine {
cell.state = CellState::Revealed;
}
}
}
/// Converts mouse event coordinates to board cell coordinates.
fn cell_coords_from_mouse(&self, event: event::MouseEvent) -> Option<(isize, isize)> {
let (board_start_x, board_start_y) = self.get_board_start_pos();
let cell_x = (event.column as isize - board_start_x as isize - 2) / 2;
let cell_y = event.row as isize - board_start_y as isize - 1;
if cell_x >= 0
&& cell_x < self.width as isize
&& cell_y >= 0
&& cell_y < self.height as isize
{
Some((cell_x, cell_y))
} else {
None // Click was outside the board
}
}
/// Handles left mouse click event for revealing cells.
///
/// Returns Some(GameState) if the game state changes (win/loss).
pub fn handle_mouse_left(&mut self, event: event::MouseEvent) -> Option<GameState> {
if let Some((cell_x, cell_y)) = self.cell_coords_from_mouse(event) {
if self.mines_placed == false {
self.initialize_board(cell_x, cell_y);
self.mines_placed = true;
}
if let Some(cell) = self.get_cell_mut(cell_x, cell_y) {
match cell.state {
CellState::Hidden => {
// Only reveal if the cell is hidden
if let Some(game_state_change) = self.reveal_adjacent_empty(cell_x, cell_y)
{
return Some(game_state_change);
};
}
CellState::Revealed => {
// If already revealed, reveal adjacent non-flagged cells if it's a number
if let CellKind::Number(n) = cell.kind {
if n > 0 {
if let Some(game_state_change) =
self.reveal_non_flagged(cell_x, cell_y)
{
return Some(game_state_change);
};
}
}
}
_ => (), // Do nothing if it's already revealed or flagged
};
}
}
None
}
/// Handles right mouse click event for flagging/unflagging cells.
pub fn handle_mouse_right(&mut self, event: event::MouseEvent) {
if let Some((cell_x, cell_y)) = self.cell_coords_from_mouse(event) {
if let Some(cell) = self.get_cell_mut(cell_x, cell_y) {
cell.state = match cell.state {
CellState::Hidden => CellState::Flagged,
CellState::Flagged => CellState::Hidden,
_ => cell.state, // Do nothing if it's already revealed
};
}
}
}
/// Clamps the game configuration values to allowed ranges.
pub fn clamp_config(width: usize, height: usize, mines: usize) -> GameConfig {
let clamped_width = width.clamp(MIN_WIDTH, MAX_WIDTH);
let clamped_height = height.clamp(MIN_HEIGHT, MAX_HEIGHT);
let max_mines = clamped_width * clamped_height - 1; // Ensure at least one cell is free
let clamped_mines = mines.clamp(MIN_MINES, max_mines);
GameConfig {
width: clamped_width,
height: clamped_height,
mines: clamped_mines,
}
}
/// Returns the number of remaining mines to be flagged.
pub fn get_remaining_mines(&self) -> isize {
self.mines_to_place as isize - self.get_flags_count() as isize
}
/// Returns the number of flagged cells.
///
/// Could be cached for performance.
fn get_flags_count(&self) -> usize {
self.grid
.iter()
.filter(|cell| cell.state == CellState::Flagged)
.count()
}
}