Skip to content

Commit 89d3ca0

Browse files
Simplify game state handling logic
1 parent bab125e commit 89d3ca0

File tree

1 file changed

+26
-35
lines changed
  • minesweeper/src/minesweeper_logic

1 file changed

+26
-35
lines changed

minesweeper/src/minesweeper_logic/game.rs

Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -60,48 +60,43 @@ impl Game {
6060
}
6161
}
6262

63-
fn start_game_if_needed(&mut self) {
64-
if self.state != GameState::NotStarted {
65-
return;
63+
fn start_game_if_needed(&mut self) -> Result<(), &'static str> {
64+
match self.state {
65+
GameState::Started => Ok(()),
66+
GameState::NotStarted => {
67+
self.stopwatch.start();
68+
self.state = GameState::Started;
69+
Ok(())
70+
}
71+
GameState::Stopped { win: _ } => Err(GAME_IS_ALREADY_STOPPED_ERROR),
6672
}
67-
68-
self.stopwatch.start();
69-
self.state = GameState::Started;
7073
}
7174

7275
fn stop_game(&mut self, win: bool) {
7376
self.stopwatch.stop();
7477
self.state = GameState::Stopped { win };
7578
}
7679

77-
fn is_running(&self) -> bool {
78-
self.state == GameState::Started
79-
}
80-
8180
fn execute_open(
8281
&mut self,
8382
open_func: impl Fn(&mut dyn Table) -> Result<OpenInfo, &'static str>,
8483
) -> Result<OpenInfo, &'static str> {
85-
self.start_game_if_needed();
86-
87-
if self.is_running() {
88-
let open_info = open_func(&mut *self.table)?;
89-
match open_info.result {
90-
OpenResult::WINNER => {
91-
self.state = GameState::Stopped { win: true };
92-
self.stop_game(true);
93-
}
94-
OpenResult::Boom => {
95-
self.state = GameState::Stopped { win: false };
96-
self.stop_game(false);
97-
}
98-
_ => (),
99-
};
84+
self.start_game_if_needed()?;
10085

101-
Ok(open_info)
102-
} else {
103-
Err(GAME_IS_ALREADY_STOPPED_ERROR)
104-
}
86+
let open_info = open_func(&mut *self.table)?;
87+
match open_info.result {
88+
OpenResult::WINNER => {
89+
self.state = GameState::Stopped { win: true };
90+
self.stop_game(true);
91+
}
92+
OpenResult::Boom => {
93+
self.state = GameState::Stopped { win: false };
94+
self.stop_game(false);
95+
}
96+
_ => (),
97+
};
98+
99+
Ok(open_info)
105100
}
106101

107102
pub fn open(&mut self, row: SizeType, col: SizeType) -> Result<OpenInfo, &'static str> {
@@ -121,13 +116,9 @@ impl Game {
121116
row: SizeType,
122117
col: SizeType,
123118
) -> Result<FlagResult, &'static str> {
124-
self.start_game_if_needed();
119+
self.start_game_if_needed()?;
125120

126-
if self.is_running() {
127-
self.table.toggle_flag(row, col)
128-
} else {
129-
Err(GAME_IS_ALREADY_STOPPED_ERROR)
130-
}
121+
self.table.toggle_flag(row, col)
131122
}
132123

133124
pub fn width(&self) -> SizeType {

0 commit comments

Comments
 (0)