Skip to content

Commit a5aefd8

Browse files
authored
Function memory game improvements (#3972)
update best_score immediately and optimize card cloning
1 parent bce22e0 commit a5aefd8

File tree

1 file changed

+13
-5
lines changed
  • examples/function_memory_game/src

1 file changed

+13
-5
lines changed

examples/function_memory_game/src/state.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub struct Card {
2323
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2424
pub struct State {
2525
pub unresolved_card_pairs: u8,
26-
pub best_score: u32,
26+
pub best_score: u32, // seconds to solve
2727
pub status: Status,
2828
pub cards: Vec<Card>,
2929
pub last_card: Option<RawCard>,
@@ -67,7 +67,7 @@ impl Reducible for State {
6767
unresolved_card_pairs: self.unresolved_card_pairs,
6868
best_score: self.best_score,
6969
status,
70-
cards: cards.clone(),
70+
cards,
7171
last_card: Some(card),
7272
rollback_cards: None,
7373
},
@@ -90,7 +90,7 @@ impl Reducible for State {
9090
unresolved_card_pairs,
9191
best_score: self.best_score,
9292
status,
93-
cards: cards.clone(),
93+
cards,
9494
last_card: None,
9595
rollback_cards,
9696
}
@@ -126,8 +126,16 @@ impl Reducible for State {
126126
.into()
127127
}
128128
Action::TrySaveBestScore(sec_past) => {
129-
(self.best_score > sec_past).then(|| LocalStorage::set(KEY_BEST_SCORE, sec_past));
130-
self
129+
if sec_past < self.best_score {
130+
let _ = LocalStorage::set(KEY_BEST_SCORE, sec_past);
131+
State {
132+
best_score: sec_past,
133+
..self.as_ref().clone()
134+
}
135+
.into()
136+
} else {
137+
self // No update needed, return existing state
138+
}
131139
}
132140
Action::GameReset => State::reset().into(),
133141
}

0 commit comments

Comments
 (0)