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

44 lines
1.1 KiB
Rust
Raw Normal View History

2024-04-10 07:08:55 +10:00
use agb::external::portable_atomic::{AtomicU32, Ordering};
2023-02-24 08:18:29 +11:00
use agb::save::{Error, SaveManager};
2022-11-18 08:22:14 +11:00
use agb::Gba;
2022-07-25 06:33:51 +10:00
2024-02-18 07:04:03 +11:00
static HIGH_SCORE: AtomicU32 = AtomicU32::new(0);
2024-04-21 01:18:42 +10:00
static SAVE_OFFSET: usize = 1;
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];
2024-04-21 01:18:42 +10:00
access.read(SAVE_OFFSET, &mut buffer)?;
let high_score = u32::from_le_bytes(buffer);
2022-07-25 06:33:51 +10:00
2024-02-18 07:04:03 +11:00
let score = if high_score > 100 { 0 } else { high_score };
HIGH_SCORE.store(score, Ordering::SeqCst);
}
Ok(())
2022-07-25 06:33:51 +10:00
}
pub fn load_high_score() -> u32 {
2024-02-18 07:04:03 +11:00
HIGH_SCORE.load(Ordering::SeqCst)
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()?
2024-04-21 01:18:42 +10:00
.prepare_write(SAVE_OFFSET..SAVE_OFFSET + 4)?
.write(SAVE_OFFSET, &score.to_le_bytes())?;
2024-02-18 07:04:03 +11:00
HIGH_SCORE.store(score, Ordering::SeqCst);
Ok(())
2022-07-25 06:33:51 +10:00
}