agb/examples/the-dungeon-puzzlers-lament/src/save.rs

48 lines
1.2 KiB
Rust
Raw Normal View History

2024-04-10 07:08:55 +10:00
use agb::external::portable_atomic::{AtomicU32, Ordering};
2023-07-20 02:41:17 +10:00
use agb::{
save::{Error, SaveManager},
Gba,
};
2024-02-18 07:04:03 +11:00
static MAXIMUM_LEVEL: AtomicU32 = AtomicU32::new(0);
2024-04-21 01:18:42 +10:00
static SAVE_OFFSET: usize = 0xFF;
2023-07-20 02:41:17 +10:00
pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
gba.save.init_sram();
let mut access = gba.save.access()?;
let mut buffer = [0; 1];
access.read(0, &mut buffer)?;
if buffer[0] != 0 {
access.prepare_write(0..1)?.write(0, &[0])?;
core::mem::drop(access);
save_max_level(&mut gba.save, 0)?;
} else {
let mut buffer = [0; 4];
2024-04-21 01:18:42 +10:00
access.read(SAVE_OFFSET, &mut buffer)?;
2023-07-20 02:41:17 +10:00
let max_level = u32::from_le_bytes(buffer);
if max_level > 100 {
2024-02-18 07:04:03 +11:00
MAXIMUM_LEVEL.store(0, Ordering::SeqCst)
2023-07-20 02:41:17 +10:00
} else {
2024-02-18 07:04:03 +11:00
MAXIMUM_LEVEL.store(max_level, Ordering::SeqCst)
2023-07-20 02:41:17 +10:00
}
}
Ok(())
}
pub fn load_max_level() -> u32 {
2024-02-18 07:04:03 +11:00
MAXIMUM_LEVEL.load(Ordering::SeqCst)
2023-07-20 02:41:17 +10:00
}
pub fn save_max_level(save: &mut SaveManager, level: u32) -> Result<(), Error> {
save.access()?
2024-04-21 01:18:42 +10:00
.prepare_write(SAVE_OFFSET..SAVE_OFFSET + 4)?
.write(SAVE_OFFSET, &level.to_le_bytes())?;
2024-02-18 07:04:03 +11:00
MAXIMUM_LEVEL.store(level, Ordering::SeqCst);
2023-07-20 02:41:17 +10:00
Ok(())
}