agb/examples/hyperspace-roll/src/save.rs

45 lines
1 KiB
Rust
Raw Normal View History

2023-02-24 08:18:29 +11:00
use agb::save::{Error, SaveManager};
use agb::sync::Static;
2022-11-18 08:22:14 +11:00
use agb::Gba;
2022-07-25 06:33:51 +10:00
2022-11-18 08:22:14 +11:00
static HIGH_SCORE: Static<u32> = Static::new(0);
2022-07-25 06:33:51 +10:00
pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
gba.save.init_sram();
2022-07-25 06:33:51 +10:00
let mut access = gba.save.access()?;
2022-07-25 06:33:51 +10:00
let mut buffer = [0; 1];
access.read(0, &mut buffer)?;
2022-07-25 06:33:51 +10:00
if buffer[0] != 0 {
access.prepare_write(0..1)?.write(0, &[0])?;
core::mem::drop(access);
2023-02-24 08:18:29 +11:00
save_high_score(&mut gba.save, 0)?;
} else {
let mut buffer = [0; 4];
access.read(1, &mut buffer)?;
let high_score = u32::from_le_bytes(buffer);
2022-07-25 06:33:51 +10:00
if high_score > 100 {
2022-11-18 08:22:14 +11:00
HIGH_SCORE.write(0)
2022-07-25 06:33:51 +10:00
} else {
2022-11-18 08:22:14 +11:00
HIGH_SCORE.write(high_score)
2022-07-25 06:33:51 +10:00
}
}
Ok(())
2022-07-25 06:33:51 +10:00
}
pub fn load_high_score() -> u32 {
2022-11-18 08:22:14 +11:00
HIGH_SCORE.read()
2022-07-25 06:33:51 +10:00
}
2023-02-24 08:18:29 +11:00
pub fn save_high_score(save: &mut SaveManager, score: u32) -> Result<(), Error> {
save.access()?
2022-11-18 08:22:14 +11:00
.prepare_write(1..5)?
.write(1, &score.to_le_bytes())?;
HIGH_SCORE.write(score);
Ok(())
2022-07-25 06:33:51 +10:00
}